protocol.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941
  1. // Copyright (C) 2014 The Protocol Authors.
  2. package protocol
  3. import (
  4. "crypto/sha256"
  5. "encoding/binary"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "path"
  10. "strings"
  11. "sync"
  12. "time"
  13. lz4 "github.com/bkaradzic/go-lz4"
  14. )
  15. const (
  16. // Shifts
  17. KiB = 10
  18. MiB = 20
  19. GiB = 30
  20. )
  21. const (
  22. // MaxMessageLen is the largest message size allowed on the wire. (500 MB)
  23. MaxMessageLen = 500 * 1000 * 1000
  24. // MinBlockSize is the minimum block size allowed
  25. MinBlockSize = 128 << KiB
  26. // MaxBlockSize is the maximum block size allowed
  27. MaxBlockSize = 16 << MiB
  28. // DesiredPerFileBlocks is the number of blocks we aim for per file
  29. DesiredPerFileBlocks = 2000
  30. )
  31. // BlockSizes is the list of valid block sizes, from min to max
  32. var BlockSizes []int
  33. // For each block size, the hash of a block of all zeroes
  34. var sha256OfEmptyBlock = map[int][sha256.Size]byte{
  35. 128 << KiB: {0xfa, 0x43, 0x23, 0x9b, 0xce, 0xe7, 0xb9, 0x7c, 0xa6, 0x2f, 0x0, 0x7c, 0xc6, 0x84, 0x87, 0x56, 0xa, 0x39, 0xe1, 0x9f, 0x74, 0xf3, 0xdd, 0xe7, 0x48, 0x6d, 0xb3, 0xf9, 0x8d, 0xf8, 0xe4, 0x71},
  36. 256 << KiB: {0x8a, 0x39, 0xd2, 0xab, 0xd3, 0x99, 0x9a, 0xb7, 0x3c, 0x34, 0xdb, 0x24, 0x76, 0x84, 0x9c, 0xdd, 0xf3, 0x3, 0xce, 0x38, 0x9b, 0x35, 0x82, 0x68, 0x50, 0xf9, 0xa7, 0x0, 0x58, 0x9b, 0x4a, 0x90},
  37. 512 << KiB: {0x7, 0x85, 0x4d, 0x2f, 0xef, 0x29, 0x7a, 0x6, 0xba, 0x81, 0x68, 0x5e, 0x66, 0xc, 0x33, 0x2d, 0xe3, 0x6d, 0x5d, 0x18, 0xd5, 0x46, 0x92, 0x7d, 0x30, 0xda, 0xad, 0x6d, 0x7f, 0xda, 0x15, 0x41},
  38. 1 << MiB: {0x30, 0xe1, 0x49, 0x55, 0xeb, 0xf1, 0x35, 0x22, 0x66, 0xdc, 0x2f, 0xf8, 0x6, 0x7e, 0x68, 0x10, 0x46, 0x7, 0xe7, 0x50, 0xab, 0xb9, 0xd3, 0xb3, 0x65, 0x82, 0xb8, 0xaf, 0x90, 0x9f, 0xcb, 0x58},
  39. 2 << MiB: {0x56, 0x47, 0xf0, 0x5e, 0xc1, 0x89, 0x58, 0x94, 0x7d, 0x32, 0x87, 0x4e, 0xeb, 0x78, 0x8f, 0xa3, 0x96, 0xa0, 0x5d, 0xb, 0xab, 0x7c, 0x1b, 0x71, 0xf1, 0x12, 0xce, 0xb7, 0xe9, 0xb3, 0x1e, 0xee},
  40. 4 << MiB: {0xbb, 0x9f, 0x8d, 0xf6, 0x14, 0x74, 0xd2, 0x5e, 0x71, 0xfa, 0x0, 0x72, 0x23, 0x18, 0xcd, 0x38, 0x73, 0x96, 0xca, 0x17, 0x36, 0x60, 0x5e, 0x12, 0x48, 0x82, 0x1c, 0xc0, 0xde, 0x3d, 0x3a, 0xf8},
  41. 8 << MiB: {0x2d, 0xae, 0xb1, 0xf3, 0x60, 0x95, 0xb4, 0x4b, 0x31, 0x84, 0x10, 0xb3, 0xf4, 0xe8, 0xb5, 0xd9, 0x89, 0xdc, 0xc7, 0xbb, 0x2, 0x3d, 0x14, 0x26, 0xc4, 0x92, 0xda, 0xb0, 0xa3, 0x5, 0x3e, 0x74},
  42. 16 << MiB: {0x8, 0xa, 0xcf, 0x35, 0xa5, 0x7, 0xac, 0x98, 0x49, 0xcf, 0xcb, 0xa4, 0x7d, 0xc2, 0xad, 0x83, 0xe0, 0x1b, 0x75, 0x66, 0x3a, 0x51, 0x62, 0x79, 0xc8, 0xb9, 0xd2, 0x43, 0xb7, 0x19, 0x64, 0x3e},
  43. }
  44. func init() {
  45. for blockSize := MinBlockSize; blockSize <= MaxBlockSize; blockSize *= 2 {
  46. BlockSizes = append(BlockSizes, blockSize)
  47. if _, ok := sha256OfEmptyBlock[blockSize]; !ok {
  48. panic("missing hard coded value for sha256 of empty block")
  49. }
  50. }
  51. BufferPool = newBufferPool()
  52. }
  53. // BlockSize returns the block size to use for the given file size
  54. func BlockSize(fileSize int64) int {
  55. var blockSize int
  56. for _, blockSize = range BlockSizes {
  57. if fileSize < DesiredPerFileBlocks*int64(blockSize) {
  58. break
  59. }
  60. }
  61. return blockSize
  62. }
  63. const (
  64. stateInitial = iota
  65. stateReady
  66. )
  67. // Request message flags
  68. const (
  69. FlagFromTemporary uint32 = 1 << iota
  70. )
  71. // ClusterConfigMessage.Folders flags
  72. const (
  73. FlagFolderReadOnly uint32 = 1 << 0
  74. FlagFolderIgnorePerms = 1 << 1
  75. FlagFolderIgnoreDelete = 1 << 2
  76. FlagFolderDisabledTempIndexes = 1 << 3
  77. FlagFolderAll = 1<<4 - 1
  78. )
  79. // ClusterConfigMessage.Folders.Devices flags
  80. const (
  81. FlagShareTrusted uint32 = 1 << 0
  82. FlagShareReadOnly = 1 << 1
  83. FlagIntroducer = 1 << 2
  84. FlagShareBits = 0x000000ff
  85. )
  86. // FileInfo.LocalFlags flags
  87. const (
  88. FlagLocalUnsupported = 1 << 0 // The kind is unsupported, e.g. symlinks on Windows
  89. FlagLocalIgnored = 1 << 1 // Matches local ignore patterns
  90. FlagLocalMustRescan = 1 << 2 // Doesn't match content on disk, must be rechecked fully
  91. FlagLocalReceiveOnly = 1 << 3 // Change detected on receive only folder
  92. // Flags that should result in the Invalid bit on outgoing updates
  93. LocalInvalidFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalMustRescan | FlagLocalReceiveOnly
  94. // Flags that should result in a file being in conflict with its
  95. // successor, due to us not having an up to date picture of its state on
  96. // disk.
  97. LocalConflictFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalReceiveOnly
  98. LocalAllFlags = FlagLocalUnsupported | FlagLocalIgnored | FlagLocalMustRescan | FlagLocalReceiveOnly
  99. )
  100. var (
  101. ErrClosed = errors.New("connection closed")
  102. ErrTimeout = errors.New("read timeout")
  103. ErrSwitchingConnections = errors.New("switching connections")
  104. errUnknownMessage = errors.New("unknown message")
  105. errInvalidFilename = errors.New("filename is invalid")
  106. errUncleanFilename = errors.New("filename not in canonical format")
  107. errDeletedHasBlocks = errors.New("deleted file with non-empty block list")
  108. errDirectoryHasBlocks = errors.New("directory with non-empty block list")
  109. errFileHasNoBlocks = errors.New("file with empty block list")
  110. )
  111. type Model interface {
  112. // An index was received from the peer device
  113. Index(deviceID DeviceID, folder string, files []FileInfo)
  114. // An index update was received from the peer device
  115. IndexUpdate(deviceID DeviceID, folder string, files []FileInfo)
  116. // A request was made by the peer device
  117. Request(deviceID DeviceID, folder, name string, size int32, offset int64, hash []byte, weakHash uint32, fromTemporary bool) (RequestResponse, error)
  118. // A cluster configuration message was received
  119. ClusterConfig(deviceID DeviceID, config ClusterConfig)
  120. // The peer device closed the connection
  121. Closed(conn Connection, err error)
  122. // The peer device sent progress updates for the files it is currently downloading
  123. DownloadProgress(deviceID DeviceID, folder string, updates []FileDownloadProgressUpdate)
  124. }
  125. type RequestResponse interface {
  126. Data() []byte
  127. Close() // Must always be called once the byte slice is no longer in use
  128. Wait() // Blocks until Close is called
  129. }
  130. type Connection interface {
  131. Start()
  132. Close(err error)
  133. ID() DeviceID
  134. Name() string
  135. Index(folder string, files []FileInfo) error
  136. IndexUpdate(folder string, files []FileInfo) error
  137. Request(folder string, name string, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error)
  138. ClusterConfig(config ClusterConfig)
  139. DownloadProgress(folder string, updates []FileDownloadProgressUpdate)
  140. Statistics() Statistics
  141. Closed() bool
  142. }
  143. type rawConnection struct {
  144. id DeviceID
  145. name string
  146. receiver Model
  147. cr *countingReader
  148. cw *countingWriter
  149. awaiting map[int32]chan asyncResult
  150. awaitingMut sync.Mutex
  151. idxMut sync.Mutex // ensures serialization of Index calls
  152. nextID int32
  153. nextIDMut sync.Mutex
  154. outbox chan asyncMessage
  155. closed chan struct{}
  156. closeOnce sync.Once
  157. sendCloseOnce sync.Once
  158. compression Compression
  159. }
  160. type asyncResult struct {
  161. val []byte
  162. err error
  163. }
  164. type message interface {
  165. ProtoSize() int
  166. Marshal() ([]byte, error)
  167. MarshalTo([]byte) (int, error)
  168. Unmarshal([]byte) error
  169. }
  170. type asyncMessage struct {
  171. msg message
  172. done chan struct{} // done closes when we're done sending the message
  173. }
  174. const (
  175. // PingSendInterval is how often we make sure to send a message, by
  176. // triggering pings if necessary.
  177. PingSendInterval = 90 * time.Second
  178. // ReceiveTimeout is the longest we'll wait for a message from the other
  179. // side before closing the connection.
  180. ReceiveTimeout = 300 * time.Second
  181. )
  182. func NewConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, receiver Model, name string, compress Compression) Connection {
  183. cr := &countingReader{Reader: reader}
  184. cw := &countingWriter{Writer: writer}
  185. c := rawConnection{
  186. id: deviceID,
  187. name: name,
  188. receiver: nativeModel{receiver},
  189. cr: cr,
  190. cw: cw,
  191. awaiting: make(map[int32]chan asyncResult),
  192. outbox: make(chan asyncMessage),
  193. closed: make(chan struct{}),
  194. compression: compress,
  195. }
  196. return wireFormatConnection{&c}
  197. }
  198. // Start creates the goroutines for sending and receiving of messages. It must
  199. // be called exactly once after creating a connection.
  200. func (c *rawConnection) Start() {
  201. go func() {
  202. err := c.readerLoop()
  203. c.internalClose(err)
  204. }()
  205. go c.writerLoop()
  206. go c.pingSender()
  207. go c.pingReceiver()
  208. }
  209. func (c *rawConnection) ID() DeviceID {
  210. return c.id
  211. }
  212. func (c *rawConnection) Name() string {
  213. return c.name
  214. }
  215. // Index writes the list of file information to the connected peer device
  216. func (c *rawConnection) Index(folder string, idx []FileInfo) error {
  217. select {
  218. case <-c.closed:
  219. return ErrClosed
  220. default:
  221. }
  222. c.idxMut.Lock()
  223. c.send(&Index{
  224. Folder: folder,
  225. Files: idx,
  226. }, nil)
  227. c.idxMut.Unlock()
  228. return nil
  229. }
  230. // IndexUpdate writes the list of file information to the connected peer device as an update
  231. func (c *rawConnection) IndexUpdate(folder string, idx []FileInfo) error {
  232. select {
  233. case <-c.closed:
  234. return ErrClosed
  235. default:
  236. }
  237. c.idxMut.Lock()
  238. c.send(&IndexUpdate{
  239. Folder: folder,
  240. Files: idx,
  241. }, nil)
  242. c.idxMut.Unlock()
  243. return nil
  244. }
  245. // Request returns the bytes for the specified block after fetching them from the connected peer.
  246. func (c *rawConnection) Request(folder string, name string, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  247. c.nextIDMut.Lock()
  248. id := c.nextID
  249. c.nextID++
  250. c.nextIDMut.Unlock()
  251. c.awaitingMut.Lock()
  252. if _, ok := c.awaiting[id]; ok {
  253. panic("id taken")
  254. }
  255. rc := make(chan asyncResult, 1)
  256. c.awaiting[id] = rc
  257. c.awaitingMut.Unlock()
  258. ok := c.send(&Request{
  259. ID: id,
  260. Folder: folder,
  261. Name: name,
  262. Offset: offset,
  263. Size: int32(size),
  264. Hash: hash,
  265. WeakHash: weakHash,
  266. FromTemporary: fromTemporary,
  267. }, nil)
  268. if !ok {
  269. return nil, ErrClosed
  270. }
  271. res, ok := <-rc
  272. if !ok {
  273. return nil, ErrClosed
  274. }
  275. return res.val, res.err
  276. }
  277. // ClusterConfig send the cluster configuration message to the peer and returns any error
  278. func (c *rawConnection) ClusterConfig(config ClusterConfig) {
  279. c.send(&config, nil)
  280. }
  281. func (c *rawConnection) Closed() bool {
  282. select {
  283. case <-c.closed:
  284. return true
  285. default:
  286. return false
  287. }
  288. }
  289. // DownloadProgress sends the progress updates for the files that are currently being downloaded.
  290. func (c *rawConnection) DownloadProgress(folder string, updates []FileDownloadProgressUpdate) {
  291. c.send(&DownloadProgress{
  292. Folder: folder,
  293. Updates: updates,
  294. }, nil)
  295. }
  296. func (c *rawConnection) ping() bool {
  297. return c.send(&Ping{}, nil)
  298. }
  299. func (c *rawConnection) readerLoop() (err error) {
  300. fourByteBuf := make([]byte, 4)
  301. state := stateInitial
  302. for {
  303. select {
  304. case <-c.closed:
  305. return ErrClosed
  306. default:
  307. }
  308. msg, err := c.readMessage(fourByteBuf)
  309. if err == errUnknownMessage {
  310. // Unknown message types are skipped, for future extensibility.
  311. continue
  312. }
  313. if err != nil {
  314. return err
  315. }
  316. switch msg := msg.(type) {
  317. case *ClusterConfig:
  318. l.Debugln("read ClusterConfig message")
  319. if state != stateInitial {
  320. return fmt.Errorf("protocol error: cluster config message in state %d", state)
  321. }
  322. c.receiver.ClusterConfig(c.id, *msg)
  323. state = stateReady
  324. case *Index:
  325. l.Debugln("read Index message")
  326. if state != stateReady {
  327. return fmt.Errorf("protocol error: index message in state %d", state)
  328. }
  329. if err := checkIndexConsistency(msg.Files); err != nil {
  330. return fmt.Errorf("protocol error: index: %v", err)
  331. }
  332. c.handleIndex(*msg)
  333. state = stateReady
  334. case *IndexUpdate:
  335. l.Debugln("read IndexUpdate message")
  336. if state != stateReady {
  337. return fmt.Errorf("protocol error: index update message in state %d", state)
  338. }
  339. if err := checkIndexConsistency(msg.Files); err != nil {
  340. return fmt.Errorf("protocol error: index update: %v", err)
  341. }
  342. c.handleIndexUpdate(*msg)
  343. state = stateReady
  344. case *Request:
  345. l.Debugln("read Request message")
  346. if state != stateReady {
  347. return fmt.Errorf("protocol error: request message in state %d", state)
  348. }
  349. if err := checkFilename(msg.Name); err != nil {
  350. return fmt.Errorf("protocol error: request: %q: %v", msg.Name, err)
  351. }
  352. go c.handleRequest(*msg)
  353. case *Response:
  354. l.Debugln("read Response message")
  355. if state != stateReady {
  356. return fmt.Errorf("protocol error: response message in state %d", state)
  357. }
  358. c.handleResponse(*msg)
  359. case *DownloadProgress:
  360. l.Debugln("read DownloadProgress message")
  361. if state != stateReady {
  362. return fmt.Errorf("protocol error: response message in state %d", state)
  363. }
  364. c.receiver.DownloadProgress(c.id, msg.Folder, msg.Updates)
  365. case *Ping:
  366. l.Debugln("read Ping message")
  367. if state != stateReady {
  368. return fmt.Errorf("protocol error: ping message in state %d", state)
  369. }
  370. // Nothing
  371. case *Close:
  372. l.Debugln("read Close message")
  373. return errors.New(msg.Reason)
  374. default:
  375. l.Debugf("read unknown message: %+T", msg)
  376. return fmt.Errorf("protocol error: %s: unknown or empty message", c.id)
  377. }
  378. }
  379. }
  380. func (c *rawConnection) readMessage(fourByteBuf []byte) (message, error) {
  381. hdr, err := c.readHeader(fourByteBuf)
  382. if err != nil {
  383. return nil, err
  384. }
  385. return c.readMessageAfterHeader(hdr, fourByteBuf)
  386. }
  387. func (c *rawConnection) readMessageAfterHeader(hdr Header, fourByteBuf []byte) (message, error) {
  388. // First comes a 4 byte message length
  389. if _, err := io.ReadFull(c.cr, fourByteBuf[:4]); err != nil {
  390. return nil, fmt.Errorf("reading message length: %v", err)
  391. }
  392. msgLen := int32(binary.BigEndian.Uint32(fourByteBuf))
  393. if msgLen < 0 {
  394. return nil, fmt.Errorf("negative message length %d", msgLen)
  395. }
  396. // Then comes the message
  397. buf := BufferPool.Get(int(msgLen))
  398. if _, err := io.ReadFull(c.cr, buf); err != nil {
  399. return nil, fmt.Errorf("reading message: %v", err)
  400. }
  401. // ... which might be compressed
  402. switch hdr.Compression {
  403. case MessageCompressionNone:
  404. // Nothing
  405. case MessageCompressionLZ4:
  406. decomp, err := c.lz4Decompress(buf)
  407. BufferPool.Put(buf)
  408. if err != nil {
  409. return nil, fmt.Errorf("decompressing message: %v", err)
  410. }
  411. buf = decomp
  412. default:
  413. return nil, fmt.Errorf("unknown message compression %d", hdr.Compression)
  414. }
  415. // ... and is then unmarshalled
  416. msg, err := c.newMessage(hdr.Type)
  417. if err != nil {
  418. return nil, err
  419. }
  420. if err := msg.Unmarshal(buf); err != nil {
  421. return nil, fmt.Errorf("unmarshalling message: %v", err)
  422. }
  423. BufferPool.Put(buf)
  424. return msg, nil
  425. }
  426. func (c *rawConnection) readHeader(fourByteBuf []byte) (Header, error) {
  427. // First comes a 2 byte header length
  428. if _, err := io.ReadFull(c.cr, fourByteBuf[:2]); err != nil {
  429. return Header{}, fmt.Errorf("reading length: %v", err)
  430. }
  431. hdrLen := int16(binary.BigEndian.Uint16(fourByteBuf))
  432. if hdrLen < 0 {
  433. return Header{}, fmt.Errorf("negative header length %d", hdrLen)
  434. }
  435. // Then comes the header
  436. buf := BufferPool.Get(int(hdrLen))
  437. if _, err := io.ReadFull(c.cr, buf); err != nil {
  438. return Header{}, fmt.Errorf("reading header: %v", err)
  439. }
  440. var hdr Header
  441. if err := hdr.Unmarshal(buf); err != nil {
  442. return Header{}, fmt.Errorf("unmarshalling header: %v", err)
  443. }
  444. BufferPool.Put(buf)
  445. return hdr, nil
  446. }
  447. func (c *rawConnection) handleIndex(im Index) {
  448. l.Debugf("Index(%v, %v, %d file)", c.id, im.Folder, len(im.Files))
  449. c.receiver.Index(c.id, im.Folder, im.Files)
  450. }
  451. func (c *rawConnection) handleIndexUpdate(im IndexUpdate) {
  452. l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.id, im.Folder, len(im.Files))
  453. c.receiver.IndexUpdate(c.id, im.Folder, im.Files)
  454. }
  455. // checkIndexConsistency verifies a number of invariants on FileInfos received in
  456. // index messages.
  457. func checkIndexConsistency(fs []FileInfo) error {
  458. for _, f := range fs {
  459. if err := checkFileInfoConsistency(f); err != nil {
  460. return fmt.Errorf("%q: %v", f.Name, err)
  461. }
  462. }
  463. return nil
  464. }
  465. // checkFileInfoConsistency verifies a number of invariants on the given FileInfo
  466. func checkFileInfoConsistency(f FileInfo) error {
  467. if err := checkFilename(f.Name); err != nil {
  468. return err
  469. }
  470. switch {
  471. case f.Deleted && len(f.Blocks) != 0:
  472. // Deleted files should have no blocks
  473. return errDeletedHasBlocks
  474. case f.Type == FileInfoTypeDirectory && len(f.Blocks) != 0:
  475. // Directories should have no blocks
  476. return errDirectoryHasBlocks
  477. case !f.Deleted && !f.IsInvalid() && f.Type == FileInfoTypeFile && len(f.Blocks) == 0:
  478. // Non-deleted, non-invalid files should have at least one block
  479. return errFileHasNoBlocks
  480. }
  481. return nil
  482. }
  483. // checkFilename verifies that the given filename is valid according to the
  484. // spec on what's allowed over the wire. A filename failing this test is
  485. // grounds for disconnecting the device.
  486. func checkFilename(name string) error {
  487. cleanedName := path.Clean(name)
  488. if cleanedName != name {
  489. // The filename on the wire should be in canonical format. If
  490. // Clean() managed to clean it up, there was something wrong with
  491. // it.
  492. return errUncleanFilename
  493. }
  494. switch name {
  495. case "", ".", "..":
  496. // These names are always invalid.
  497. return errInvalidFilename
  498. }
  499. if strings.HasPrefix(name, "/") {
  500. // Names are folder relative, not absolute.
  501. return errInvalidFilename
  502. }
  503. if strings.HasPrefix(name, "../") {
  504. // Starting with a dotdot is not allowed. Any other dotdots would
  505. // have been handled by the Clean() call at the top.
  506. return errInvalidFilename
  507. }
  508. return nil
  509. }
  510. func (c *rawConnection) handleRequest(req Request) {
  511. res, err := c.receiver.Request(c.id, req.Folder, req.Name, req.Size, req.Offset, req.Hash, req.WeakHash, req.FromTemporary)
  512. if err != nil {
  513. c.send(&Response{
  514. ID: req.ID,
  515. Code: errorToCode(err),
  516. }, nil)
  517. return
  518. }
  519. done := make(chan struct{})
  520. c.send(&Response{
  521. ID: req.ID,
  522. Data: res.Data(),
  523. Code: errorToCode(nil),
  524. }, done)
  525. <-done
  526. res.Close()
  527. }
  528. func (c *rawConnection) handleResponse(resp Response) {
  529. c.awaitingMut.Lock()
  530. if rc := c.awaiting[resp.ID]; rc != nil {
  531. delete(c.awaiting, resp.ID)
  532. rc <- asyncResult{resp.Data, codeToError(resp.Code)}
  533. close(rc)
  534. }
  535. c.awaitingMut.Unlock()
  536. }
  537. func (c *rawConnection) send(msg message, done chan struct{}) bool {
  538. select {
  539. case c.outbox <- asyncMessage{msg, done}:
  540. return true
  541. case <-c.closed:
  542. if done != nil {
  543. close(done)
  544. }
  545. return false
  546. }
  547. }
  548. func (c *rawConnection) writerLoop() {
  549. for {
  550. select {
  551. case hm := <-c.outbox:
  552. err := c.writeMessage(hm)
  553. if hm.done != nil {
  554. close(hm.done)
  555. }
  556. if err != nil {
  557. c.internalClose(err)
  558. return
  559. }
  560. case <-c.closed:
  561. return
  562. }
  563. }
  564. }
  565. func (c *rawConnection) writeMessage(hm asyncMessage) error {
  566. if c.shouldCompressMessage(hm.msg) {
  567. return c.writeCompressedMessage(hm)
  568. }
  569. return c.writeUncompressedMessage(hm)
  570. }
  571. func (c *rawConnection) writeCompressedMessage(hm asyncMessage) error {
  572. size := hm.msg.ProtoSize()
  573. buf := BufferPool.Get(size)
  574. if _, err := hm.msg.MarshalTo(buf); err != nil {
  575. return fmt.Errorf("marshalling message: %v", err)
  576. }
  577. compressed, err := c.lz4Compress(buf)
  578. if err != nil {
  579. return fmt.Errorf("compressing message: %v", err)
  580. }
  581. hdr := Header{
  582. Type: c.typeOf(hm.msg),
  583. Compression: MessageCompressionLZ4,
  584. }
  585. hdrSize := hdr.ProtoSize()
  586. if hdrSize > 1<<16-1 {
  587. panic("impossibly large header")
  588. }
  589. totSize := 2 + hdrSize + 4 + len(compressed)
  590. buf = BufferPool.Upgrade(buf, totSize)
  591. // Header length
  592. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  593. // Header
  594. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  595. return fmt.Errorf("marshalling header: %v", err)
  596. }
  597. // Message length
  598. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(len(compressed)))
  599. // Message
  600. copy(buf[2+hdrSize+4:], compressed)
  601. BufferPool.Put(compressed)
  602. n, err := c.cw.Write(buf)
  603. BufferPool.Put(buf)
  604. l.Debugf("wrote %d bytes on the wire (2 bytes length, %d bytes header, 4 bytes message length, %d bytes message (%d uncompressed)), err=%v", n, hdrSize, len(compressed), size, err)
  605. if err != nil {
  606. return fmt.Errorf("writing message: %v", err)
  607. }
  608. return nil
  609. }
  610. func (c *rawConnection) writeUncompressedMessage(hm asyncMessage) error {
  611. size := hm.msg.ProtoSize()
  612. hdr := Header{
  613. Type: c.typeOf(hm.msg),
  614. }
  615. hdrSize := hdr.ProtoSize()
  616. if hdrSize > 1<<16-1 {
  617. panic("impossibly large header")
  618. }
  619. totSize := 2 + hdrSize + 4 + size
  620. buf := BufferPool.Get(totSize)
  621. // Header length
  622. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  623. // Header
  624. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  625. return fmt.Errorf("marshalling header: %v", err)
  626. }
  627. // Message length
  628. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(size))
  629. // Message
  630. if _, err := hm.msg.MarshalTo(buf[2+hdrSize+4:]); err != nil {
  631. return fmt.Errorf("marshalling message: %v", err)
  632. }
  633. n, err := c.cw.Write(buf[:totSize])
  634. BufferPool.Put(buf)
  635. l.Debugf("wrote %d bytes on the wire (2 bytes length, %d bytes header, 4 bytes message length, %d bytes message), err=%v", n, hdrSize, size, err)
  636. if err != nil {
  637. return fmt.Errorf("writing message: %v", err)
  638. }
  639. return nil
  640. }
  641. func (c *rawConnection) typeOf(msg message) MessageType {
  642. switch msg.(type) {
  643. case *ClusterConfig:
  644. return messageTypeClusterConfig
  645. case *Index:
  646. return messageTypeIndex
  647. case *IndexUpdate:
  648. return messageTypeIndexUpdate
  649. case *Request:
  650. return messageTypeRequest
  651. case *Response:
  652. return messageTypeResponse
  653. case *DownloadProgress:
  654. return messageTypeDownloadProgress
  655. case *Ping:
  656. return messageTypePing
  657. case *Close:
  658. return messageTypeClose
  659. default:
  660. panic("bug: unknown message type")
  661. }
  662. }
  663. func (c *rawConnection) newMessage(t MessageType) (message, error) {
  664. switch t {
  665. case messageTypeClusterConfig:
  666. return new(ClusterConfig), nil
  667. case messageTypeIndex:
  668. return new(Index), nil
  669. case messageTypeIndexUpdate:
  670. return new(IndexUpdate), nil
  671. case messageTypeRequest:
  672. return new(Request), nil
  673. case messageTypeResponse:
  674. return new(Response), nil
  675. case messageTypeDownloadProgress:
  676. return new(DownloadProgress), nil
  677. case messageTypePing:
  678. return new(Ping), nil
  679. case messageTypeClose:
  680. return new(Close), nil
  681. default:
  682. return nil, errUnknownMessage
  683. }
  684. }
  685. func (c *rawConnection) shouldCompressMessage(msg message) bool {
  686. switch c.compression {
  687. case CompressNever:
  688. return false
  689. case CompressAlways:
  690. // Use compression for large enough messages
  691. return msg.ProtoSize() >= compressionThreshold
  692. case CompressMetadata:
  693. _, isResponse := msg.(*Response)
  694. // Compress if it's large enough and not a response message
  695. return !isResponse && msg.ProtoSize() >= compressionThreshold
  696. default:
  697. panic("unknown compression setting")
  698. }
  699. }
  700. // Close is called when the connection is regularely closed and thus the Close
  701. // BEP message is sent before terminating the actual connection. The error
  702. // argument specifies the reason for closing the connection.
  703. func (c *rawConnection) Close(err error) {
  704. c.sendCloseOnce.Do(func() {
  705. done := make(chan struct{})
  706. c.send(&Close{err.Error()}, done)
  707. select {
  708. case <-done:
  709. case <-c.closed:
  710. }
  711. })
  712. // No more sends are necessary, therefore further steps to close the
  713. // connection outside of this package can proceed immediately.
  714. // And this prevents a potential deadlock due to calling c.receiver.Closed
  715. go c.internalClose(err)
  716. }
  717. // internalClose is called if there is an unexpected error during normal operation.
  718. func (c *rawConnection) internalClose(err error) {
  719. c.closeOnce.Do(func() {
  720. l.Debugln("close due to", err)
  721. close(c.closed)
  722. c.awaitingMut.Lock()
  723. for i, ch := range c.awaiting {
  724. if ch != nil {
  725. close(ch)
  726. delete(c.awaiting, i)
  727. }
  728. }
  729. c.awaitingMut.Unlock()
  730. c.receiver.Closed(c, err)
  731. })
  732. }
  733. // The pingSender makes sure that we've sent a message within the last
  734. // PingSendInterval. If we already have something sent in the last
  735. // PingSendInterval/2, we do nothing. Otherwise we send a ping message. This
  736. // results in an effecting ping interval of somewhere between
  737. // PingSendInterval/2 and PingSendInterval.
  738. func (c *rawConnection) pingSender() {
  739. ticker := time.NewTicker(PingSendInterval / 2)
  740. defer ticker.Stop()
  741. for {
  742. select {
  743. case <-ticker.C:
  744. d := time.Since(c.cw.Last())
  745. if d < PingSendInterval/2 {
  746. l.Debugln(c.id, "ping skipped after wr", d)
  747. continue
  748. }
  749. l.Debugln(c.id, "ping -> after", d)
  750. c.ping()
  751. case <-c.closed:
  752. return
  753. }
  754. }
  755. }
  756. // The pingReceiver checks that we've received a message (any message will do,
  757. // but we expect pings in the absence of other messages) within the last
  758. // ReceiveTimeout. If not, we close the connection with an ErrTimeout.
  759. func (c *rawConnection) pingReceiver() {
  760. ticker := time.NewTicker(ReceiveTimeout / 2)
  761. defer ticker.Stop()
  762. for {
  763. select {
  764. case <-ticker.C:
  765. d := time.Since(c.cr.Last())
  766. if d > ReceiveTimeout {
  767. l.Debugln(c.id, "ping timeout", d)
  768. c.internalClose(ErrTimeout)
  769. }
  770. l.Debugln(c.id, "last read within", d)
  771. case <-c.closed:
  772. return
  773. }
  774. }
  775. }
  776. type Statistics struct {
  777. At time.Time
  778. InBytesTotal int64
  779. OutBytesTotal int64
  780. }
  781. func (c *rawConnection) Statistics() Statistics {
  782. return Statistics{
  783. At: time.Now(),
  784. InBytesTotal: c.cr.Tot(),
  785. OutBytesTotal: c.cw.Tot(),
  786. }
  787. }
  788. func (c *rawConnection) lz4Compress(src []byte) ([]byte, error) {
  789. var err error
  790. buf := BufferPool.Get(len(src))
  791. buf, err = lz4.Encode(buf, src)
  792. if err != nil {
  793. return nil, err
  794. }
  795. binary.BigEndian.PutUint32(buf, binary.LittleEndian.Uint32(buf))
  796. return buf, nil
  797. }
  798. func (c *rawConnection) lz4Decompress(src []byte) ([]byte, error) {
  799. size := binary.BigEndian.Uint32(src)
  800. binary.LittleEndian.PutUint32(src, size)
  801. var err error
  802. buf := BufferPool.Get(int(size))
  803. buf, err = lz4.Decode(buf, src)
  804. if err != nil {
  805. return nil, err
  806. }
  807. return buf, nil
  808. }