-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdpm.c
2841 lines (2303 loc) · 76 KB
/
dpm.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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2008 Dormando (dormando@rydia.net). All rights reserved.
*
* Use and distribution licensed under the BSD license. See
* the LICENSE file for full text.
*/
/* Dormando's Proxy for MySQL, with lua scripting! */
/* Internal headers */
#include "proxy.h"
#include "sha1.h"
#include "luaobj.h"
/* Internal defines */
#undef DBUG
#define BUF_SIZE 2048
#define VERSION "5"
const char *my_state_name[]={
"Server connect",
"Client connect",
"Server sent handshake",
"Client wait handshake",
"Client waiting",
"Server waiting",
"Client sent command",
"Server sending fields",
"Server sending rows",
"Server waiting auth",
"Server sending OK",
"Server waiting command",
"Server sending resultset",
"Client waiting auth",
"Server sending handshake",
"Server got error",
"Closing",
"Server sending stats",
"Server got command",
"Server sending eof",
"Server sent resultset",
"Server sent fields",
};
/* Global structures/values. These will need to be thread local. */
struct lua_State *L;
int urandom_sock = 0;
int verbose = 0;
/* Track connections which have had their write buffers appended to.
* This is walked during run_protocol() */
conn *dpm_conn_flush_list = NULL;
/* Declarations */
static void sig_hup(const int sig);
int set_sock_nonblock(int fd);
static int handle_accept(int fd);
static int handle_read(conn *c);
static int handle_write(conn *c);
static conn *init_conn(int newfd);
static void handle_event(int fd, short event, void *arg);
static int add_conn_event(conn *c, const int new_flags);
//static int del_conn_event(conn *c, const int new_flags);
static int update_conn_event(conn *c, const int new_flags);
static int run_protocol(conn *c, int read, int written);
static int my_next_packet_start(conn *c);
static int grow_write_buffer(conn *c, int newsize);
static int sent_packet(conn *c, void **p, int ptype, int field_count);
static int received_packet(conn *c, void **p, int *ptype, int field_count);
/* Packet managers */
static void *my_consume_handshake_packet(conn *c);
static void my_free_handshake_packet(void *p);
static int my_wire_handshake_packet(conn *c, void *pkt);
static void *my_consume_auth_packet(conn *c);
static void my_free_auth_packet(void *p);
static int my_wire_auth_packet(conn *c, void *pkt);
static void *my_consume_ok_packet(conn *c);
static void my_free_ok_packet(void *p);
static int my_wire_ok_packet(conn *c, void *pkt);
static void *my_consume_err_packet(conn *c);
static void my_free_err_packet(void *pkt);
static int my_wire_err_packet(conn *c, void *pkt);
static void *my_consume_cmd_packet(conn *c);
static void my_free_cmd_packet(void *pkt);
static int my_wire_cmd_packet(conn *c, void *pkt);
static void *my_consume_rset_packet(conn *c);
static void my_free_rset_packet(void *pkt);
static int my_wire_rset_packet(conn *c, void *pkt);
static void *my_consume_row_packet(conn *c);
static void my_free_row_packet(void *pkt);
static int my_wire_row_packet(conn *c, void *pkt);
static void *my_consume_field_packet(conn *c);
static void my_free_field_packet(void *pkt);
static int my_wire_field_packet(conn *c, void *pkt);
static void *my_consume_eof_packet(conn *c);
static void my_free_eof_packet(void *pkt);
static int my_wire_eof_packet(conn *c, void *pkt);
static uint8_t my_char_val(uint8_t X);
static void my_hex2octet(uint8_t *dst, const char *src, unsigned int len);
static void my_crypt(char *dst, const unsigned char *s1, const unsigned char *s2, uint len);
static void my_scramble(char *dst, const char *random, const char *pass);
static int my_check_scramble(const char *remote_scram, const char *random, const char *stored_hash);
/* Lua related forward declarations. */
static int new_listener(lua_State *L);
static int new_connect(lua_State *L);
static int close_conn(lua_State *L);
static int check_pass(lua_State *L);
static int crypt_pass(lua_State *L);
static int wire_packet(lua_State *L);
static int run_lua_callback(conn *c, int nargs);
static int proxy_connect(lua_State *L);
static int proxy_disconnect(lua_State *L);
/* Wrappers for string handling. Replaceable with GString or more buffer
* functions later.
*/
cbuffer_t *cbuffer_new(size_t len, const char *src)
{
cbuffer_t *buf = (cbuffer_t *)malloc(sizeof(cbuffer_t) + len);
if (buf == NULL) {
perror("malloc");
return NULL;
}
memcpy(buf->data, src, len);
buf->data[len] = '\0';
return buf;
}
void cbuffer_free(cbuffer_t *buf)
{
free(buf);
}
/* Start of access functions. This thing should be more or less... write once.
* if we're to rewrite, free/create a new one.
*/
inline size_t cbuffer_size(cbuffer_t *buf)
{
return buf->len;
}
inline const char *cbuffer_data(cbuffer_t *buf)
{
return buf->data;
}
/* Stack a connection for flushing later. */
static void _dpm_add_to_flush_list(conn *c)
{
if (dpm_conn_flush_list)
c->nextconn = (struct conn *)dpm_conn_flush_list;
dpm_conn_flush_list = c;
}
/* Stub function. In the future, should set a flag to reload or dump stuff */
static void sig_hup(const int sig)
{
fprintf(stdout, "Got reload request.\n");
}
int set_sock_nonblock(int fd)
{
int flags = 1;
if ( (flags = fcntl(fd, F_GETFL, 0)) < 0 ||
fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("Could not set O_NONBLOCK");
close(fd);
return -1;
}
return 0;
}
static int add_conn_event(conn *c, const int new_flags)
{
int ret;
ret = update_conn_event(c, c->ev_flags | new_flags);
return ret;
}
/* FIXME: Logic is wrong */
/*static int del_conn_event(conn *c, const int new_flags)
{
int ret;
ret = update_conn_event(c, c->ev_flags & ~new_flags);
return ret;
}*/
static int update_conn_event(conn *c, const int new_flags)
{
if (c->ev_flags == new_flags) return 1;
if (event_del(&c->ev) == -1) return 0;
c->ev_flags = new_flags;
event_set(&c->ev, c->fd, new_flags, handle_event, (void *)c);
if (event_add(&c->ev, 0) == -1) return 0;
return 1;
}
static int handle_accept(int fd)
{
struct sockaddr_in addr;
socklen_t addrlen = 0;
int newfd;
if ( (newfd = accept(fd, (struct sockaddr *)&addr, &addrlen)) == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
if (verbose)
fprintf(stderr, "Blocking error on accept. ignore?\n");
} else if (errno == EMFILE) {
fprintf(stderr, "Holy crap out of FDs!\n");
} else {
perror("Died on accept");
}
}
return newfd;
}
void handle_close(conn *c)
{
conn *remote;
assert(c != 0);
c->dpmstate = MY_CLOSING;
run_lua_callback(c, 0);
event_del(&c->ev);
/* Release a connected remote connection.
* FIXME: Is this detectable from within lua?
*/
if (c->remote) {
remote = (conn *)c->remote;
remote->remote = NULL;
c->remote = NULL;
}
close(c->fd);
if (verbose)
fprintf(stdout, "Closed connection for %llu listener: %s\n", (unsigned long long) c->id, c->listener ? "yes" : "no");
if (c->rbuf) free(c->rbuf);
if (c->wbuf) free(c->wbuf);
c->alive = 0;
}
/* Generic "Grow my write buffer" function. */
static int grow_write_buffer(conn *c, int newsize)
{
unsigned char *new_wbuf;
if (c->wbufsize < newsize) {
/* Figure the next power of two using bit magic */
int nextsize = newsize - 1;
int i = 1;
int intbits = sizeof(nextsize) * 4;
for (; i != intbits; i *= 2) {
nextsize |= nextsize >> i;
}
nextsize++;
if (verbose)
fprintf(stdout, "Reallocating write buffer from %d to %d\n", c->wbufsize, nextsize);
new_wbuf = realloc(c->wbuf, nextsize);
if (new_wbuf == NULL) {
perror("Realloc output buffer");
return -1;
}
c->wbuf = new_wbuf;
c->wbufsize = nextsize;
}
return 0;
}
/* handle buffering writes... we're looking for EAGAIN until we stop
* transmitting.
* We're assuming the write data was pre-populated.
* NOTE: Need to support changes in written between calls
*/
static int handle_write(conn *c)
{
int wbytes;
int written = 0;
/* Short circuit for outbound connections. */
if (c->towrite < 1) {
return written;
}
for(;;) {
if (c->written == c->towrite) {
c->mystate = my_reading;
c->written = 0;
c->towrite = 0;
update_conn_event(c, EV_READ | EV_PERSIST);
break;
}
wbytes = send(c->fd, c->wbuf + c->written, c->towrite - c->written, 0);
if (wbytes == 0) {
return -1;
} else if (wbytes == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
if (add_conn_event(c, EV_WRITE) == 0) {
fprintf(stderr, "Couldn't add write watch to %d\n", c->fd);
return -1;
}
/* Transient error. Come back later. */
return 0;
} else {
perror("Unhandled write error");
return -1;
}
}
c->written += wbytes;
written += wbytes;
}
return written;
}
/* Handle buffered read events. Read into the buffer until we would block.
* returns the total number of bytes read in the session. */
static int handle_read(conn *c)
{
int rbytes;
int newdata = 0;
unsigned char *new_rbuf;
for(;;) {
/* We're in trouble if read is larger than rbufsize, right? ;)
* Anyhoo, if so, we want to realloc up the buffer.
* TODO: Share buffers so we don't realloc so often... */
if (c->read >= c->rbufsize) {
/* I'd prefer 1.5... */
if (verbose)
fprintf(stdout, "Reallocing input buffer from %d to %d\n",
c->rbufsize, c->rbufsize * 2);
new_rbuf = realloc(c->rbuf, c->rbufsize * 2);
if (new_rbuf == NULL) {
perror("Realloc input buffer");
return -1;
}
/* The start of the new buffer might've changed: realloc(2) */
c->rbuf = new_rbuf;
c->rbufsize *= 2;
}
/* while bytes from read, pack into buffer. return when would block */
rbytes = read(c->fd, c->rbuf + c->read, c->rbufsize - c->read);
/* If signaled for reading and got zero bytes, close it up
* FIXME : Should we flush the command? */
if (rbytes == 0 && newdata) {
break;
} else if (rbytes == 0) {
return -1;
} else if (rbytes == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return 0;
} else {
return -1;
}
}
/* Successfuly read. Mark our progress */
c->read += rbytes;
newdata += rbytes;
}
/* Allows caller to arbitrarily measure progress, since we use a binary
* protocol. "Did we get enough bytes to satisfy len? No? Yawn. Nap."
*/
return newdata;
}
static conn *init_conn(int newfd)
{
conn *newc;
static int my_connection_counter = 1; /* NOTE: Not positive if this should be global or not */
/* client typedef init should be its own function */
newc = (conn *)malloc( sizeof(conn) ); /* error handling */
memset(newc, 0, sizeof(conn));
newc->fd = newfd;
newc->id = my_connection_counter++;
newc->ev_flags = EV_READ | EV_PERSIST;
newc->mystate = my_reading;
newc->dpmstate = my_waiting;
/* Misc inits, for clarity. */
newc->read = 0;
newc->readto = 0;
newc->written = 0;
newc->towrite = 0;
newc->my_type = MY_CLIENT;
newc->packetsize = 0;
newc->field_count = 0;
newc->last_cmd = 0;
newc->packet_seq = 0;
newc->listener = 0;
newc->nextconn = NULL;
/* Set up the buffers. */
newc->rbufsize = BUF_SIZE;
newc->wbufsize = BUF_SIZE;
newc->rbuf = (unsigned char *)malloc( (size_t)newc->rbufsize );
newc->wbuf = (unsigned char *)malloc( (size_t)newc->wbufsize );
/* Cleaner way to do this? I guess not with C */
if (newc->rbuf == 0 || newc->wbuf == 0) {
if (newc->rbuf != 0) free(newc->rbuf);
if (newc->wbuf != 0) free(newc->wbuf);
free(newc);
perror("Could not malloc()");
return NULL;
}
newc->remote = NULL;
/* Callback structures. Rest are zero from above memset. */
newc->package_callback = NULL;
event_set(&newc->ev, newfd, newc->ev_flags, handle_event, (void *)newc);
event_add(&newc->ev, NULL); /* error handling */
if (verbose)
fprintf(stdout, "Made new conn structure for %d\n", newfd);
return newc;
}
static void handle_event(int fd, short event, void *arg)
{
conn *c = arg;
conn *newc = NULL;
struct linger l = {0, 0};
int newfd, rbytes, wbytes;
int flags = 1;
int err = 0;
/* if we're the server socket, it's a new conn */
if (c->listener) {
newfd = handle_accept(fd); /* error handling */
if (verbose)
fprintf(stdout, "Got new client sock %d\n", newfd);
set_sock_nonblock(newfd); /* error handling on this and below */
setsockopt(newfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags));
setsockopt(newfd, SOL_SOCKET, SO_LINGER, (void *)&l, sizeof(l));
newc = init_conn(newfd);
if (newc == NULL)
return;
newc->dpmstate = MYC_WAIT_HANDSHAKE;
newc->my_type = MY_CLIENT;
newc->alive++;
/* Pass the object up into lua for later inspection. */
new_obj(L, newc, "dpm.conn");
/* And the id of our listener object. */
lua_pushinteger(L, c->id);
c->dpmstate = MYC_CONNECT;
run_lua_callback(c, 2);
/* The callback might've written packets to the wire. */
if (newc->towrite) {
if (handle_write(newc) == -1)
return;
}
return;
}
if (event & EV_READ) {
/* Client socket. */
rbytes = handle_read(c);
/* FIXME : Should we do the error handling at this level? Or lower? */
if (rbytes < 0) {
handle_close(c);
return;
}
}
if (event & EV_WRITE) {
if (c->mystate != my_connect) {
wbytes = handle_write(c);
if (wbytes < 0) {
handle_close(c);
return;
}
}
}
err = run_protocol(c, rbytes, wbytes);
if (err == -1) {
handle_close(c);
}
}
/* MySQL Protocol support routines */
/* Read a length encoded binary field into a uint64_t */
uint64_t my_read_binary_field(unsigned char *buf, int *base)
{
uint64_t ret = 0;
if (buf[*base] < 251) {
(*base)++;
return (uint64_t) buf[*base - 1];
}
(*base)++;
switch (buf[*base - 1]) {
case 251:
return MYSQL_NULL;
case 252:
ret = uint2korr(&buf[*base]);
(*base) += 2;
break;
case 253:
/* NOTE: Docs say this is 32-bit. libmysqlnd says 24-bit? */
ret = uint4korr(&buf[*base]);
(*base) += 4;
break;
case 254:
ret = uint8korr(&buf[*base]);
(*base) += 8;
}
return ret;
}
/* Same as above, but writes the binary field into buffer. */
void my_write_binary_field(unsigned char *buf, int *base, uint64_t length)
{
if (length < (uint64_t) 251) {
*buf = length;
(*base)++;
return;
}
if (length < (uint64_t) 65536) {
*buf++ = 252;
int2store(buf, (uint16_t) length);
(*base) += 2;
return;
}
if (length < (uint64_t) 16777216) {
*buf++ = 253;
int3store(buf, (uint32_t) length);
(*base) += 3;
return;
}
if (length == MYSQL_NULL) {
*buf = 251;
(*base)++;
return;
}
*buf++ = 254;
int8store(buf, length);
(*base) += 8;
}
/* Returns the binary size of a field, for use in pre-allocating wire buffers
*/
int my_size_binary_field(uint64_t length)
{
if (length < (uint64_t) 251)
return 1;
if (length < (uint64_t) 65536)
return 3;
if (length < (uint64_t) 16777216)
return 5;
if (length == MYSQL_NULL)
return 1;
return 9;
}
static uint8_t my_char_val(uint8_t X)
{
return (unsigned int) (X >= '0' && X <= '9' ? X-'0' :
X >= 'A' && X <= 'Z' ? X-'A'+10 : X-'a'+10);
}
static void my_hex2octet(uint8_t *dst, const char *src, unsigned int len)
{
const char *str_end= src + len;
while (src < str_end) {
char tmp = my_char_val(*src++);
*dst++ = (tmp << 4) | my_char_val(*src++);
}
}
static void my_crypt(char *dst, const unsigned char *s1, const unsigned char *s2, uint len)
{
const uint8_t *s1_end= s1 + len;
while (s1 < s1_end)
*dst++ = *s1++ ^ *s2++;
}
/* End. */
/* Client scramble
* random is 20 byte random scramble from the server.
* pass is plaintext password supplied from client
* dst is a 20 byte buffer to receive the jumbled mess. */
static void my_scramble(char *dst, const char *random, const char *pass)
{
SHA1_CTX context;
uint8_t hash1[SHA1_DIGEST_LENGTH];
uint8_t hash2[SHA1_DIGEST_LENGTH];
/* Make sure the null terminator's in the right spot. */
dst[SHA1_DIGEST_LENGTH] = '\0';
/* First hash the password. */
SHA1Init(&context);
SHA1Update(&context, (const uint8_t *) pass, strlen(pass));
SHA1Final(hash1, &context);
/* Second, hash the hash. */
SHA1Init(&context);
SHA1Update(&context, hash1, SHA1_DIGEST_LENGTH);
SHA1Final(hash2, &context);
/* Now we have the equivalent of SELECT PASSWORD('whatever') */
/* Now SHA1 the random message against hash2, then xor it against hash1 */
SHA1Init(&context);
SHA1Update(&context, (const uint8_t *) random, SHA1_DIGEST_LENGTH);
SHA1Update(&context, hash2, SHA1_DIGEST_LENGTH);
SHA1Final((uint8_t *) dst, &context);
my_crypt((char *)dst, (const unsigned char *) dst, hash1, SHA1_DIGEST_LENGTH);
/* The sha1 context has temporary data that needs to disappear. */
memset(&context, 0, sizeof(SHA1_CTX));
}
/* Server side check. */
static int my_check_scramble(const char *remote_scram, const char *random, const char *stored_hash)
{
uint8_t pass_hash[SHA1_DIGEST_LENGTH];
uint8_t rand_hash[SHA1_DIGEST_LENGTH];
uint8_t pass_orig[SHA1_DIGEST_LENGTH];
uint8_t pass_check[SHA1_DIGEST_LENGTH];
SHA1_CTX context;
/* Parse string into bytes... */
my_hex2octet(pass_hash, stored_hash, strlen(stored_hash));
/* Muck up our view of the password against our original random num */
SHA1Init(&context);
SHA1Update(&context, (const uint8_t *) random, SHA1_DIGEST_LENGTH);
SHA1Update(&context, pass_hash, SHA1_DIGEST_LENGTH);
SHA1Final(rand_hash, &context);
/* Pull out the client sha1 */
my_crypt((char *) pass_orig, (const unsigned char *) rand_hash, (const unsigned char *) remote_scram, SHA1_DIGEST_LENGTH);
/* Update it to be more like our own */
SHA1Init(&context);
SHA1Update(&context, pass_orig, SHA1_DIGEST_LENGTH);
SHA1Final(pass_check, &context);
memset(&context, 0, sizeof(SHA1_CTX));
/* Compare */
return memcmp(pass_hash, pass_check, SHA1_DIGEST_LENGTH);
}
/* If we're ready to send the next packet along, prep the header and
* return the starting position. */
static int my_next_packet_start(conn *c)
{
int seq = 0;
/* A couple sanity checks... First is that we must have enough bytes
* readable to try consuming a header. */
if (c->readto + 3 > c->read)
return -1;
c->packetsize = uint3korr(&c->rbuf[c->readto]);
seq = uint1korr(&c->rbuf[c->readto + 3]);
c->packetsize += 4;
/* Don't handle large packets right now.
* TODO: This actually shouldn't be too hard. Keep spooling with this
* function until we can scan to the end of the function within the buffer
* structure. Ugly, but the protocol's ugly anyway.
*/
if (c->packetsize == 0 && seq == 255) {
fprintf(stderr, "***WARNING*** DPM does not support packet sizes larger than 16M currently. If you report this warning it will probably be fixed.");
handle_close(c);
return -1;
}
/* If we've read a packet header, see if we have the whole packet. */
if (c->read - c->readto >= c->packetsize) {
/* Test the packet header. Is it out of sequence? */
/* FIXME: The MY_CLIENT hack is because we're not fully tracking client
* state. So if the consumer is a client and the header's zero for no
* reason, it's probably a new command packet and will get fixed
* later.
*/
if (c->packet_seq != seq && !(c->my_type == MY_CLIENT && seq == 0)) {
fprintf(stderr, "***WARNING*** Packets appear to be out of order: type [%d] conn [%d], header [%d]\n", c->my_type, c->packet_seq, seq);
}
return c->readto;
}
return -1;
}
/* TODO: In another life this should be some crazy struct buffer. */
static void my_free_handshake_packet(void *p)
{
/* No allocated memory, easy. */
free(p);
}
/* Takes handshake packet *p and writes as a packet into c's write buffer. */
static int my_wire_handshake_packet(conn *c, void *pkt)
{
my_handshake_packet *p = (my_handshake_packet *)pkt;
int psize = 45;
size_t my_size = strlen(p->server_version) + 1;
int base = c->towrite;
/* We must discover the length of the packet first, so we can size the
* buffer. HS packets are 45 bytes + strlen(server_version) + 1
*/
psize += my_size + 4;
if (grow_write_buffer(c, c->towrite + psize) == -1) {
return -1;
}
c->towrite += psize;
int3store(&c->wbuf[base], psize - 4);
base += 3;
int1store(&c->wbuf[base], c->packet_seq);
base++;
c->wbuf[base] = p->protocol_version;
base++;
memcpy(&c->wbuf[base], p->server_version, my_size);
base += my_size;
int4store(&c->wbuf[base], p->thread_id);
base += 4;
memcpy(&c->wbuf[base], p->scramble_buff, 8);
base += 8;
c->wbuf[base] = 0;
base++;
int2store(&c->wbuf[base], p->server_capabilities);
base += 2;
c->wbuf[base] = p->server_language;
base++;
int2store(&c->wbuf[base], p->server_status);
base += 2;
memset(&c->wbuf[base], 0, 13);
base += 13;
memcpy(&c->wbuf[base], p->scramble_buff + 8, 13);
return psize;
}
/* Creates an "empty" handshake packet */
void *my_new_handshake_packet()
{
my_handshake_packet *p;
int i; char next_rand;
p = (my_handshake_packet *)malloc( sizeof(my_handshake_packet) );
if (p == NULL) {
perror("Could not malloc()");
return NULL;
}
memset(p, 0, sizeof(my_handshake_packet));
p->h.ptype = dpm_handshake;
p->h.free_me = my_free_handshake_packet;
p->h.to_buf = my_wire_handshake_packet;
p->protocol_version = 10; /* FIXME: Should be a define? */
strcpy(p->server_version, "5.0.37"); /* :P */
p->thread_id = 1; /* Who cares. */
p->server_capabilities = CLIENT_LONG_PASSWORD | CLIENT_LONG_FLAG | CLIENT_CONNECT_WITH_DB | CLIENT_PROTOCOL_41 | CLIENT_TRANSACTIONS | CLIENT_SECURE_CONNECTION;
p->server_language = 8;
p->server_status = SERVER_STATUS_AUTOCOMMIT;
for (i = 0; i != SHA1_DIGEST_LENGTH; i++) {
read(urandom_sock, &next_rand, 1);
p->scramble_buff[i] = next_rand * 94 + 33;
}
return p;
}
/* FIXME: If we have the second scramblebuff, it needs to be assembled
* into a single line for processing.
*/
static void *my_consume_handshake_packet(conn *c)
{
my_handshake_packet *p;
int base = c->readto + 4;
size_t my_size = 0;
/* Clear out the struct. */
p = (my_handshake_packet *)malloc( sizeof(my_handshake_packet) );
if (p == NULL) {
perror("Could not malloc()");
return NULL;
}
memset(p, 0, sizeof(my_handshake_packet));
p->h.ptype = dpm_handshake;
p->h.free_me = my_free_handshake_packet;
p->h.to_buf = my_wire_handshake_packet;
/* We only support protocol 10 right now... */
p->protocol_version = c->rbuf[base];
if (p->protocol_version != 10) {
fprintf(stderr, "We only support protocol version 10! Closing.\n");
return NULL;
}
base++;
/* Server version string. Crappy malloc. */
my_size = strlen((const char *)&c->rbuf[base]);
/* +1 to account for the \0 */
my_size++;
if (my_size > SERVER_VERSION_LENGTH) {
fprintf(stderr, "Server version string is too long! Closing.\n");
return NULL;
}
memcpy(p->server_version, &c->rbuf[base], my_size);
base += my_size;
/* 4 byte thread id */
p->thread_id = uint4korr(&c->rbuf[base]);
base += 4;
/* First 8 bytes of scramble_buff. Sandwich with 12 more + \0 later */
memcpy(&p->scramble_buff, &c->rbuf[base], 8);
base += 8;
/* filler1 should be 0 */
base++;
/* Set of flags for server caps. */
/* TODO: Need to explicitly disable compression, ssl, other features we
* don't support. */
p->server_capabilities = uint2korr(&c->rbuf[base]);
base += 2;
/* Language setting. Pass-through and/or ignore. */
p->server_language = c->rbuf[base];
base++;
/* Server status flags. AUTOCOMMIT flags and such? */
p->server_status = uint2korr(&c->rbuf[base]);
base += 2;
/* More zeroes. */
base += 13;
/* Rest of random number "string" */
memcpy(&p->scramble_buff[8], &c->rbuf[base], 13);
base += 13;
new_obj(L, p, "dpm.handshake");
return p;
}
static void my_free_auth_packet(void *pkt)
{
my_auth_packet *p = (my_auth_packet *)pkt;
if (p->databasename)
free(p->databasename);
free(p);
}
void *my_new_auth_packet()
{
my_auth_packet *p;
/* Clear out the struct. */
p = (my_auth_packet *)malloc( sizeof(my_auth_packet) );
if (p == NULL) {
perror("Could not malloc()");
return NULL;
}
memset(p, 0, sizeof(my_auth_packet));
p->h.ptype = dpm_auth;
p->h.free_me = my_free_auth_packet;
p->h.to_buf = my_wire_auth_packet;
p->client_flags = CLIENT_LONG_PASSWORD | CLIENT_LONG_FLAG | CLIENT_CONNECT_WITH_DB | CLIENT_PROTOCOL_41 | CLIENT_TRANSACTIONS | CLIENT_SECURE_CONNECTION;
p->max_packet_size = 16777216; /* FIXME: Double check this. */
p->charset_number = 8;
strcpy(p->user, "root"); /* FIXME: Needs to be editable. */
p->databasename = NULL; /* Don't need a default DB. */
p->scramble_buff[20] = 1;
return p;
}
static int my_wire_auth_packet(conn *c, void *pkt)
{
my_auth_packet *p = (my_auth_packet *)pkt;
int psize = 32;
size_t user_size = strlen(p->user) + 1;
size_t dbname_size = 0;
int base = c->towrite;
/* password, or no password. */
psize += p->scramble_buff[20] == '\0' ? 21 : 1;
/* databasename, or no databasename. */
if (p->databasename)
dbname_size = strlen(p->databasename) + 1;
/* Add in the username length + header. */
psize += user_size + dbname_size + 4;
if (grow_write_buffer(c, c->towrite + psize) == -1) {
return -1;
}
c->towrite += psize;
int3store(&c->wbuf[base], psize - 4);
base += 3;
int1store(&c->wbuf[base], c->packet_seq);
base++;
int4store(&c->wbuf[base], p->client_flags);
base += 4;
int4store(&c->wbuf[base], p->max_packet_size);
base += 4;
c->wbuf[base] = p->charset_number;
base++;
memset(&c->wbuf[base], 0, 23);
base += 23;
memcpy(&c->wbuf[base], p->user, user_size);
base += user_size;