frontend.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. package pgproto3
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "errors"
  6. "fmt"
  7. "io"
  8. )
  9. // Frontend acts as a client for the PostgreSQL wire protocol version 3.
  10. type Frontend struct {
  11. cr *chunkReader
  12. w io.Writer
  13. // tracer is used to trace messages when Send or Receive is called. This means an outbound message is traced
  14. // before it is actually transmitted (i.e. before Flush). It is safe to change this variable when the Frontend is
  15. // idle. Setting and unsetting tracer provides equivalent functionality to PQtrace and PQuntrace in libpq.
  16. tracer *tracer
  17. wbuf []byte
  18. encodeError error
  19. // Backend message flyweights
  20. authenticationOk AuthenticationOk
  21. authenticationCleartextPassword AuthenticationCleartextPassword
  22. authenticationMD5Password AuthenticationMD5Password
  23. authenticationGSS AuthenticationGSS
  24. authenticationGSSContinue AuthenticationGSSContinue
  25. authenticationSASL AuthenticationSASL
  26. authenticationSASLContinue AuthenticationSASLContinue
  27. authenticationSASLFinal AuthenticationSASLFinal
  28. backendKeyData BackendKeyData
  29. bindComplete BindComplete
  30. closeComplete CloseComplete
  31. commandComplete CommandComplete
  32. copyBothResponse CopyBothResponse
  33. copyData CopyData
  34. copyInResponse CopyInResponse
  35. copyOutResponse CopyOutResponse
  36. copyDone CopyDone
  37. dataRow DataRow
  38. emptyQueryResponse EmptyQueryResponse
  39. errorResponse ErrorResponse
  40. functionCallResponse FunctionCallResponse
  41. noData NoData
  42. noticeResponse NoticeResponse
  43. notificationResponse NotificationResponse
  44. parameterDescription ParameterDescription
  45. parameterStatus ParameterStatus
  46. parseComplete ParseComplete
  47. readyForQuery ReadyForQuery
  48. rowDescription RowDescription
  49. portalSuspended PortalSuspended
  50. bodyLen int
  51. 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.
  52. msgType byte
  53. partialMsg bool
  54. authType uint32
  55. }
  56. // NewFrontend creates a new Frontend.
  57. func NewFrontend(r io.Reader, w io.Writer) *Frontend {
  58. cr := newChunkReader(r, 0)
  59. return &Frontend{cr: cr, w: w}
  60. }
  61. // Send sends a message to the backend (i.e. the server). The message is buffered until Flush is called. Any error
  62. // encountered will be returned from Flush.
  63. //
  64. // Send can work with any FrontendMessage. Some commonly used message types such as Bind have specialized send methods
  65. // such as SendBind. These methods should be preferred when the type of message is known up front (e.g. when building an
  66. // extended query protocol query) as they may be faster due to knowing the type of msg rather than it being hidden
  67. // behind an interface.
  68. func (f *Frontend) Send(msg FrontendMessage) {
  69. if f.encodeError != nil {
  70. return
  71. }
  72. prevLen := len(f.wbuf)
  73. newBuf, err := msg.Encode(f.wbuf)
  74. if err != nil {
  75. f.encodeError = err
  76. return
  77. }
  78. f.wbuf = newBuf
  79. if f.tracer != nil {
  80. f.tracer.traceMessage('F', int32(len(f.wbuf)-prevLen), msg)
  81. }
  82. }
  83. // Flush writes any pending messages to the backend (i.e. the server).
  84. func (f *Frontend) Flush() error {
  85. if err := f.encodeError; err != nil {
  86. f.encodeError = nil
  87. f.wbuf = f.wbuf[:0]
  88. return &writeError{err: err, safeToRetry: true}
  89. }
  90. if len(f.wbuf) == 0 {
  91. return nil
  92. }
  93. n, err := f.w.Write(f.wbuf)
  94. const maxLen = 1024
  95. if len(f.wbuf) > maxLen {
  96. f.wbuf = make([]byte, 0, maxLen)
  97. } else {
  98. f.wbuf = f.wbuf[:0]
  99. }
  100. if err != nil {
  101. return &writeError{err: err, safeToRetry: n == 0}
  102. }
  103. return nil
  104. }
  105. // Trace starts tracing the message traffic to w. It writes in a similar format to that produced by the libpq function
  106. // PQtrace.
  107. func (f *Frontend) Trace(w io.Writer, options TracerOptions) {
  108. f.tracer = &tracer{
  109. w: w,
  110. buf: &bytes.Buffer{},
  111. TracerOptions: options,
  112. }
  113. }
  114. // Untrace stops tracing.
  115. func (f *Frontend) Untrace() {
  116. f.tracer = nil
  117. }
  118. // SendBind sends a Bind message to the backend (i.e. the server). The message is buffered until Flush is called. Any
  119. // error encountered will be returned from Flush.
  120. func (f *Frontend) SendBind(msg *Bind) {
  121. if f.encodeError != nil {
  122. return
  123. }
  124. prevLen := len(f.wbuf)
  125. newBuf, err := msg.Encode(f.wbuf)
  126. if err != nil {
  127. f.encodeError = err
  128. return
  129. }
  130. f.wbuf = newBuf
  131. if f.tracer != nil {
  132. f.tracer.traceBind('F', int32(len(f.wbuf)-prevLen), msg)
  133. }
  134. }
  135. // SendParse sends a Parse message to the backend (i.e. the server). The message is buffered until Flush is called. Any
  136. // error encountered will be returned from Flush.
  137. func (f *Frontend) SendParse(msg *Parse) {
  138. if f.encodeError != nil {
  139. return
  140. }
  141. prevLen := len(f.wbuf)
  142. newBuf, err := msg.Encode(f.wbuf)
  143. if err != nil {
  144. f.encodeError = err
  145. return
  146. }
  147. f.wbuf = newBuf
  148. if f.tracer != nil {
  149. f.tracer.traceParse('F', int32(len(f.wbuf)-prevLen), msg)
  150. }
  151. }
  152. // SendClose sends a Close message to the backend (i.e. the server). The message is buffered until Flush is called. Any
  153. // error encountered will be returned from Flush.
  154. func (f *Frontend) SendClose(msg *Close) {
  155. if f.encodeError != nil {
  156. return
  157. }
  158. prevLen := len(f.wbuf)
  159. newBuf, err := msg.Encode(f.wbuf)
  160. if err != nil {
  161. f.encodeError = err
  162. return
  163. }
  164. f.wbuf = newBuf
  165. if f.tracer != nil {
  166. f.tracer.traceClose('F', int32(len(f.wbuf)-prevLen), msg)
  167. }
  168. }
  169. // SendDescribe sends a Describe message to the backend (i.e. the server). The message is buffered until Flush is
  170. // called. Any error encountered will be returned from Flush.
  171. func (f *Frontend) SendDescribe(msg *Describe) {
  172. if f.encodeError != nil {
  173. return
  174. }
  175. prevLen := len(f.wbuf)
  176. newBuf, err := msg.Encode(f.wbuf)
  177. if err != nil {
  178. f.encodeError = err
  179. return
  180. }
  181. f.wbuf = newBuf
  182. if f.tracer != nil {
  183. f.tracer.traceDescribe('F', int32(len(f.wbuf)-prevLen), msg)
  184. }
  185. }
  186. // SendExecute sends an Execute message to the backend (i.e. the server). The message is buffered until Flush is called.
  187. // Any error encountered will be returned from Flush.
  188. func (f *Frontend) SendExecute(msg *Execute) {
  189. if f.encodeError != nil {
  190. return
  191. }
  192. prevLen := len(f.wbuf)
  193. newBuf, err := msg.Encode(f.wbuf)
  194. if err != nil {
  195. f.encodeError = err
  196. return
  197. }
  198. f.wbuf = newBuf
  199. if f.tracer != nil {
  200. f.tracer.TraceQueryute('F', int32(len(f.wbuf)-prevLen), msg)
  201. }
  202. }
  203. // SendSync sends a Sync message to the backend (i.e. the server). The message is buffered until Flush is called. Any
  204. // error encountered will be returned from Flush.
  205. func (f *Frontend) SendSync(msg *Sync) {
  206. if f.encodeError != nil {
  207. return
  208. }
  209. prevLen := len(f.wbuf)
  210. newBuf, err := msg.Encode(f.wbuf)
  211. if err != nil {
  212. f.encodeError = err
  213. return
  214. }
  215. f.wbuf = newBuf
  216. if f.tracer != nil {
  217. f.tracer.traceSync('F', int32(len(f.wbuf)-prevLen), msg)
  218. }
  219. }
  220. // SendQuery sends a Query message to the backend (i.e. the server). The message is buffered until Flush is called. Any
  221. // error encountered will be returned from Flush.
  222. func (f *Frontend) SendQuery(msg *Query) {
  223. if f.encodeError != nil {
  224. return
  225. }
  226. prevLen := len(f.wbuf)
  227. newBuf, err := msg.Encode(f.wbuf)
  228. if err != nil {
  229. f.encodeError = err
  230. return
  231. }
  232. f.wbuf = newBuf
  233. if f.tracer != nil {
  234. f.tracer.traceQuery('F', int32(len(f.wbuf)-prevLen), msg)
  235. }
  236. }
  237. // SendUnbufferedEncodedCopyData immediately sends an encoded CopyData message to the backend (i.e. the server). This method
  238. // is more efficient than sending a CopyData message with Send as the message data is not copied to the internal buffer
  239. // before being written out. The internal buffer is flushed before the message is sent.
  240. func (f *Frontend) SendUnbufferedEncodedCopyData(msg []byte) error {
  241. err := f.Flush()
  242. if err != nil {
  243. return err
  244. }
  245. n, err := f.w.Write(msg)
  246. if err != nil {
  247. return &writeError{err: err, safeToRetry: n == 0}
  248. }
  249. if f.tracer != nil {
  250. f.tracer.traceCopyData('F', int32(len(msg)-1), &CopyData{})
  251. }
  252. return nil
  253. }
  254. func translateEOFtoErrUnexpectedEOF(err error) error {
  255. if err == io.EOF {
  256. return io.ErrUnexpectedEOF
  257. }
  258. return err
  259. }
  260. // Receive receives a message from the backend. The returned message is only valid until the next call to Receive.
  261. func (f *Frontend) Receive() (BackendMessage, error) {
  262. if !f.partialMsg {
  263. header, err := f.cr.Next(5)
  264. if err != nil {
  265. return nil, translateEOFtoErrUnexpectedEOF(err)
  266. }
  267. f.msgType = header[0]
  268. msgLength := int(binary.BigEndian.Uint32(header[1:]))
  269. if msgLength < 4 {
  270. return nil, fmt.Errorf("invalid message length: %d", msgLength)
  271. }
  272. f.bodyLen = msgLength - 4
  273. if f.maxBodyLen > 0 && f.bodyLen > f.maxBodyLen {
  274. return nil, &ExceededMaxBodyLenErr{f.maxBodyLen, f.bodyLen}
  275. }
  276. f.partialMsg = true
  277. }
  278. msgBody, err := f.cr.Next(f.bodyLen)
  279. if err != nil {
  280. return nil, translateEOFtoErrUnexpectedEOF(err)
  281. }
  282. f.partialMsg = false
  283. var msg BackendMessage
  284. switch f.msgType {
  285. case '1':
  286. msg = &f.parseComplete
  287. case '2':
  288. msg = &f.bindComplete
  289. case '3':
  290. msg = &f.closeComplete
  291. case 'A':
  292. msg = &f.notificationResponse
  293. case 'c':
  294. msg = &f.copyDone
  295. case 'C':
  296. msg = &f.commandComplete
  297. case 'd':
  298. msg = &f.copyData
  299. case 'D':
  300. msg = &f.dataRow
  301. case 'E':
  302. msg = &f.errorResponse
  303. case 'G':
  304. msg = &f.copyInResponse
  305. case 'H':
  306. msg = &f.copyOutResponse
  307. case 'I':
  308. msg = &f.emptyQueryResponse
  309. case 'K':
  310. msg = &f.backendKeyData
  311. case 'n':
  312. msg = &f.noData
  313. case 'N':
  314. msg = &f.noticeResponse
  315. case 'R':
  316. var err error
  317. msg, err = f.findAuthenticationMessageType(msgBody)
  318. if err != nil {
  319. return nil, err
  320. }
  321. case 's':
  322. msg = &f.portalSuspended
  323. case 'S':
  324. msg = &f.parameterStatus
  325. case 't':
  326. msg = &f.parameterDescription
  327. case 'T':
  328. msg = &f.rowDescription
  329. case 'V':
  330. msg = &f.functionCallResponse
  331. case 'W':
  332. msg = &f.copyBothResponse
  333. case 'Z':
  334. msg = &f.readyForQuery
  335. default:
  336. return nil, fmt.Errorf("unknown message type: %c", f.msgType)
  337. }
  338. err = msg.Decode(msgBody)
  339. if err != nil {
  340. return nil, err
  341. }
  342. if f.tracer != nil {
  343. f.tracer.traceMessage('B', int32(5+len(msgBody)), msg)
  344. }
  345. return msg, nil
  346. }
  347. // Authentication message type constants.
  348. // See src/include/libpq/pqcomm.h for all
  349. // constants.
  350. const (
  351. AuthTypeOk = 0
  352. AuthTypeCleartextPassword = 3
  353. AuthTypeMD5Password = 5
  354. AuthTypeSCMCreds = 6
  355. AuthTypeGSS = 7
  356. AuthTypeGSSCont = 8
  357. AuthTypeSSPI = 9
  358. AuthTypeSASL = 10
  359. AuthTypeSASLContinue = 11
  360. AuthTypeSASLFinal = 12
  361. )
  362. func (f *Frontend) findAuthenticationMessageType(src []byte) (BackendMessage, error) {
  363. if len(src) < 4 {
  364. return nil, errors.New("authentication message too short")
  365. }
  366. f.authType = binary.BigEndian.Uint32(src[:4])
  367. switch f.authType {
  368. case AuthTypeOk:
  369. return &f.authenticationOk, nil
  370. case AuthTypeCleartextPassword:
  371. return &f.authenticationCleartextPassword, nil
  372. case AuthTypeMD5Password:
  373. return &f.authenticationMD5Password, nil
  374. case AuthTypeSCMCreds:
  375. return nil, errors.New("AuthTypeSCMCreds is unimplemented")
  376. case AuthTypeGSS:
  377. return &f.authenticationGSS, nil
  378. case AuthTypeGSSCont:
  379. return &f.authenticationGSSContinue, nil
  380. case AuthTypeSSPI:
  381. return nil, errors.New("AuthTypeSSPI is unimplemented")
  382. case AuthTypeSASL:
  383. return &f.authenticationSASL, nil
  384. case AuthTypeSASLContinue:
  385. return &f.authenticationSASLContinue, nil
  386. case AuthTypeSASLFinal:
  387. return &f.authenticationSASLFinal, nil
  388. default:
  389. return nil, fmt.Errorf("unknown authentication type: %d", f.authType)
  390. }
  391. }
  392. // GetAuthType returns the authType used in the current state of the frontend.
  393. // See SetAuthType for more information.
  394. func (f *Frontend) GetAuthType() uint32 {
  395. return f.authType
  396. }
  397. func (f *Frontend) ReadBufferLen() int {
  398. return f.cr.wp - f.cr.rp
  399. }
  400. // SetMaxBodyLen sets the maximum length of a message body in octets.
  401. // If a message body exceeds this length, Receive will return an error.
  402. // This is useful for protecting against a corrupted server that sends
  403. // messages with incorrect length, which can cause memory exhaustion.
  404. // The default value is 0.
  405. // If maxBodyLen is 0, then no maximum is enforced.
  406. func (f *Frontend) SetMaxBodyLen(maxBodyLen int) {
  407. f.maxBodyLen = maxBodyLen
  408. }