You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/app/proxyman/mux/writer.go

86 lines
1.5 KiB

8 years ago
package mux
8 years ago
import (
"v2ray.com/core/common/buf"
8 years ago
"v2ray.com/core/common/net"
8 years ago
"v2ray.com/core/common/serial"
)
8 years ago
8 years ago
type Writer struct {
8 years ago
id uint16
dest net.Destination
writer buf.Writer
followup bool
8 years ago
}
8 years ago
func NewWriter(id uint16, dest net.Destination, writer buf.Writer) *Writer {
return &Writer{
8 years ago
id: id,
dest: dest,
writer: writer,
}
}
8 years ago
func (w *Writer) writeInternal(b *buf.Buffer) error {
8 years ago
meta := FrameMetadata{
SessionID: w.id,
Target: w.dest,
}
if w.followup {
meta.SessionStatus = SessionStatusKeep
} else {
w.followup = true
meta.SessionStatus = SessionStatusNew
8 years ago
}
8 years ago
if b.Len() > 0 {
meta.Option.Add(OptionData)
}
8 years ago
8 years ago
frame := buf.New()
frame.AppendSupplier(meta.AsSupplier())
if b.Len() > 0 {
frame.AppendSupplier(serial.WriteUint16(0))
lengthBytes := frame.BytesFrom(-2)
nBytes, err := frame.Write(b.Bytes())
if err != nil {
frame.Release()
return err
}
serial.Uint16ToBytes(uint16(nBytes), lengthBytes[:0])
b.SliceFrom(nBytes)
8 years ago
}
8 years ago
return w.writer.Write(frame)
}
8 years ago
func (w *Writer) Write(b *buf.Buffer) error {
8 years ago
defer b.Release()
if err := w.writeInternal(b); err != nil {
8 years ago
return err
}
8 years ago
for !b.IsEmpty() {
if err := w.writeInternal(b); err != nil {
return err
}
}
return nil
}
8 years ago
8 years ago
func (w *Writer) Close() {
8 years ago
meta := FrameMetadata{
SessionID: w.id,
Target: w.dest,
SessionStatus: SessionStatusEnd,
8 years ago
}
8 years ago
frame := buf.New()
frame.AppendSupplier(meta.AsSupplier())
w.writer.Write(frame)
8 years ago
}