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

107 lines
2.0 KiB

8 years ago
package mux
8 years ago
import (
8 years ago
"runtime"
8 years ago
"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{
id: id,
dest: dest,
writer: writer,
followup: false,
8 years ago
}
}
8 years ago
func NewResponseWriter(id uint16, writer buf.Writer) *Writer {
return &Writer{
id: id,
writer: writer,
followup: true,
}
}
8 years ago
func (w *Writer) getNextFrameMeta() FrameMetadata {
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
return meta
}
8 years ago
8 years ago
func (w *Writer) writeMetaOnly() error {
meta := w.getNextFrameMeta()
b := buf.New()
if err := b.AppendSupplier(meta.AsSupplier()); err != nil {
return err
8 years ago
}
8 years ago
runtime.KeepAlive(meta)
return w.writer.Write(buf.NewMultiBufferValue(b))
}
func (w *Writer) writeData(mb buf.MultiBuffer) error {
meta := w.getNextFrameMeta()
meta.Option.Add(OptionData)
8 years ago
8 years ago
frame := buf.New()
8 years ago
if err := frame.AppendSupplier(meta.AsSupplier()); err != nil {
return err
}
runtime.KeepAlive(meta)
if err := frame.AppendSupplier(serial.WriteUint16(uint16(mb.Len()))); err != nil {
return err
8 years ago
}
8 years ago
8 years ago
mb2 := buf.NewMultiBuffer()
mb2.Append(frame)
8 years ago
mb2.AppendMulti(mb)
8 years ago
return w.writer.Write(mb2)
8 years ago
}
8 years ago
8 years ago
// Write implements buf.MultiBufferWriter.
func (w *Writer) Write(mb buf.MultiBuffer) error {
8 years ago
if mb.IsEmpty() {
return w.writeMetaOnly()
}
const chunkSize = 8 * 1024
8 years ago
for !mb.IsEmpty() {
slice := mb.SliceBySize(chunkSize)
8 years ago
if err := w.writeData(slice); err != nil {
return err
}
}
return nil
}
8 years ago
func (w *Writer) Close() {
8 years ago
meta := FrameMetadata{
SessionID: w.id,
SessionStatus: SessionStatusEnd,
8 years ago
}
8 years ago
frame := buf.New()
frame.AppendSupplier(meta.AsSupplier())
8 years ago
runtime.KeepAlive(meta)
8 years ago
8 years ago
w.writer.Write(buf.NewMultiBufferValue(frame))
8 years ago
}