backend.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. package pgproto3
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. "io"
  7. )
  8. // Backend acts as a server for the PostgreSQL wire protocol version 3.
  9. type Backend struct {
  10. cr *chunkReader
  11. w io.Writer
  12. // tracer is used to trace messages when Send or Receive is called. This means an outbound message is traced
  13. // before it is actually transmitted (i.e. before Flush).
  14. tracer *tracer
  15. wbuf []byte
  16. encodeError error
  17. // Frontend message flyweights
  18. bind Bind
  19. cancelRequest CancelRequest
  20. _close Close
  21. copyFail CopyFail
  22. copyData CopyData
  23. copyDone CopyDone
  24. describe Describe
  25. execute Execute
  26. flush Flush
  27. functionCall FunctionCall
  28. gssEncRequest GSSEncRequest
  29. parse Parse
  30. query Query
  31. sslRequest SSLRequest
  32. startupMessage StartupMessage
  33. sync Sync
  34. terminate Terminate
  35. bodyLen int
  36. maxBodyLen int // maxBodyLen is the maximum length of a message body in octets. If a message body exceeds this length, Receive will return an error.
  37. msgType byte
  38. partialMsg bool
  39. authType uint32
  40. }
  41. const (
  42. minStartupPacketLen = 4 // minStartupPacketLen is a single 32-bit int version or code.
  43. maxStartupPacketLen = 10_000 // maxStartupPacketLen is MAX_STARTUP_PACKET_LENGTH from PG source.
  44. )
  45. // NewBackend creates a new Backend.
  46. func NewBackend(r io.Reader, w io.Writer) *Backend {
  47. cr := newChunkReader(r, 0)
  48. return &Backend{cr: cr, w: w}
  49. }
  50. // Send sends a message to the frontend (i.e. the client). The message is buffered until Flush is called. Any error
  51. // encountered will be returned from Flush.
  52. func (b *Backend) Send(msg BackendMessage) {
  53. if b.encodeError != nil {
  54. return
  55. }
  56. prevLen := len(b.wbuf)
  57. newBuf, err := msg.Encode(b.wbuf)
  58. if err != nil {
  59. b.encodeError = err
  60. return
  61. }
  62. b.wbuf = newBuf
  63. if b.tracer != nil {
  64. b.tracer.traceMessage('B', int32(len(b.wbuf)-prevLen), msg)
  65. }
  66. }
  67. // Flush writes any pending messages to the frontend (i.e. the client).
  68. func (b *Backend) Flush() error {
  69. if err := b.encodeError; err != nil {
  70. b.encodeError = nil
  71. b.wbuf = b.wbuf[:0]
  72. return &writeError{err: err, safeToRetry: true}
  73. }
  74. n, err := b.w.Write(b.wbuf)
  75. const maxLen = 1024
  76. if len(b.wbuf) > maxLen {
  77. b.wbuf = make([]byte, 0, maxLen)
  78. } else {
  79. b.wbuf = b.wbuf[:0]
  80. }
  81. if err != nil {
  82. return &writeError{err: err, safeToRetry: n == 0}
  83. }
  84. return nil
  85. }
  86. // Trace starts tracing the message traffic to w. It writes in a similar format to that produced by the libpq function
  87. // PQtrace.
  88. func (b *Backend) Trace(w io.Writer, options TracerOptions) {
  89. b.tracer = &tracer{
  90. w: w,
  91. buf: &bytes.Buffer{},
  92. TracerOptions: options,
  93. }
  94. }
  95. // Untrace stops tracing.
  96. func (b *Backend) Untrace() {
  97. b.tracer = nil
  98. }
  99. // ReceiveStartupMessage receives the initial connection message. This method is used of the normal Receive method
  100. // because the initial connection message is "special" and does not include the message type as the first byte. This
  101. // will return either a StartupMessage, SSLRequest, GSSEncRequest, or CancelRequest.
  102. func (b *Backend) ReceiveStartupMessage() (FrontendMessage, error) {
  103. buf, err := b.cr.Next(4)
  104. if err != nil {
  105. return nil, err
  106. }
  107. msgSize := int(binary.BigEndian.Uint32(buf) - 4)
  108. if msgSize < minStartupPacketLen || msgSize > maxStartupPacketLen {
  109. return nil, fmt.Errorf("invalid length of startup packet: %d", msgSize)
  110. }
  111. buf, err = b.cr.Next(msgSize)
  112. if err != nil {
  113. return nil, translateEOFtoErrUnexpectedEOF(err)
  114. }
  115. code := binary.BigEndian.Uint32(buf)
  116. switch code {
  117. case ProtocolVersionNumber:
  118. err = b.startupMessage.Decode(buf)
  119. if err != nil {
  120. return nil, err
  121. }
  122. return &b.startupMessage, nil
  123. case sslRequestNumber:
  124. err = b.sslRequest.Decode(buf)
  125. if err != nil {
  126. return nil, err
  127. }
  128. return &b.sslRequest, nil
  129. case cancelRequestCode:
  130. err = b.cancelRequest.Decode(buf)
  131. if err != nil {
  132. return nil, err
  133. }
  134. return &b.cancelRequest, nil
  135. case gssEncReqNumber:
  136. err = b.gssEncRequest.Decode(buf)
  137. if err != nil {
  138. return nil, err
  139. }
  140. return &b.gssEncRequest, nil
  141. default:
  142. return nil, fmt.Errorf("unknown startup message code: %d", code)
  143. }
  144. }
  145. // Receive receives a message from the frontend. The returned message is only valid until the next call to Receive.
  146. func (b *Backend) Receive() (FrontendMessage, error) {
  147. if !b.partialMsg {
  148. header, err := b.cr.Next(5)
  149. if err != nil {
  150. return nil, translateEOFtoErrUnexpectedEOF(err)
  151. }
  152. b.msgType = header[0]
  153. msgLength := int(binary.BigEndian.Uint32(header[1:]))
  154. if msgLength < 4 {
  155. return nil, fmt.Errorf("invalid message length: %d", msgLength)
  156. }
  157. b.bodyLen = msgLength - 4
  158. if b.maxBodyLen > 0 && b.bodyLen > b.maxBodyLen {
  159. return nil, &ExceededMaxBodyLenErr{b.maxBodyLen, b.bodyLen}
  160. }
  161. b.partialMsg = true
  162. }
  163. var msg FrontendMessage
  164. switch b.msgType {
  165. case 'B':
  166. msg = &b.bind
  167. case 'C':
  168. msg = &b._close
  169. case 'D':
  170. msg = &b.describe
  171. case 'E':
  172. msg = &b.execute
  173. case 'F':
  174. msg = &b.functionCall
  175. case 'f':
  176. msg = &b.copyFail
  177. case 'd':
  178. msg = &b.copyData
  179. case 'c':
  180. msg = &b.copyDone
  181. case 'H':
  182. msg = &b.flush
  183. case 'P':
  184. msg = &b.parse
  185. case 'p':
  186. switch b.authType {
  187. case AuthTypeSASL:
  188. msg = &SASLInitialResponse{}
  189. case AuthTypeSASLContinue:
  190. msg = &SASLResponse{}
  191. case AuthTypeSASLFinal:
  192. msg = &SASLResponse{}
  193. case AuthTypeGSS, AuthTypeGSSCont:
  194. msg = &GSSResponse{}
  195. case AuthTypeCleartextPassword, AuthTypeMD5Password:
  196. fallthrough
  197. default:
  198. // to maintain backwards compatibility
  199. msg = &PasswordMessage{}
  200. }
  201. case 'Q':
  202. msg = &b.query
  203. case 'S':
  204. msg = &b.sync
  205. case 'X':
  206. msg = &b.terminate
  207. default:
  208. return nil, fmt.Errorf("unknown message type: %c", b.msgType)
  209. }
  210. msgBody, err := b.cr.Next(b.bodyLen)
  211. if err != nil {
  212. return nil, translateEOFtoErrUnexpectedEOF(err)
  213. }
  214. b.partialMsg = false
  215. err = msg.Decode(msgBody)
  216. if err != nil {
  217. return nil, err
  218. }
  219. if b.tracer != nil {
  220. b.tracer.traceMessage('F', int32(5+len(msgBody)), msg)
  221. }
  222. return msg, nil
  223. }
  224. // SetAuthType sets the authentication type in the backend.
  225. // Since multiple message types can start with 'p', SetAuthType allows
  226. // contextual identification of FrontendMessages. For example, in the
  227. // PG message flow documentation for PasswordMessage:
  228. //
  229. // Byte1('p')
  230. //
  231. // Identifies the message as a password response. Note that this is also used for
  232. // GSSAPI, SSPI and SASL response messages. The exact message type can be deduced from
  233. // the context.
  234. //
  235. // Since the Frontend does not know about the state of a backend, it is important
  236. // to call SetAuthType() after an authentication request is received by the Frontend.
  237. func (b *Backend) SetAuthType(authType uint32) error {
  238. switch authType {
  239. case AuthTypeOk,
  240. AuthTypeCleartextPassword,
  241. AuthTypeMD5Password,
  242. AuthTypeSCMCreds,
  243. AuthTypeGSS,
  244. AuthTypeGSSCont,
  245. AuthTypeSSPI,
  246. AuthTypeSASL,
  247. AuthTypeSASLContinue,
  248. AuthTypeSASLFinal:
  249. b.authType = authType
  250. default:
  251. return fmt.Errorf("authType not recognized: %d", authType)
  252. }
  253. return nil
  254. }
  255. // SetMaxBodyLen sets the maximum length of a message body in octets.
  256. // If a message body exceeds this length, Receive will return an error.
  257. // This is useful for protecting against malicious clients that send
  258. // large messages with the intent of causing memory exhaustion.
  259. // The default value is 0.
  260. // If maxBodyLen is 0, then no maximum is enforced.
  261. func (b *Backend) SetMaxBodyLen(maxBodyLen int) {
  262. b.maxBodyLen = maxBodyLen
  263. }