records.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. recordTypeAPIClientDSLRequest = 14
  47. recordTypeAPIClientDSLResponse = 15
  48. recordTypeLast = 15
  49. )
  50. func marshalRecord(record interface{}, recordType int) ([]byte, error) {
  51. payload, err := protocol.CBOREncoding.Marshal(record)
  52. if err != nil {
  53. return nil, errors.Trace(err)
  54. }
  55. payload, err = addRecordPreamble(recordType, payload)
  56. if err != nil {
  57. return nil, errors.Trace(err)
  58. }
  59. return payload, nil
  60. }
  61. func unmarshalRecord(expectedRecordType int, payload []byte, record interface{}) error {
  62. payload, err := readRecordPreamble(expectedRecordType, payload)
  63. if err != nil {
  64. return errors.Trace(err)
  65. }
  66. err = cbor.Unmarshal(payload, record)
  67. if err != nil {
  68. return errors.Trace(err)
  69. }
  70. return nil
  71. }
  72. // addRecordPreamble prepends a record preamble to the given record data
  73. // buffer. The input recordType specifies the type to encode; a version
  74. // number identifying the current encoding schema is supplied automatically.
  75. //
  76. // To avoid allocations, addRecordPreamble modifies the input record buffer;
  77. // use like record = append(record, ...).
  78. func addRecordPreamble(
  79. recordType int, record []byte) ([]byte, error) {
  80. if recordVersion < 0 || recordVersion > 0xff {
  81. return nil, errors.TraceNew("invalid record preamble version")
  82. }
  83. if recordType < 0 || recordType > 0xff {
  84. return nil, errors.TraceNew("invalid record preamble type")
  85. }
  86. if len(record) > 0xffff {
  87. return nil, errors.TraceNew("invalid record length")
  88. }
  89. // The preamble:
  90. // [ 1 byte version ][ 1 byte type ][ varint record data length ][ ...record data ... ]
  91. var preamble [2 + binary.MaxVarintLen64]byte
  92. preamble[0] = byte(recordVersion)
  93. preamble[1] = byte(recordType)
  94. preambleLen := 2 + binary.PutUvarint(preamble[2:], uint64(len(record)))
  95. // Attempt to use the input buffer, which will avoid an allocation if it
  96. // has sufficient capacity.
  97. record = append(record, preamble[:preambleLen]...)
  98. copy(record[preambleLen:], record[:len(record)-preambleLen])
  99. copy(record[0:preambleLen], preamble[:preambleLen])
  100. return record, nil
  101. }
  102. // peekRecordPreambleType returns the record type of the record data payload,
  103. // or an error if the preamble is invalid.
  104. func peekRecordPreambleType(payload []byte) (int, error) {
  105. if len(payload) < 2 {
  106. return -1, errors.TraceNew("invalid record preamble length")
  107. }
  108. if int(payload[0]) != recordVersion {
  109. return -1, errors.TraceNew("invalid record preamble version")
  110. }
  111. recordType := int(payload[1])
  112. if recordType < recordTypeFirst || recordType > recordTypeLast {
  113. return -1, errors.Tracef("invalid record preamble type: %d %x", recordType, payload)
  114. }
  115. return recordType, nil
  116. }
  117. // readRecordPreamble consumes the record preamble from the given record data
  118. // payload and returns the remaining record. The record type must match
  119. // expectedRecordType and the version must match a known encoding schema
  120. // version.
  121. //
  122. // To avoid allocations, readRecordPreamble returns a slice of the
  123. // input record buffer; use like record = record[n:].
  124. func readRecordPreamble(expectedRecordType int, payload []byte) ([]byte, error) {
  125. if len(payload) < 2 {
  126. return nil, errors.TraceNew("invalid record preamble length")
  127. }
  128. if int(payload[0]) != recordVersion {
  129. return nil, errors.TraceNew("invalid record preamble version")
  130. }
  131. if int(payload[1]) != expectedRecordType {
  132. return nil, errors.Tracef("unexpected record preamble type")
  133. }
  134. recordDataLength, n := binary.Uvarint(payload[2:])
  135. if (recordDataLength == 0 && n <= 0) || 2+n > len(payload) {
  136. return nil, errors.Tracef("invalid record preamble data length")
  137. }
  138. record := payload[2+n:]
  139. // In the future, the data length field may be used to implement framing
  140. // for a stream of records. For now, this check is simply a sanity check.
  141. if len(record) != int(recordDataLength) {
  142. return nil, errors.TraceNew("unexpected record preamble data length")
  143. }
  144. return record, nil
  145. }