protocol.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  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. inbox chan message
  155. outbox chan asyncMessage
  156. clusterConfigBox chan *ClusterConfig
  157. dispatcherLoopStopped chan struct{}
  158. closed chan struct{}
  159. closeOnce sync.Once
  160. sendCloseOnce sync.Once
  161. compression Compression
  162. }
  163. type asyncResult struct {
  164. val []byte
  165. err error
  166. }
  167. type message interface {
  168. ProtoSize() int
  169. Marshal() ([]byte, error)
  170. MarshalTo([]byte) (int, error)
  171. Unmarshal([]byte) error
  172. }
  173. type asyncMessage struct {
  174. msg message
  175. done chan struct{} // done closes when we're done sending the message
  176. }
  177. const (
  178. // PingSendInterval is how often we make sure to send a message, by
  179. // triggering pings if necessary.
  180. PingSendInterval = 90 * time.Second
  181. // ReceiveTimeout is the longest we'll wait for a message from the other
  182. // side before closing the connection.
  183. ReceiveTimeout = 300 * time.Second
  184. )
  185. func NewConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, receiver Model, name string, compress Compression) Connection {
  186. cr := &countingReader{Reader: reader}
  187. cw := &countingWriter{Writer: writer}
  188. c := rawConnection{
  189. id: deviceID,
  190. name: name,
  191. receiver: nativeModel{receiver},
  192. cr: cr,
  193. cw: cw,
  194. awaiting: make(map[int32]chan asyncResult),
  195. inbox: make(chan message),
  196. outbox: make(chan asyncMessage),
  197. clusterConfigBox: make(chan *ClusterConfig),
  198. dispatcherLoopStopped: make(chan struct{}),
  199. closed: make(chan struct{}),
  200. compression: compress,
  201. }
  202. return wireFormatConnection{&c}
  203. }
  204. // Start creates the goroutines for sending and receiving of messages. It must
  205. // be called exactly once after creating a connection.
  206. func (c *rawConnection) Start() {
  207. go c.readerLoop()
  208. go func() {
  209. err := c.dispatcherLoop()
  210. c.internalClose(err)
  211. }()
  212. go c.writerLoop()
  213. go c.pingSender()
  214. go c.pingReceiver()
  215. }
  216. func (c *rawConnection) ID() DeviceID {
  217. return c.id
  218. }
  219. func (c *rawConnection) Name() string {
  220. return c.name
  221. }
  222. // Index writes the list of file information to the connected peer device
  223. func (c *rawConnection) Index(folder string, idx []FileInfo) error {
  224. select {
  225. case <-c.closed:
  226. return ErrClosed
  227. default:
  228. }
  229. c.idxMut.Lock()
  230. c.send(&Index{
  231. Folder: folder,
  232. Files: idx,
  233. }, nil)
  234. c.idxMut.Unlock()
  235. return nil
  236. }
  237. // IndexUpdate writes the list of file information to the connected peer device as an update
  238. func (c *rawConnection) IndexUpdate(folder string, idx []FileInfo) error {
  239. select {
  240. case <-c.closed:
  241. return ErrClosed
  242. default:
  243. }
  244. c.idxMut.Lock()
  245. c.send(&IndexUpdate{
  246. Folder: folder,
  247. Files: idx,
  248. }, nil)
  249. c.idxMut.Unlock()
  250. return nil
  251. }
  252. // Request returns the bytes for the specified block after fetching them from the connected peer.
  253. func (c *rawConnection) Request(folder string, name string, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
  254. c.nextIDMut.Lock()
  255. id := c.nextID
  256. c.nextID++
  257. c.nextIDMut.Unlock()
  258. c.awaitingMut.Lock()
  259. if _, ok := c.awaiting[id]; ok {
  260. panic("id taken")
  261. }
  262. rc := make(chan asyncResult, 1)
  263. c.awaiting[id] = rc
  264. c.awaitingMut.Unlock()
  265. ok := c.send(&Request{
  266. ID: id,
  267. Folder: folder,
  268. Name: name,
  269. Offset: offset,
  270. Size: int32(size),
  271. Hash: hash,
  272. WeakHash: weakHash,
  273. FromTemporary: fromTemporary,
  274. }, nil)
  275. if !ok {
  276. return nil, ErrClosed
  277. }
  278. res, ok := <-rc
  279. if !ok {
  280. return nil, ErrClosed
  281. }
  282. return res.val, res.err
  283. }
  284. // ClusterConfig sends the cluster configuration message to the peer.
  285. // It must be called just once (as per BEP), otherwise it will panic.
  286. func (c *rawConnection) ClusterConfig(config ClusterConfig) {
  287. c.clusterConfigBox <- &config
  288. close(c.clusterConfigBox)
  289. }
  290. func (c *rawConnection) Closed() bool {
  291. select {
  292. case <-c.closed:
  293. return true
  294. default:
  295. return false
  296. }
  297. }
  298. // DownloadProgress sends the progress updates for the files that are currently being downloaded.
  299. func (c *rawConnection) DownloadProgress(folder string, updates []FileDownloadProgressUpdate) {
  300. c.send(&DownloadProgress{
  301. Folder: folder,
  302. Updates: updates,
  303. }, nil)
  304. }
  305. func (c *rawConnection) ping() bool {
  306. return c.send(&Ping{}, nil)
  307. }
  308. func (c *rawConnection) readerLoop() {
  309. fourByteBuf := make([]byte, 4)
  310. for {
  311. msg, err := c.readMessage(fourByteBuf)
  312. if err != nil {
  313. if err == errUnknownMessage {
  314. // Unknown message types are skipped, for future extensibility.
  315. continue
  316. }
  317. c.internalClose(err)
  318. return
  319. }
  320. select {
  321. case c.inbox <- msg:
  322. case <-c.closed:
  323. return
  324. }
  325. }
  326. }
  327. func (c *rawConnection) dispatcherLoop() (err error) {
  328. defer close(c.dispatcherLoopStopped)
  329. var msg message
  330. state := stateInitial
  331. for {
  332. select {
  333. case msg = <-c.inbox:
  334. case <-c.closed:
  335. return ErrClosed
  336. }
  337. switch msg := msg.(type) {
  338. case *ClusterConfig:
  339. l.Debugln("read ClusterConfig message")
  340. if state != stateInitial {
  341. return fmt.Errorf("protocol error: cluster config message in state %d", state)
  342. }
  343. c.receiver.ClusterConfig(c.id, *msg)
  344. state = stateReady
  345. case *Index:
  346. l.Debugln("read Index message")
  347. if state != stateReady {
  348. return fmt.Errorf("protocol error: index message in state %d", state)
  349. }
  350. if err := checkIndexConsistency(msg.Files); err != nil {
  351. return fmt.Errorf("protocol error: index: %v", err)
  352. }
  353. c.handleIndex(*msg)
  354. state = stateReady
  355. case *IndexUpdate:
  356. l.Debugln("read IndexUpdate message")
  357. if state != stateReady {
  358. return fmt.Errorf("protocol error: index update message in state %d", state)
  359. }
  360. if err := checkIndexConsistency(msg.Files); err != nil {
  361. return fmt.Errorf("protocol error: index update: %v", err)
  362. }
  363. c.handleIndexUpdate(*msg)
  364. state = stateReady
  365. case *Request:
  366. l.Debugln("read Request message")
  367. if state != stateReady {
  368. return fmt.Errorf("protocol error: request message in state %d", state)
  369. }
  370. if err := checkFilename(msg.Name); err != nil {
  371. return fmt.Errorf("protocol error: request: %q: %v", msg.Name, err)
  372. }
  373. go c.handleRequest(*msg)
  374. case *Response:
  375. l.Debugln("read Response message")
  376. if state != stateReady {
  377. return fmt.Errorf("protocol error: response message in state %d", state)
  378. }
  379. c.handleResponse(*msg)
  380. case *DownloadProgress:
  381. l.Debugln("read DownloadProgress message")
  382. if state != stateReady {
  383. return fmt.Errorf("protocol error: response message in state %d", state)
  384. }
  385. c.receiver.DownloadProgress(c.id, msg.Folder, msg.Updates)
  386. case *Ping:
  387. l.Debugln("read Ping message")
  388. if state != stateReady {
  389. return fmt.Errorf("protocol error: ping message in state %d", state)
  390. }
  391. // Nothing
  392. case *Close:
  393. l.Debugln("read Close message")
  394. return errors.New(msg.Reason)
  395. default:
  396. l.Debugf("read unknown message: %+T", msg)
  397. return fmt.Errorf("protocol error: %s: unknown or empty message", c.id)
  398. }
  399. }
  400. }
  401. func (c *rawConnection) readMessage(fourByteBuf []byte) (message, error) {
  402. hdr, err := c.readHeader(fourByteBuf)
  403. if err != nil {
  404. return nil, err
  405. }
  406. return c.readMessageAfterHeader(hdr, fourByteBuf)
  407. }
  408. func (c *rawConnection) readMessageAfterHeader(hdr Header, fourByteBuf []byte) (message, error) {
  409. // First comes a 4 byte message length
  410. if _, err := io.ReadFull(c.cr, fourByteBuf[:4]); err != nil {
  411. return nil, fmt.Errorf("reading message length: %v", err)
  412. }
  413. msgLen := int32(binary.BigEndian.Uint32(fourByteBuf))
  414. if msgLen < 0 {
  415. return nil, fmt.Errorf("negative message length %d", msgLen)
  416. }
  417. // Then comes the message
  418. buf := BufferPool.Get(int(msgLen))
  419. if _, err := io.ReadFull(c.cr, buf); err != nil {
  420. return nil, fmt.Errorf("reading message: %v", err)
  421. }
  422. // ... which might be compressed
  423. switch hdr.Compression {
  424. case MessageCompressionNone:
  425. // Nothing
  426. case MessageCompressionLZ4:
  427. decomp, err := c.lz4Decompress(buf)
  428. BufferPool.Put(buf)
  429. if err != nil {
  430. return nil, fmt.Errorf("decompressing message: %v", err)
  431. }
  432. buf = decomp
  433. default:
  434. return nil, fmt.Errorf("unknown message compression %d", hdr.Compression)
  435. }
  436. // ... and is then unmarshalled
  437. msg, err := c.newMessage(hdr.Type)
  438. if err != nil {
  439. return nil, err
  440. }
  441. if err := msg.Unmarshal(buf); err != nil {
  442. return nil, fmt.Errorf("unmarshalling message: %v", err)
  443. }
  444. BufferPool.Put(buf)
  445. return msg, nil
  446. }
  447. func (c *rawConnection) readHeader(fourByteBuf []byte) (Header, error) {
  448. // First comes a 2 byte header length
  449. if _, err := io.ReadFull(c.cr, fourByteBuf[:2]); err != nil {
  450. return Header{}, fmt.Errorf("reading length: %v", err)
  451. }
  452. hdrLen := int16(binary.BigEndian.Uint16(fourByteBuf))
  453. if hdrLen < 0 {
  454. return Header{}, fmt.Errorf("negative header length %d", hdrLen)
  455. }
  456. // Then comes the header
  457. buf := BufferPool.Get(int(hdrLen))
  458. if _, err := io.ReadFull(c.cr, buf); err != nil {
  459. return Header{}, fmt.Errorf("reading header: %v", err)
  460. }
  461. var hdr Header
  462. if err := hdr.Unmarshal(buf); err != nil {
  463. return Header{}, fmt.Errorf("unmarshalling header: %v", err)
  464. }
  465. BufferPool.Put(buf)
  466. return hdr, nil
  467. }
  468. func (c *rawConnection) handleIndex(im Index) {
  469. l.Debugf("Index(%v, %v, %d file)", c.id, im.Folder, len(im.Files))
  470. c.receiver.Index(c.id, im.Folder, im.Files)
  471. }
  472. func (c *rawConnection) handleIndexUpdate(im IndexUpdate) {
  473. l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.id, im.Folder, len(im.Files))
  474. c.receiver.IndexUpdate(c.id, im.Folder, im.Files)
  475. }
  476. // checkIndexConsistency verifies a number of invariants on FileInfos received in
  477. // index messages.
  478. func checkIndexConsistency(fs []FileInfo) error {
  479. for _, f := range fs {
  480. if err := checkFileInfoConsistency(f); err != nil {
  481. return fmt.Errorf("%q: %v", f.Name, err)
  482. }
  483. }
  484. return nil
  485. }
  486. // checkFileInfoConsistency verifies a number of invariants on the given FileInfo
  487. func checkFileInfoConsistency(f FileInfo) error {
  488. if err := checkFilename(f.Name); err != nil {
  489. return err
  490. }
  491. switch {
  492. case f.Deleted && len(f.Blocks) != 0:
  493. // Deleted files should have no blocks
  494. return errDeletedHasBlocks
  495. case f.Type == FileInfoTypeDirectory && len(f.Blocks) != 0:
  496. // Directories should have no blocks
  497. return errDirectoryHasBlocks
  498. case !f.Deleted && !f.IsInvalid() && f.Type == FileInfoTypeFile && len(f.Blocks) == 0:
  499. // Non-deleted, non-invalid files should have at least one block
  500. return errFileHasNoBlocks
  501. }
  502. return nil
  503. }
  504. // checkFilename verifies that the given filename is valid according to the
  505. // spec on what's allowed over the wire. A filename failing this test is
  506. // grounds for disconnecting the device.
  507. func checkFilename(name string) error {
  508. cleanedName := path.Clean(name)
  509. if cleanedName != name {
  510. // The filename on the wire should be in canonical format. If
  511. // Clean() managed to clean it up, there was something wrong with
  512. // it.
  513. return errUncleanFilename
  514. }
  515. switch name {
  516. case "", ".", "..":
  517. // These names are always invalid.
  518. return errInvalidFilename
  519. }
  520. if strings.HasPrefix(name, "/") {
  521. // Names are folder relative, not absolute.
  522. return errInvalidFilename
  523. }
  524. if strings.HasPrefix(name, "../") {
  525. // Starting with a dotdot is not allowed. Any other dotdots would
  526. // have been handled by the Clean() call at the top.
  527. return errInvalidFilename
  528. }
  529. return nil
  530. }
  531. func (c *rawConnection) handleRequest(req Request) {
  532. res, err := c.receiver.Request(c.id, req.Folder, req.Name, req.Size, req.Offset, req.Hash, req.WeakHash, req.FromTemporary)
  533. if err != nil {
  534. c.send(&Response{
  535. ID: req.ID,
  536. Code: errorToCode(err),
  537. }, nil)
  538. return
  539. }
  540. done := make(chan struct{})
  541. c.send(&Response{
  542. ID: req.ID,
  543. Data: res.Data(),
  544. Code: errorToCode(nil),
  545. }, done)
  546. <-done
  547. res.Close()
  548. }
  549. func (c *rawConnection) handleResponse(resp Response) {
  550. c.awaitingMut.Lock()
  551. if rc := c.awaiting[resp.ID]; rc != nil {
  552. delete(c.awaiting, resp.ID)
  553. rc <- asyncResult{resp.Data, codeToError(resp.Code)}
  554. close(rc)
  555. }
  556. c.awaitingMut.Unlock()
  557. }
  558. func (c *rawConnection) send(msg message, done chan struct{}) bool {
  559. select {
  560. case c.outbox <- asyncMessage{msg, done}:
  561. return true
  562. case <-c.closed:
  563. if done != nil {
  564. close(done)
  565. }
  566. return false
  567. }
  568. }
  569. func (c *rawConnection) writerLoop() {
  570. select {
  571. case cc := <-c.clusterConfigBox:
  572. err := c.writeMessage(cc)
  573. if err != nil {
  574. c.internalClose(err)
  575. return
  576. }
  577. case <-c.closed:
  578. return
  579. }
  580. for {
  581. select {
  582. case hm := <-c.outbox:
  583. err := c.writeMessage(hm.msg)
  584. if hm.done != nil {
  585. close(hm.done)
  586. }
  587. if err != nil {
  588. c.internalClose(err)
  589. return
  590. }
  591. case <-c.closed:
  592. return
  593. }
  594. }
  595. }
  596. func (c *rawConnection) writeMessage(msg message) error {
  597. if c.shouldCompressMessage(msg) {
  598. return c.writeCompressedMessage(msg)
  599. }
  600. return c.writeUncompressedMessage(msg)
  601. }
  602. func (c *rawConnection) writeCompressedMessage(msg message) error {
  603. size := msg.ProtoSize()
  604. buf := BufferPool.Get(size)
  605. if _, err := msg.MarshalTo(buf); err != nil {
  606. return fmt.Errorf("marshalling message: %v", err)
  607. }
  608. compressed, err := c.lz4Compress(buf)
  609. if err != nil {
  610. return fmt.Errorf("compressing message: %v", err)
  611. }
  612. hdr := Header{
  613. Type: c.typeOf(msg),
  614. Compression: MessageCompressionLZ4,
  615. }
  616. hdrSize := hdr.ProtoSize()
  617. if hdrSize > 1<<16-1 {
  618. panic("impossibly large header")
  619. }
  620. totSize := 2 + hdrSize + 4 + len(compressed)
  621. buf = BufferPool.Upgrade(buf, totSize)
  622. // Header length
  623. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  624. // Header
  625. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  626. return fmt.Errorf("marshalling header: %v", err)
  627. }
  628. // Message length
  629. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(len(compressed)))
  630. // Message
  631. copy(buf[2+hdrSize+4:], compressed)
  632. BufferPool.Put(compressed)
  633. n, err := c.cw.Write(buf)
  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 (%d uncompressed)), err=%v", n, hdrSize, len(compressed), size, err)
  636. if err != nil {
  637. return fmt.Errorf("writing message: %v", err)
  638. }
  639. return nil
  640. }
  641. func (c *rawConnection) writeUncompressedMessage(msg message) error {
  642. size := msg.ProtoSize()
  643. hdr := Header{
  644. Type: c.typeOf(msg),
  645. }
  646. hdrSize := hdr.ProtoSize()
  647. if hdrSize > 1<<16-1 {
  648. panic("impossibly large header")
  649. }
  650. totSize := 2 + hdrSize + 4 + size
  651. buf := BufferPool.Get(totSize)
  652. // Header length
  653. binary.BigEndian.PutUint16(buf, uint16(hdrSize))
  654. // Header
  655. if _, err := hdr.MarshalTo(buf[2:]); err != nil {
  656. return fmt.Errorf("marshalling header: %v", err)
  657. }
  658. // Message length
  659. binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(size))
  660. // Message
  661. if _, err := msg.MarshalTo(buf[2+hdrSize+4:]); err != nil {
  662. return fmt.Errorf("marshalling message: %v", err)
  663. }
  664. n, err := c.cw.Write(buf[:totSize])
  665. BufferPool.Put(buf)
  666. 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)
  667. if err != nil {
  668. return fmt.Errorf("writing message: %v", err)
  669. }
  670. return nil
  671. }
  672. func (c *rawConnection) typeOf(msg message) MessageType {
  673. switch msg.(type) {
  674. case *ClusterConfig:
  675. return messageTypeClusterConfig
  676. case *Index:
  677. return messageTypeIndex
  678. case *IndexUpdate:
  679. return messageTypeIndexUpdate
  680. case *Request:
  681. return messageTypeRequest
  682. case *Response:
  683. return messageTypeResponse
  684. case *DownloadProgress:
  685. return messageTypeDownloadProgress
  686. case *Ping:
  687. return messageTypePing
  688. case *Close:
  689. return messageTypeClose
  690. default:
  691. panic("bug: unknown message type")
  692. }
  693. }
  694. func (c *rawConnection) newMessage(t MessageType) (message, error) {
  695. switch t {
  696. case messageTypeClusterConfig:
  697. return new(ClusterConfig), nil
  698. case messageTypeIndex:
  699. return new(Index), nil
  700. case messageTypeIndexUpdate:
  701. return new(IndexUpdate), nil
  702. case messageTypeRequest:
  703. return new(Request), nil
  704. case messageTypeResponse:
  705. return new(Response), nil
  706. case messageTypeDownloadProgress:
  707. return new(DownloadProgress), nil
  708. case messageTypePing:
  709. return new(Ping), nil
  710. case messageTypeClose:
  711. return new(Close), nil
  712. default:
  713. return nil, errUnknownMessage
  714. }
  715. }
  716. func (c *rawConnection) shouldCompressMessage(msg message) bool {
  717. switch c.compression {
  718. case CompressNever:
  719. return false
  720. case CompressAlways:
  721. // Use compression for large enough messages
  722. return msg.ProtoSize() >= compressionThreshold
  723. case CompressMetadata:
  724. _, isResponse := msg.(*Response)
  725. // Compress if it's large enough and not a response message
  726. return !isResponse && msg.ProtoSize() >= compressionThreshold
  727. default:
  728. panic("unknown compression setting")
  729. }
  730. }
  731. // Close is called when the connection is regularely closed and thus the Close
  732. // BEP message is sent before terminating the actual connection. The error
  733. // argument specifies the reason for closing the connection.
  734. func (c *rawConnection) Close(err error) {
  735. c.sendCloseOnce.Do(func() {
  736. done := make(chan struct{})
  737. c.send(&Close{err.Error()}, done)
  738. select {
  739. case <-done:
  740. case <-c.closed:
  741. }
  742. })
  743. // No more sends are necessary, therefore further steps to close the
  744. // connection outside of this package can proceed immediately.
  745. // And this prevents a potential deadlock due to calling c.receiver.Closed
  746. go c.internalClose(err)
  747. }
  748. // internalClose is called if there is an unexpected error during normal operation.
  749. func (c *rawConnection) internalClose(err error) {
  750. c.closeOnce.Do(func() {
  751. l.Debugln("close due to", err)
  752. close(c.closed)
  753. c.awaitingMut.Lock()
  754. for i, ch := range c.awaiting {
  755. if ch != nil {
  756. close(ch)
  757. delete(c.awaiting, i)
  758. }
  759. }
  760. c.awaitingMut.Unlock()
  761. <-c.dispatcherLoopStopped
  762. c.receiver.Closed(c, err)
  763. })
  764. }
  765. // The pingSender makes sure that we've sent a message within the last
  766. // PingSendInterval. If we already have something sent in the last
  767. // PingSendInterval/2, we do nothing. Otherwise we send a ping message. This
  768. // results in an effecting ping interval of somewhere between
  769. // PingSendInterval/2 and PingSendInterval.
  770. func (c *rawConnection) pingSender() {
  771. ticker := time.NewTicker(PingSendInterval / 2)
  772. defer ticker.Stop()
  773. for {
  774. select {
  775. case <-ticker.C:
  776. d := time.Since(c.cw.Last())
  777. if d < PingSendInterval/2 {
  778. l.Debugln(c.id, "ping skipped after wr", d)
  779. continue
  780. }
  781. l.Debugln(c.id, "ping -> after", d)
  782. c.ping()
  783. case <-c.closed:
  784. return
  785. }
  786. }
  787. }
  788. // The pingReceiver checks that we've received a message (any message will do,
  789. // but we expect pings in the absence of other messages) within the last
  790. // ReceiveTimeout. If not, we close the connection with an ErrTimeout.
  791. func (c *rawConnection) pingReceiver() {
  792. ticker := time.NewTicker(ReceiveTimeout / 2)
  793. defer ticker.Stop()
  794. for {
  795. select {
  796. case <-ticker.C:
  797. d := time.Since(c.cr.Last())
  798. if d > ReceiveTimeout {
  799. l.Debugln(c.id, "ping timeout", d)
  800. c.internalClose(ErrTimeout)
  801. }
  802. l.Debugln(c.id, "last read within", d)
  803. case <-c.closed:
  804. return
  805. }
  806. }
  807. }
  808. type Statistics struct {
  809. At time.Time
  810. InBytesTotal int64
  811. OutBytesTotal int64
  812. }
  813. func (c *rawConnection) Statistics() Statistics {
  814. return Statistics{
  815. At: time.Now(),
  816. InBytesTotal: c.cr.Tot(),
  817. OutBytesTotal: c.cw.Tot(),
  818. }
  819. }
  820. func (c *rawConnection) lz4Compress(src []byte) ([]byte, error) {
  821. var err error
  822. buf := BufferPool.Get(len(src))
  823. buf, err = lz4.Encode(buf, src)
  824. if err != nil {
  825. return nil, err
  826. }
  827. binary.BigEndian.PutUint32(buf, binary.LittleEndian.Uint32(buf))
  828. return buf, nil
  829. }
  830. func (c *rawConnection) lz4Decompress(src []byte) ([]byte, error) {
  831. size := binary.BigEndian.Uint32(src)
  832. binary.LittleEndian.PutUint32(src, size)
  833. var err error
  834. buf := BufferPool.Get(int(size))
  835. buf, err = lz4.Decode(buf, src)
  836. if err != nil {
  837. return nil, err
  838. }
  839. return buf, nil
  840. }