Blob


1 package p9p
3 import (
4 "bufio"
5 "encoding/binary"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "log"
10 "net"
11 "time"
13 "golang.org/x/net/context"
14 )
16 // Channel defines the operations necessary to implement a 9p message channel
17 // interface. Typically, message channels do no protocol processing except to
18 // send and receive message frames.
19 type Channel interface {
20 // ReadFcall reads one fcall frame into the provided fcall structure. The
21 // Fcall may be cleared whether there is an error or not. If the operation
22 // is successful, the contents of the fcall will be populated in the
23 // argument. ReadFcall cannot be called concurrently with other calls to
24 // ReadFcall. This both to preserve message ordering and to allow lockless
25 // buffer reusage.
26 ReadFcall(ctx context.Context, fcall *Fcall) error
28 // WriteFcall writes the provided fcall to the channel. WriteFcall cannot
29 // be called concurrently with other calls to WriteFcall.
30 WriteFcall(ctx context.Context, fcall *Fcall) error
32 // MSize returns the current msize for the channel.
33 MSize() int
35 // SetMSize sets the maximum message size for the channel. This must never
36 // be called currently with ReadFcall or WriteFcall.
37 SetMSize(msize int)
38 }
40 func NewChannel(conn net.Conn, msize int) Channel {
41 return newChannel(conn, codec9p{}, msize)
42 }
44 const (
45 defaultRWTimeout = 30 * time.Second // default read/write timeout if not set in context
46 )
48 // channel provides bidirectional protocol framing for 9p over net.Conn.
49 // Operations are not thread-safe but reads and writes may be carried out
50 // concurrently, supporting separate read and write loops.
51 //
52 // Lifecyle
53 //
54 // A connection, or message channel abstraction, has a lifecycle delineated by
55 // Tversion/Rversion request response cycles. For now, this is part of the
56 // channel itself but doesn't necessarily influence the channels state, except
57 // the msize. Visually, it might look something like this:
58 //
59 // [Established] -> [Version] -> [Session] -> [Version]---+
60 // ^ |
61 // |_________________________________|
62 //
63 // The connection is established, then we negotiate a version, run a session,
64 // then negotiate a version and so on. For most purposes, we are likely going
65 // to terminate the connection after the session but we may want to support
66 // connection pooling. Pooling may result in possible security leaks if the
67 // connections are shared among contexts, since the version is negotiated at
68 // the start of the session. To avoid this, we can actually use a "tombstone"
69 // version message which clears the server's session state without starting a
70 // new session. The next version message would then prepare the session
71 // without leaking any Fid's.
72 type channel struct {
73 conn net.Conn
74 codec Codec
75 brd *bufio.Reader
76 bwr *bufio.Writer
77 closed chan struct{}
78 msize int
79 rdbuf []byte
80 }
82 func newChannel(conn net.Conn, codec Codec, msize int) *channel {
83 return &channel{
84 conn: conn,
85 codec: codec,
86 brd: bufio.NewReaderSize(conn, msize), // msize may not be optimal buffer size
87 bwr: bufio.NewWriterSize(conn, msize),
88 closed: make(chan struct{}),
89 msize: msize,
90 rdbuf: make([]byte, msize),
91 }
92 }
94 func (ch *channel) MSize() int {
95 return ch.msize
96 }
98 // setmsize resizes the buffers for use with a separate msize. This call must
99 // be protected by a mutex or made before passing to other goroutines.
100 func (ch *channel) SetMSize(msize int) {
101 // NOTE(stevvooe): We cannot safely resize the buffered reader and writer.
102 // Proceed assuming that original size is sufficient.
104 ch.msize = msize
105 if msize < len(ch.rdbuf) {
106 // just change the cap
107 ch.rdbuf = ch.rdbuf[:msize]
108 return
111 ch.rdbuf = make([]byte, msize)
114 // ReadFcall reads the next message from the channel into fcall.
115 func (ch *channel) ReadFcall(ctx context.Context, fcall *Fcall) error {
116 select {
117 case <-ctx.Done():
118 return ctx.Err()
119 case <-ch.closed:
120 return ErrClosed
121 default:
124 deadline, ok := ctx.Deadline()
125 if !ok {
126 deadline = time.Now().Add(defaultRWTimeout)
129 if err := ch.conn.SetReadDeadline(deadline); err != nil {
130 log.Printf("transport: error setting read deadline on %v: %v", ch.conn.RemoteAddr(), err)
133 n, err := readmsg(ch.brd, ch.rdbuf)
134 if err != nil {
135 // TODO(stevvooe): There may be more we can do here to detect partial
136 // reads. For now, we just propagate the error untouched.
137 return err
140 if n > len(ch.rdbuf) {
141 // TODO(stevvooe): Make this error detectable and respond with error
142 // message.
143 return fmt.Errorf("message large than buffer:", n)
146 // clear out the fcall
147 *fcall = Fcall{}
148 if err := ch.codec.Unmarshal(ch.rdbuf[:n], fcall); err != nil {
149 return err
152 return nil
155 func (ch *channel) WriteFcall(ctx context.Context, fcall *Fcall) error {
156 select {
157 case <-ctx.Done():
158 return ctx.Err()
159 case <-ch.closed:
160 return ErrClosed
161 default:
164 deadline, ok := ctx.Deadline()
165 if !ok {
166 deadline = time.Now().Add(defaultRWTimeout)
169 if err := ch.conn.SetWriteDeadline(deadline); err != nil {
170 log.Printf("transport: error setting read deadline on %v: %v", ch.conn.RemoteAddr(), err)
173 p, err := ch.codec.Marshal(fcall)
174 if err != nil {
175 return err
178 if err := sendmsg(ch.bwr, p); err != nil {
179 return err
182 return ch.bwr.Flush()
185 // readmsg reads a 9p message into p from rd, ensuring that all bytes are
186 // consumed from the size header. If the size header indicates the message is
187 // larger than p, the entire message will be discarded, leaving a truncated
188 // portion in p. Any error should be treated as a framing error unless n is
189 // zero. The caller must check that n is less than or equal to len(p) to
190 // ensure that a valid message has been read.
191 func readmsg(rd io.Reader, p []byte) (n int, err error) {
192 var msize uint32
194 if err := binary.Read(rd, binary.LittleEndian, &msize); err != nil {
195 return 0, err
198 n += binary.Size(msize)
199 mbody := int(msize) - 4
201 if mbody < len(p) {
202 p = p[:mbody]
205 np, err := io.ReadFull(rd, p)
206 if err != nil {
207 return np + n, err
209 n += np
211 if mbody > len(p) {
212 // message has been read up to len(p) but we must consume the entire
213 // message. This is an error condition but is non-fatal if we can
214 // consume msize bytes.
215 nn, err := io.CopyN(ioutil.Discard, rd, int64(mbody-len(p)))
216 n += int(nn)
217 if err != nil {
218 return n, err
222 return n, nil
225 // sendmsg writes a message of len(p) to wr with a 9p size header. All errors
226 // should be considered terminal.
227 func sendmsg(wr io.Writer, p []byte) error {
228 size := uint32(len(p) + 4) // message size plus 4-bytes for size.
229 if err := binary.Write(wr, binary.LittleEndian, size); err != nil {
230 return err
233 // This assume partial writes to wr aren't possible. Not sure if this
234 // valid. Matters during timeout retries.
235 if n, err := wr.Write(p); err != nil {
236 return err
237 } else if n < len(p) {
238 return io.ErrShortWrite
241 return nil