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

121 lines
2.5 KiB

8 years ago
package mux
8 years ago
import (
"v2ray.com/core/common"
8 years ago
"v2ray.com/core/common/buf"
8 years ago
"v2ray.com/core/common/net"
"v2ray.com/core/common/protocol"
8 years ago
"v2ray.com/core/common/serial"
)
8 years ago
8 years ago
type Writer struct {
dest net.Destination
writer buf.Writer
id uint16
followup bool
hasError bool
transferType protocol.TransferType
8 years ago
}
func NewWriter(id uint16, dest net.Destination, writer buf.Writer, transferType protocol.TransferType) *Writer {
8 years ago
return &Writer{
id: id,
dest: dest,
writer: writer,
followup: false,
transferType: transferType,
8 years ago
}
}
func NewResponseWriter(id uint16, writer buf.Writer, transferType protocol.TransferType) *Writer {
8 years ago
return &Writer{
id: id,
writer: writer,
followup: true,
transferType: transferType,
8 years ago
}
}
8 years ago
func (w *Writer) getNextFrameMeta() FrameMetadata {
8 years ago
meta := FrameMetadata{
SessionID: w.id,
Target: w.dest,
}
8 years ago
if w.followup {
meta.SessionStatus = SessionStatusKeep
} else {
w.followup = true
meta.SessionStatus = SessionStatusNew
8 years ago
}
8 years ago
return meta
}
8 years ago
8 years ago
func (w *Writer) writeMetaOnly() error {
meta := w.getNextFrameMeta()
b := buf.New()
if err := meta.WriteTo(b); err != nil {
8 years ago
return err
8 years ago
}
return w.writer.WriteMultiBuffer(buf.NewMultiBufferValue(b))
8 years ago
}
func (w *Writer) writeData(mb buf.MultiBuffer) error {
meta := w.getNextFrameMeta()
meta.Option.Set(OptionData)
8 years ago
8 years ago
frame := buf.New()
if err := meta.WriteTo(frame); err != nil {
8 years ago
return err
}
if err := frame.AppendSupplier(serial.WriteUint16(uint16(mb.Len()))); err != nil {
return err
8 years ago
}
8 years ago
mb2 := buf.NewMultiBufferCap(int32(len(mb)) + 1)
8 years ago
mb2.Append(frame)
8 years ago
mb2.AppendMulti(mb)
return w.writer.WriteMultiBuffer(mb2)
8 years ago
}
8 years ago
// WriteMultiBuffer implements buf.Writer.
func (w *Writer) WriteMultiBuffer(mb buf.MultiBuffer) error {
defer mb.Release()
8 years ago
if mb.IsEmpty() {
return w.writeMetaOnly()
}
for !mb.IsEmpty() {
var chunk buf.MultiBuffer
if w.transferType == protocol.TransferTypeStream {
chunk = mb.SliceBySize(8 * 1024)
} else {
chunk = buf.NewMultiBufferValue(mb.SplitFirst())
}
if err := w.writeData(chunk); err != nil {
return err
}
}
return nil
}
7 years ago
// Close implements common.Closable.
func (w *Writer) Close() error {
8 years ago
meta := FrameMetadata{
SessionID: w.id,
SessionStatus: SessionStatusEnd,
8 years ago
}
if w.hasError {
meta.Option.Set(OptionError)
}
frame := buf.New()
common.Must(meta.WriteTo(frame))
7 years ago
w.writer.WriteMultiBuffer(buf.NewMultiBufferValue(frame)) // nolint: errcheck
return nil
}