records.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. /*
  2. * Copyright (c) 2023, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package inproxy
  20. import (
  21. "encoding/binary"
  22. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
  23. "github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
  24. "github.com/fxamacker/cbor/v2"
  25. )
  26. // Records are CBOR-encoded data with a preamble, or prefix, indicating the
  27. // encoding schema version, data type, and data length. Records include
  28. // session messages, as well as API requests and responses which are session
  29. // message payloads.
  30. const (
  31. recordVersion = 1
  32. recordTypeFirst = 1
  33. recordTypeSessionPacket = 1
  34. recordTypeSessionRoundTrip = 2
  35. recordTypeAPIProxyAnnounceRequest = 3
  36. recordTypeAPIProxyAnnounceResponse = 4
  37. recordTypeAPIProxyAnswerRequest = 5
  38. recordTypeAPIProxyAnswerResponse = 6
  39. recordTypeAPIClientOfferRequest = 7
  40. recordTypeAPIClientOfferResponse = 8
  41. recordTypeAPIClientRelayedPacketRequest = 9
  42. recordTypeAPIClientRelayedPacketResponse = 10
  43. recordTypeAPIBrokerServerReport = 11
  44. recordTypeAPIServerProxyQualityRequest = 12
  45. recordTypeAPIServerProxyQualityResponse = 13
  46. recordTypeLast = 13
  47. )
  48. func marshalRecord(record interface{}, recordType int) ([]byte, error) {
  49. payload, err := protocol.CBOREncoding.Marshal(record)
  50. if err != nil {
  51. return nil, errors.Trace(err)
  52. }
  53. payload, err = addRecordPreamble(recordType, payload)
  54. if err != nil {
  55. return nil, errors.Trace(err)
  56. }
  57. return payload, nil
  58. }
  59. func unmarshalRecord(expectedRecordType int, payload []byte, record interface{}) error {
  60. payload, err := readRecordPreamble(expectedRecordType, payload)
  61. if err != nil {
  62. return errors.Trace(err)
  63. }
  64. err = cbor.Unmarshal(payload, record)
  65. if err != nil {
  66. return errors.Trace(err)
  67. }
  68. return nil
  69. }
  70. // addRecordPreamble prepends a record preamble to the given record data
  71. // buffer. The input recordType specifies the type to encode; a version
  72. // number identifying the current encoding schema is supplied automatically.
  73. //
  74. // To avoid allocations, addRecordPreamble modifies the input record buffer;
  75. // use like record = append(record, ...).
  76. func addRecordPreamble(
  77. recordType int, record []byte) ([]byte, error) {
  78. if recordVersion < 0 || recordVersion > 0xff {
  79. return nil, errors.TraceNew("invalid record preamble version")
  80. }
  81. if recordType < 0 || recordType > 0xff {
  82. return nil, errors.TraceNew("invalid record preamble type")
  83. }
  84. if len(record) > 0xffff {
  85. return nil, errors.TraceNew("invalid record length")
  86. }
  87. // The preamble:
  88. // [ 1 byte version ][ 1 byte type ][ varint record data length ][ ...record data ... ]
  89. var preamble [2 + binary.MaxVarintLen64]byte
  90. preamble[0] = byte(recordVersion)
  91. preamble[1] = byte(recordType)
  92. preambleLen := 2 + binary.PutUvarint(preamble[2:], uint64(len(record)))
  93. // Attempt to use the input buffer, which will avoid an allocation if it
  94. // has sufficient capacity.
  95. record = append(record, preamble[:preambleLen]...)
  96. copy(record[preambleLen:], record[:len(record)-preambleLen])
  97. copy(record[0:preambleLen], preamble[:preambleLen])
  98. return record, nil
  99. }
  100. // peekRecordPreambleType returns the record type of the record data payload,
  101. // or an error if the preamble is invalid.
  102. func peekRecordPreambleType(payload []byte) (int, error) {
  103. if len(payload) < 2 {
  104. return -1, errors.TraceNew("invalid record preamble length")
  105. }
  106. if int(payload[0]) != recordVersion {
  107. return -1, errors.TraceNew("invalid record preamble version")
  108. }
  109. recordType := int(payload[1])
  110. if recordType < recordTypeFirst || recordType > recordTypeLast {
  111. return -1, errors.Tracef("invalid record preamble type: %d %x", recordType, payload)
  112. }
  113. return recordType, nil
  114. }
  115. // readRecordPreamble consumes the record preamble from the given record data
  116. // payload and returns the remaining record. The record type must match
  117. // expectedRecordType and the version must match a known encoding schema
  118. // version.
  119. //
  120. // To avoid allocations, readRecordPreamble returns a slice of the
  121. // input record buffer; use like record = record[n:].
  122. func readRecordPreamble(expectedRecordType int, payload []byte) ([]byte, error) {
  123. if len(payload) < 2 {
  124. return nil, errors.TraceNew("invalid record preamble length")
  125. }
  126. if int(payload[0]) != recordVersion {
  127. return nil, errors.TraceNew("invalid record preamble version")
  128. }
  129. if int(payload[1]) != expectedRecordType {
  130. return nil, errors.Tracef("unexpected record preamble type")
  131. }
  132. recordDataLength, n := binary.Uvarint(payload[2:])
  133. if (recordDataLength == 0 && n <= 0) || 2+n > len(payload) {
  134. return nil, errors.Tracef("invalid record preamble data length")
  135. }
  136. record := payload[2+n:]
  137. // In the future, the data length field may be used to implement framing
  138. // for a stream of records. For now, this check is simply a sanity check.
  139. if len(record) != int(recordDataLength) {
  140. return nil, errors.TraceNew("unexpected record preamble data length")
  141. }
  142. return record, nil
  143. }