1 /*
2  * PgBouncer - Lightweight connection pooler for PostgreSQL.
3  *
4  * Copyright (c) 2007-2009  Marko Kreen, Skype Technologies OÜ
5  *
6  * Permission to use, copy, modify, and/or distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 /* old style V2 header: len:4b code:4b */
20 #define OLD_HEADER_LEN	8
21 /* new style V3 packet header len - type:1b, len:4b */
22 #define NEW_HEADER_LEN	5
23 
24 /*
25  * parsed packet header, plus whatever data is
26  * available in SBuf for this packet.
27  *
28  * if (pkt->len == mbuf_avail(&pkt->data))
29  *     packet is fully in buffer
30  *
31  * get_header() points pkt->data.pos after header.
32  * to packet body.
33  */
34 struct PktHdr {
35 	unsigned type;
36 	unsigned len;
37 	struct MBuf data;
38 };
39 
40 bool get_header(struct MBuf *data, PktHdr *pkt) _MUSTCHECK;
41 
42 bool send_pooler_error(PgSocket *client, bool send_ready, bool level_fatal, const char *msg)  /*_MUSTCHECK*/;
43 void log_server_error(const char *note, PktHdr *pkt);
44 void parse_server_error(PktHdr *pkt, const char **level_p, const char **msg_p);
45 
46 bool add_welcome_parameter(PgPool *pool, const char *key, const char *val) _MUSTCHECK;
47 void finish_welcome_msg(PgSocket *server);
48 bool welcome_client(PgSocket *client) _MUSTCHECK;
49 
50 bool answer_authreq(PgSocket *server, PktHdr *pkt) _MUSTCHECK;
51 
52 bool send_startup_packet(PgSocket *server) _MUSTCHECK;
53 bool send_sslreq_packet(PgSocket *server) _MUSTCHECK;
54 
55 int scan_text_result(struct MBuf *pkt, const char *tupdesc, ...) _MUSTCHECK;
56 
57 /* is packet completely in our buffer */
incomplete_pkt(const PktHdr * pkt)58 static inline bool incomplete_pkt(const PktHdr *pkt)
59 {
60 	return mbuf_written(&pkt->data) != pkt->len;
61 }
62 
63 /* is packet header completely in buffer */
incomplete_header(const struct MBuf * data)64 static inline bool incomplete_header(const struct MBuf *data) {
65 	uint32_t avail = mbuf_avail_for_read(data);
66 	if (avail >= OLD_HEADER_LEN)
67 		return false;
68 	if (avail < NEW_HEADER_LEN)
69 		return true;
70 	/* is it old V2 header? */
71 	return data->data[data->read_pos] == 0;
72 }
73 
74 /* one char desc */
pkt_desc(const PktHdr * pkt)75 static inline char pkt_desc(const PktHdr *pkt)
76 {
77 	return pkt->type > 256 ? '!' : pkt->type;
78 }
79