protocol.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package udp
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "io"
  6. )
  7. type Action int32
  8. const (
  9. ActionConnect Action = iota
  10. ActionAnnounce
  11. ActionScrape
  12. ActionError
  13. )
  14. const ConnectRequestConnectionId = 0x41727101980
  15. const (
  16. // BEP 41
  17. optionTypeEndOfOptions = 0
  18. optionTypeNOP = 1
  19. optionTypeURLData = 2
  20. )
  21. type TransactionId = int32
  22. type ConnectionId = uint64
  23. type ConnectionRequest struct {
  24. ConnectionId ConnectionId
  25. Action Action
  26. TransactionId TransactionId
  27. }
  28. type ConnectionResponse struct {
  29. ConnectionId ConnectionId
  30. }
  31. type ResponseHeader struct {
  32. Action Action
  33. TransactionId TransactionId
  34. }
  35. type RequestHeader struct {
  36. ConnectionId ConnectionId
  37. Action Action
  38. TransactionId TransactionId
  39. } // 16 bytes
  40. type AnnounceResponseHeader struct {
  41. Interval int32
  42. Leechers int32
  43. Seeders int32
  44. }
  45. type InfoHash = [20]byte
  46. func marshal(data interface{}) (b []byte, err error) {
  47. var buf bytes.Buffer
  48. err = Write(&buf, data)
  49. b = buf.Bytes()
  50. return
  51. }
  52. func mustMarshal(data interface{}) []byte {
  53. b, err := marshal(data)
  54. if err != nil {
  55. panic(err)
  56. }
  57. return b
  58. }
  59. // This is for fixed-size, builtin types only I think.
  60. func Write(w io.Writer, data interface{}) error {
  61. return binary.Write(w, binary.BigEndian, data)
  62. }
  63. func Read(r io.Reader, data interface{}) error {
  64. return binary.Read(r, binary.BigEndian, data)
  65. }