forked from pgbouncer/pgbouncer
/
client.c
408 lines (356 loc) · 10.4 KB
/
client.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/*
* PgBouncer - Lightweight connection pooler for PostgreSQL.
*
* Copyright (c) 2007-2009 Marko Kreen, Skype Technologies OÜ
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Client connection handling
*/
#include "bouncer.h"
static bool check_client_passwd(PgSocket *client, const char *passwd)
{
char md5[MD5_PASSWD_LEN + 1];
const char *correct;
PgUser *user = client->auth_user;
/* disallow empty passwords */
if (!*passwd || !*user->passwd)
return false;
switch (cf_auth_type) {
case AUTH_PLAIN:
return strcmp(user->passwd, passwd) == 0;
case AUTH_CRYPT:
correct = crypt(user->passwd, (char *)client->tmp_login_salt);
return correct && strcmp(correct, passwd) == 0;
case AUTH_MD5:
if (strlen(passwd) != MD5_PASSWD_LEN)
return false;
if (!isMD5(user->passwd))
pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd);
pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5);
return strcmp(md5, passwd) == 0;
}
return false;
}
bool set_pool(PgSocket *client, const char *dbname, const char *username)
{
PgDatabase *db;
PgUser *user;
/* find database */
db = find_database(dbname);
if (!db) {
db = register_auto_database(dbname);
if (!db) {
disconnect_client(client, true, "No such database");
return false;
}
else {
slog_info(client, "registered new auto-database: db = %s", dbname );
}
}
/* find user */
if (cf_auth_type == AUTH_ANY) {
/* ignore requested user */
user = NULL;
if (db->forced_user == NULL) {
slog_error(client, "auth_type=any requires forced user");
disconnect_client(client, true, "bouncer config error");
return false;
}
client->auth_user = db->forced_user;
} else {
/* the user clients wants to log in as */
user = find_user(username);
if (!user) {
disconnect_client(client, true, "No such user");
return false;
}
client->auth_user = user;
}
/* pool user may be forced */
if (db->forced_user)
user = db->forced_user;
client->pool = get_pool(db, user);
if (!client->pool) {
disconnect_client(client, true, "no memory for pool");
return false;
}
return true;
}
static bool decide_startup_pool(PgSocket *client, PktHdr *pkt)
{
const char *username = NULL, *dbname = NULL;
const char *key, *val;
while (1) {
key = mbuf_get_string(&pkt->data);
if (!key || *key == 0)
break;
val = mbuf_get_string(&pkt->data);
if (!val)
break;
if (strcmp(key, "database") == 0)
dbname = val;
else if (strcmp(key, "user") == 0)
username = val;
else if (varcache_set(&client->vars, key, val))
slog_debug(client, "got var: %s=%s", key, val);
else if (strlist_contains(cf_ignore_startup_params, key)) {
slog_debug(client, "ignoring startup parameter: %s=%s", key, val);
} else {
slog_warning(client, "unsupported startup parameter: %s=%s", key, val);
disconnect_client(client, true, "Unknown startup parameter");
return false;
}
}
if (!username) {
disconnect_client(client, true, "No username supplied");
return false;
}
if (!dbname) {
disconnect_client(client, true, "No database supplied");
return false;
}
/* check if limit allows, dont limit admin db
nb: new incoming conn will be attached to PgSocket, thus
get_active_client_count() counts it */
if (get_active_client_count() > cf_max_client_conn) {
if (strcmp(dbname, "pgbouncer") != 0) {
disconnect_client(client, true, "no more connections allowed");
return false;
}
}
/* find pool and log about it */
if (set_pool(client, dbname, username)) {
if (cf_log_connections)
slog_info(client, "login successful: db=%s user=%s", dbname, username);
return true;
} else {
if (cf_log_connections)
slog_info(client, "login failed: db=%s user=%s", dbname, username);
return false;
}
}
/* mask to get offset into valid_crypt_salt[] */
#define SALT_MASK 0x3F
static const char valid_crypt_salt[] =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
static bool send_client_authreq(PgSocket *client)
{
uint8_t saltlen = 0;
int res;
int auth = cf_auth_type;
uint8_t randbuf[2];
if (auth == AUTH_CRYPT) {
saltlen = 2;
get_random_bytes(randbuf, saltlen);
client->tmp_login_salt[0] = valid_crypt_salt[randbuf[0] & SALT_MASK];
client->tmp_login_salt[1] = valid_crypt_salt[randbuf[1] & SALT_MASK];
client->tmp_login_salt[2] = 0;
} else if (cf_auth_type == AUTH_MD5) {
saltlen = 4;
get_random_bytes((void*)client->tmp_login_salt, saltlen);
} else if (auth == AUTH_ANY)
auth = AUTH_TRUST;
SEND_generic(res, client, 'R', "ib", auth, client->tmp_login_salt, saltlen);
return res;
}
/* decide on packets of client in login phase */
static bool handle_client_startup(PgSocket *client, PktHdr *pkt)
{
const char *passwd;
SBuf *sbuf = &client->sbuf;
/* don't tolerate partial packets */
if (incomplete_pkt(pkt)) {
disconnect_client(client, true, "client sent partial pkt in startup phase");
return false;
}
if (client->wait_for_welcome) {
if (finish_client_login(client)) {
/* the packet was already parsed */
sbuf_prepare_skip(sbuf, pkt->len);
return true;
} else
return false;
}
switch (pkt->type) {
case PKT_SSLREQ:
slog_noise(client, "C: req SSL");
slog_noise(client, "P: nak");
/* reject SSL attempt */
if (!sbuf_answer(&client->sbuf, "N", 1)) {
disconnect_client(client, false, "failed to nak SSL");
return false;
}
break;
case PKT_STARTUP:
if (client->pool) {
disconnect_client(client, true, "client re-sent startup pkt");
return false;
}
if (!decide_startup_pool(client, pkt))
return false;
if (client->pool->db->admin) {
if (!admin_pre_login(client))
return false;
}
if (cf_auth_type <= AUTH_TRUST || client->own_user) {
if (!finish_client_login(client))
return false;
} else {
if (!send_client_authreq(client)) {
disconnect_client(client, false, "failed to send auth req");
return false;
}
}
break;
case 'p': /* PasswordMessage */
/* haven't requested it */
if (cf_auth_type <= AUTH_TRUST) {
disconnect_client(client, true, "unrequested passwd pkt");
return false;
}
passwd = mbuf_get_string(&pkt->data);
if (passwd && check_client_passwd(client, passwd)) {
if (!finish_client_login(client))
return false;
} else {
disconnect_client(client, true, "Login failed");
return false;
}
break;
case PKT_CANCEL:
if (mbuf_avail(&pkt->data) == BACKENDKEY_LEN) {
const uint8_t *key = mbuf_get_bytes(&pkt->data, BACKENDKEY_LEN);
memcpy(client->cancel_key, key, BACKENDKEY_LEN);
accept_cancel_request(client);
} else
disconnect_client(client, false, "bad cancel request");
return false;
default:
disconnect_client(client, false, "bad packet");
return false;
}
sbuf_prepare_skip(sbuf, pkt->len);
client->request_time = get_cached_time();
return true;
}
/* decide on packets of logged-in client */
static bool handle_client_work(PgSocket *client, PktHdr *pkt)
{
SBuf *sbuf = &client->sbuf;
switch (pkt->type) {
/* request immidiate response from server */
case 'H': /* Flush */
case 'S': /* Sync */
/* one-packet queries */
case 'Q': /* Query */
case 'F': /* FunctionCall */
/* copy end markers */
case 'c': /* CopyDone(F/B) */
case 'f': /* CopyFail(F/B) */
/*
* extended protocol allows server (and thus pooler)
* to buffer packets until sync or flush is sent by client
*/
case 'P': /* Parse */
case 'E': /* Execute */
case 'C': /* Close */
case 'B': /* Bind */
case 'D': /* Describe */
case 'd': /* CopyData(F/B) */
/* update stats */
if (!client->query_start) {
client->pool->stats.request_count++;
client->query_start = get_cached_time();
}
if (client->pool->db->admin)
return admin_handle_client(client, pkt);
/* aquire server */
if (!find_server(client))
return false;
client->pool->stats.client_bytes += pkt->len;
/* tag the server as dirty */
client->link->ready = 0;
/* forward the packet */
sbuf_prepare_send(sbuf, &client->link->sbuf, pkt->len);
break;
/* client wants to go away */
default:
slog_error(client, "unknown pkt from client: %d/0x%x", pkt->type, pkt->type);
disconnect_client(client, true, "unknown pkt");
return false;
case 'X': /* Terminate */
disconnect_client(client, false, "client close request");
return false;
}
return true;
}
/* callback from SBuf */
bool client_proto(SBuf *sbuf, SBufEvent evtype, MBuf *data)
{
bool res = false;
PgSocket *client = container_of(sbuf, PgSocket, sbuf);
PktHdr pkt;
Assert(!is_server_socket(client));
Assert(client->sbuf.sock);
Assert(client->state != CL_FREE);
/* may happen if close failed */
if (client->state == CL_JUSTFREE)
return false;
switch (evtype) {
case SBUF_EV_CONNECT_OK:
case SBUF_EV_CONNECT_FAILED:
/* ^ those should not happen */
case SBUF_EV_RECV_FAILED:
disconnect_client(client, false, "client unexpected eof");
break;
case SBUF_EV_SEND_FAILED:
disconnect_server(client->link, false, "Server connection closed");
break;
case SBUF_EV_READ:
if (mbuf_avail(data) < NEW_HEADER_LEN && client->state != CL_LOGIN) {
slog_noise(client, "C: got partial header, trying to wait a bit");
return false;
}
if (!get_header(data, &pkt)) {
disconnect_client(client, true, "bad packet header");
return false;
}
slog_noise(client, "pkt='%c' len=%d", pkt_desc(&pkt), pkt.len);
client->request_time = get_cached_time();
switch (client->state) {
case CL_LOGIN:
res = handle_client_startup(client, &pkt);
break;
case CL_ACTIVE:
if (client->wait_for_welcome)
res = handle_client_startup(client, &pkt);
else
res = handle_client_work(client, &pkt);
break;
case CL_WAITING:
fatal("why waiting client in client_proto()");
default:
fatal("bad client state: %d", client->state);
}
break;
case SBUF_EV_FLUSH:
/* client is not interested in it */
break;
case SBUF_EV_PKT_CALLBACK:
/* unused ATM */
break;
}
return res;
}