2017-02-07 15:11:47 -05:00
|
|
|
package mux
|
|
|
|
|
2017-03-26 19:47:01 -04:00
|
|
|
import (
|
|
|
|
"v2ray.com/core/common/buf"
|
2017-03-31 18:53:01 -04:00
|
|
|
"v2ray.com/core/common/net"
|
2017-03-26 19:47:01 -04:00
|
|
|
"v2ray.com/core/common/serial"
|
|
|
|
)
|
2017-02-07 15:11:47 -05:00
|
|
|
|
2017-04-02 07:43:24 -04:00
|
|
|
type Writer struct {
|
2017-03-31 18:53:01 -04:00
|
|
|
id uint16
|
|
|
|
dest net.Destination
|
|
|
|
writer buf.Writer
|
|
|
|
followup bool
|
2017-02-07 15:11:47 -05:00
|
|
|
}
|
|
|
|
|
2017-04-02 07:43:24 -04:00
|
|
|
func NewWriter(id uint16, dest net.Destination, writer buf.Writer) *Writer {
|
|
|
|
return &Writer{
|
2017-04-02 03:48:30 -04:00
|
|
|
id: id,
|
|
|
|
dest: dest,
|
|
|
|
writer: writer,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-03 06:55:46 -04:00
|
|
|
func NewResponseWriter(id uint16, writer buf.Writer) *Writer {
|
|
|
|
return &Writer{
|
|
|
|
id: id,
|
|
|
|
writer: writer,
|
|
|
|
followup: true,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-02 07:43:24 -04:00
|
|
|
func (w *Writer) writeInternal(b *buf.Buffer) error {
|
2017-03-31 18:53:01 -04:00
|
|
|
meta := FrameMetadata{
|
|
|
|
SessionID: w.id,
|
|
|
|
Target: w.dest,
|
|
|
|
}
|
|
|
|
if w.followup {
|
|
|
|
meta.SessionStatus = SessionStatusKeep
|
|
|
|
} else {
|
|
|
|
w.followup = true
|
|
|
|
meta.SessionStatus = SessionStatusNew
|
2017-02-07 15:11:47 -05:00
|
|
|
}
|
|
|
|
|
2017-03-31 18:53:01 -04:00
|
|
|
if b.Len() > 0 {
|
|
|
|
meta.Option.Add(OptionData)
|
|
|
|
}
|
2017-02-07 15:11:47 -05:00
|
|
|
|
2017-03-31 18:53:01 -04:00
|
|
|
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)
|
2017-02-07 15:11:47 -05:00
|
|
|
}
|
|
|
|
|
2017-03-31 18:53:01 -04:00
|
|
|
return w.writer.Write(frame)
|
|
|
|
}
|
|
|
|
|
2017-04-02 07:43:24 -04:00
|
|
|
func (w *Writer) Write(b *buf.Buffer) error {
|
2017-03-31 18:53:01 -04:00
|
|
|
defer b.Release()
|
|
|
|
|
|
|
|
if err := w.writeInternal(b); err != nil {
|
2017-02-07 15:11:47 -05:00
|
|
|
return err
|
|
|
|
}
|
2017-03-31 18:53:01 -04:00
|
|
|
for !b.IsEmpty() {
|
|
|
|
if err := w.writeInternal(b); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2017-02-07 15:11:47 -05:00
|
|
|
|
2017-04-02 07:43:24 -04:00
|
|
|
func (w *Writer) Close() {
|
2017-03-31 18:53:01 -04:00
|
|
|
meta := FrameMetadata{
|
|
|
|
SessionID: w.id,
|
|
|
|
SessionStatus: SessionStatusEnd,
|
2017-02-07 15:11:47 -05:00
|
|
|
}
|
|
|
|
|
2017-03-31 18:53:01 -04:00
|
|
|
frame := buf.New()
|
|
|
|
frame.AppendSupplier(meta.AsSupplier())
|
|
|
|
|
|
|
|
w.writer.Write(frame)
|
2017-02-07 15:11:47 -05:00
|
|
|
}
|