forked from octo/credis
-
Notifications
You must be signed in to change notification settings - Fork 1
/
credis.c
1951 lines (1577 loc) · 49.6 KB
/
credis.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
/* credis.c -- a C client library for Redis
*
* Copyright (c) 2009-2010, Jonas Romfelt <jonas at romfelt dot se>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Credis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef WIN32
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#else
#ifdef __FreeBSD__
#include <sys/types.h>
#endif
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "credis.h"
#ifdef WIN32
void close(int fd) {
closesocket(fd);
}
#endif
#define CR_ERROR '-'
#define CR_INLINE '+'
#define CR_BULK '$'
#define CR_MULTIBULK '*'
#define CR_INT ':'
#define CR_ANY '?'
#define CR_NONE ' '
#define CR_BUFFER_SIZE 4096
#define CR_BUFFER_WATERMARK ((CR_BUFFER_SIZE)/10+1)
#define CR_MULTIBULK_SIZE 256
#define _STRINGIF(arg) #arg
#define STRINGIFY(arg) _STRINGIF(arg)
#define CR_VERSION_STRING_SIZE_STR STRINGIFY(CREDIS_VERSION_STRING_SIZE)
#define CR_MULTIPLEXING_API_SIZE_STR STRINGIFY(CREDIS_MULTIPLEXING_API_SIZE)
#define CR_USED_MEMORY_HUMAN_SIZE_STR STRINGIFY(CREDIS_USED_MEMORY_HUMAN_SIZE)
#ifdef PRINTDEBUG
/* add -DPRINTDEBUG to CPPFLAGS in Makefile for debug outputs */
#define DEBUG(...) \
do { \
printf("%s() @ %d: ", __FUNCTION__, __LINE__); \
printf(__VA_ARGS__); \
printf("\n"); \
} while (0)
#else
#define DEBUG(...)
#endif
/* format warnings are GNU C specific */
#if !__GNUC__
#define __attribute__(x)
#endif
typedef struct _cr_buffer {
char *data;
int idx;
int len;
int size;
} cr_buffer;
typedef struct _cr_multibulk {
char **bulks;
int *idxs;
int size;
int len;
} cr_multibulk;
typedef struct _cr_reply {
char type;
int integer;
char *line;
char *bulk;
cr_multibulk multibulk;
} cr_reply;
typedef struct _cr_message {
char *pattern;
char *channel;
char *message;
struct _cr_message *next;
} cr_message;
typedef struct _cr_redis {
struct {
int major;
int minor;
int patch;
} version;
struct {
cr_message *head;
cr_message *tail;
cr_message *msg;
} pubsub;
int fd;
char *ip;
int port;
int timeout;
cr_buffer buf;
cr_reply reply;
int error;
} cr_redis;
static void cr_freeallmessages(REDIS rhnd);
/* Returns pointer to the '\r' of the first occurence of "\r\n", or NULL
* if not found */
static char * cr_findnl(char *buf, int len) {
while (--len >= 0) {
if (*(buf++) == '\r')
if (*buf == '\n')
return --buf;
}
return NULL;
}
/* Allocate at least `size' bytes more buffer memory, keeping content of
* previously allocated memory untouched.
* Returns:
* 0 on success
* -1 on error, i.e. more memory not available */
static int cr_moremem(cr_buffer *buf, int size)
{
char *ptr;
int total, n;
n = size / CR_BUFFER_SIZE + 1;
total = buf->size + n * CR_BUFFER_SIZE;
DEBUG("allocate %d x CR_BUFFER_SIZE, total %d bytes", n, total);
ptr = realloc(buf->data, total);
if (ptr == NULL)
return -1;
buf->data = ptr;
buf->size = total;
return 0;
}
/* Allocate at least `size' more multibulk storage, keeping content of
* previously allocated memory untouched.
* Returns:
* 0 on success
* -1 on error, i.e. more memory not available */
static int cr_morebulk(cr_multibulk *mb, int size)
{
char **cptr;
int *iptr;
int total, n;
n = (size / CR_MULTIBULK_SIZE + 1) * CR_MULTIBULK_SIZE;
total = mb->size + n;
DEBUG("allocate %d x CR_MULTIBULK_SIZE, total %d (%lu bytes)",
n, total, total * ((sizeof(char *)+sizeof(int))));
cptr = realloc(mb->bulks, total * sizeof(char *));
iptr = realloc(mb->idxs, total * sizeof(int));
if (cptr == NULL || iptr == NULL)
return CREDIS_ERR_NOMEM;
mb->bulks = cptr;
mb->idxs = iptr;
mb->size = total;
return 0;
}
/* Splits string `str' on character `token' builds a multi-bulk array from
* the items. This function will modify the contents of what `str' points
* to.
* Returns:
* 0 on success
* <0 on error, i.e. more memory not available */
static int cr_splitstrtomultibulk(REDIS rhnd, char *str, const char token)
{
int i = 0;
if (str != NULL) {
rhnd->reply.multibulk.bulks[i++] = str;
while ((str = strchr(str, token))) {
*str++ = '\0';
if (i >= rhnd->reply.multibulk.size)
if (cr_morebulk(&(rhnd->reply.multibulk), 1))
return CREDIS_ERR_NOMEM;
rhnd->reply.multibulk.bulks[i++] = str;
}
}
rhnd->reply.multibulk.len = i;
return 0;
}
/* Appends a printf style formatted to the end of buffer `buf'. If available
* memory in buffer is not enough to hold `str' more memory is allocated to
* the buffer.
* Returns:
* 0 on success
* <0 on error, i.e. more memory not available */
__attribute__ ((format(printf,2,3)))
static int cr_appendstrf(cr_buffer *buf, const char *format, ...)
{
int rc, avail;
va_list ap;
avail = buf->size - buf->len;
va_start(ap, format);
rc = vsnprintf(buf->data + buf->len, avail, format, ap);
va_end(ap);
if (rc < 0) {
#ifdef WIN32
rc = avail * 2;
#else
return -1;
#endif
}
while (rc >= avail) {
if (cr_moremem(buf, rc - avail + 1))
return CREDIS_ERR_NOMEM;
va_start(ap, format);
rc = vsnprintf(buf->data + buf->len, buf->size - buf->len, format, ap);
va_end(ap);
if (rc < 0) {
#ifdef WIN32
rc = avail * 2;
#else
return -1;
#endif
}
}
buf->len += rc;
return 0;
}
/* Appends a zero-terminated string `str' to the end of buffer `buf'. If
* available memory in buffer is not enough to hold `str' more memory is
* allocated to the buffer. If `space' is not 0 `str' is padded with a space.
* Returns:
* 0 on success
* <0 on error, i.e. more memory not available */
static int cr_appendstr(cr_buffer *buf, const char *str, int space)
{
int avail, len, reqd;
len = strlen(str);
avail = buf->size - buf->len;
/* required memory: len, terminating zero and possibly a space */
reqd = len + 1;
if (space)
reqd++;
if (reqd > avail)
if (cr_moremem(buf, reqd - avail + 1))
return CREDIS_ERR_NOMEM;
if (space)
buf->data[buf->len++] = ' ';
memcpy(buf->data + buf->len, str, len);
buf->len += len;
buf->data[buf->len] = '\0';
return 0;
}
/* Appends an array of strings `strv' to the end of buffer `buf', each
* separated with a space. If `newline' is not 0 "\r\n" is added last
* to buffer.
* Returns:
* 0 on success
* <0 on error, i.e. more memory not available */
static int cr_appendstrarray(cr_buffer *buf, int strc, const char **strv, int newline)
{
int rc, i;
for (i = 0; i < strc; i++) {
if ((rc = cr_appendstr(buf, strv[i], 1)) != 0)
return rc;
}
if (newline) {
if ((rc = cr_appendstr(buf, "\r\n", 0)) != 0)
return rc;
}
return 0;
}
/* Helper function for select that waits for `timeout' milliseconds
* for `fd' to become readable (`readable' == 1) or writable.
* Returns:
* >0 `fd' became readable or writable
* 0 timeout
* -1 on error */
int cr_select(int fd, int timeout, int readable)
{
struct timeval tv;
fd_set fds;
tv.tv_sec = timeout/1000;
tv.tv_usec = (timeout%1000)*1000;
FD_ZERO(&fds);
FD_SET(fd, &fds);
if (readable == 1)
return select(fd+1, &fds, NULL, NULL, &tv);
return select(fd+1, NULL, &fds, NULL, &tv);
}
#define cr_selectreadable(fd, timeout) cr_select(fd, timeout, 1)
#define cr_selectwritable(fd, timeout) cr_select(fd, timeout, 0)
/* Receives at most `size' bytes from socket `fd' to `buf'. Times out after
* `msecs' milliseconds if no data has yet arrived.
* Returns:
* >0 number of read bytes on success
* 0 server closed connection
* -1 on error
* -2 on timeout */
static int cr_receivedata(int fd, unsigned int msecs, char *buf, int size)
{
int rc = cr_selectreadable(fd, msecs);
if (rc > 0)
return recv(fd, buf, size, 0);
else if (rc == 0)
return -2;
else
return -1;
}
/* Sends `size' bytes from `buf' to socket `fd' and times out after `msecs'
* milliseconds if not all data has been sent.
* Returns:
* >0 number of bytes sent; if less than `size' it means that timeout occurred
* -1 on error */
static int cr_senddata(int fd, unsigned int msecs, char *buf, int size)
{
fd_set fds;
struct timeval tv;
int rc, sent=0;
/* NOTE: On Linux, select() modifies timeout to reflect the amount
* of time not slept, on other systems it is likely not the same */
tv.tv_sec = msecs/1000;
tv.tv_usec = (msecs%1000)*1000;
while (sent < size) {
FD_ZERO(&fds);
FD_SET(fd, &fds);
rc = select(fd+1, NULL, &fds, NULL, &tv);
if (rc > 0) {
rc = send(fd, buf+sent, size-sent, 0);
if (rc < 0)
return -1;
sent += rc;
}
else if (rc == 0) /* timeout */
break;
else
return -1;
}
return sent;
}
/* Buffered read line, returns pointer to zero-terminated string
* and length of that string. `start' specifies from which byte
* to start looking for "\r\n".
* Returns:
* >0 length of string to which pointer `line' refers. `idx' is
* an optional pointer for returning start index of line with
* respect to buffer.
* 0 connection to Redis server was closed
* -1 on error, i.e. a string is not available */
static int cr_readln(REDIS rhnd, int start, char **line, int *idx)
{
cr_buffer *buf = &(rhnd->buf);
char *nl;
int rc, len, avail, more;
/* do we need more data before we expect to find "\r\n"? */
if ((more = buf->idx + start + 2 - buf->len) < 0)
more = 0;
while (more > 0 ||
(nl = cr_findnl(buf->data + buf->idx + start, buf->len - (buf->idx + start))) == NULL) {
avail = buf->size - buf->len;
if (avail < CR_BUFFER_WATERMARK || avail < more) {
DEBUG("available buffer memory is low, get more memory");
if (cr_moremem(buf, more>0?more:1))
return CREDIS_ERR_NOMEM;
avail = buf->size - buf->len;
}
rc = cr_receivedata(rhnd->fd, rhnd->timeout, buf->data + buf->len, avail);
if (rc > 0) {
DEBUG("received %d bytes: %s", rc, buf->data + buf->len);
buf->len += rc;
}
else if (rc == 0)
return 0; /* EOF reached, connection terminated */
else
return -1; /* error */
/* do we need more data before we expect to find "\r\n"? */
if ((more = buf->idx + start + 2 - buf->len) < 0)
more = 0;
}
*nl = '\0'; /* zero terminate */
*line = buf->data + buf->idx;
if (idx)
*idx = buf->idx;
len = nl - *line;
buf->idx = (nl - buf->data) + 2; /* skip "\r\n" */
DEBUG("size=%d, len=%d, idx=%d, start=%d, line=%s",
buf->size, buf->len, buf->idx, start, *line);
return len;
}
static int cr_receivemultibulk(REDIS rhnd, char *line)
{
int bnum, blen, i, rc=0, idx;
char type;
bnum = atoi(line);
if (bnum == -1) {
rhnd->reply.multibulk.len = 0; /* no data or key didn't exist */
return 0;
}
else if (bnum > rhnd->reply.multibulk.size) {
DEBUG("available multibulk storage is low, get more memory");
if (cr_morebulk(&(rhnd->reply.multibulk), bnum - rhnd->reply.multibulk.size))
return CREDIS_ERR_NOMEM;
}
for (i = 0; bnum > 0 && (rc = cr_readln(rhnd, 0, &line, &idx)) > 0; i++, bnum--) {
type = *(line++);
if (type == CR_BULK) {
blen = atoi(line);
if (blen == -1)
rhnd->reply.multibulk.idxs[i] = -1;
else {
if ((rc = cr_readln(rhnd, blen, &line, &idx)) != blen)
return CREDIS_ERR_PROTOCOL;
rhnd->reply.multibulk.idxs[i] = idx;
}
}
else if (type == CR_INT) {
rhnd->reply.multibulk.idxs[i] = idx + 1;
}
else
return CREDIS_ERR_PROTOCOL;
}
if (bnum != 0) {
DEBUG("bnum != 0, bnum=%d, rc=%d", bnum, rc);
return CREDIS_ERR_PROTOCOL;
}
rhnd->reply.multibulk.len = i;
for (i = 0; i < rhnd->reply.multibulk.len; i++) {
if (rhnd->reply.multibulk.idxs[i] > 0)
rhnd->reply.multibulk.bulks[i] = rhnd->buf.data + rhnd->reply.multibulk.idxs[i];
else
rhnd->reply.multibulk.bulks[i] = NULL;
}
return 0;
}
static int cr_receivebulk(REDIS rhnd, char *line)
{
int blen;
blen = atoi(line);
if (blen == -1) {
rhnd->reply.bulk = NULL; /* key didn't exist */
return 0;
}
if (cr_readln(rhnd, blen, &line, NULL) >= 0) {
rhnd->reply.bulk = line;
return 0;
}
return CREDIS_ERR_PROTOCOL;
}
static int cr_receiveinline(REDIS rhnd, char *line)
{
rhnd->reply.line = line;
return 0;
}
static int cr_receiveint(REDIS rhnd, char *line)
{
rhnd->reply.integer = atoi(line);
return 0;
}
static int cr_receiveerror(REDIS rhnd, char *line)
{
rhnd->reply.line = line;
return CREDIS_ERR_PROTOCOL;
}
static int cr_receivereply(REDIS rhnd, char recvtype)
{
char *line, prefix=0;
/* reset common send/receive buffer */
rhnd->buf.len = 0;
rhnd->buf.idx = 0;
if (cr_readln(rhnd, 0, &line, NULL) > 0) {
prefix = *(line++);
if (recvtype != CR_ANY && prefix != recvtype && prefix != CR_ERROR)
return CREDIS_ERR_PROTOCOL;
rhnd->reply.type = prefix;
switch(prefix) {
case CR_ERROR:
return cr_receiveerror(rhnd, line);
case CR_INLINE:
return cr_receiveinline(rhnd, line);
case CR_INT:
return cr_receiveint(rhnd, line);
case CR_BULK:
return cr_receivebulk(rhnd, line);
case CR_MULTIBULK:
return cr_receivemultibulk(rhnd, line);
}
}
return CREDIS_ERR_RECV;
}
static void cr_delete(REDIS rhnd)
{
cr_freeallmessages(rhnd);
if (rhnd->reply.multibulk.bulks != NULL)
free(rhnd->reply.multibulk.bulks);
if (rhnd->reply.multibulk.idxs != NULL)
free(rhnd->reply.multibulk.idxs);
if (rhnd->buf.data != NULL)
free(rhnd->buf.data);
if (rhnd->ip != NULL)
free(rhnd->ip);
if (rhnd != NULL)
free(rhnd);
}
REDIS cr_new(void)
{
REDIS rhnd;
if ((rhnd = calloc(sizeof(cr_redis), 1)) == NULL ||
(rhnd->ip = malloc(32)) == NULL ||
(rhnd->buf.data = malloc(CR_BUFFER_SIZE)) == NULL ||
(rhnd->reply.multibulk.bulks = malloc(sizeof(char *)*CR_MULTIBULK_SIZE)) == NULL ||
(rhnd->reply.multibulk.idxs = malloc(sizeof(int)*CR_MULTIBULK_SIZE)) == NULL) {
cr_delete(rhnd);
return NULL;
}
rhnd->buf.size = CR_BUFFER_SIZE;
rhnd->reply.multibulk.size = CR_MULTIBULK_SIZE;
return rhnd;
}
/* Send message that has been prepared in message buffer prior to the call
* to this function. Wait and receive reply. */
static int cr_sendandreceive(REDIS rhnd, char recvtype)
{
int rc;
DEBUG("Sending message: len=%d, data=%s", rhnd->buf.len, rhnd->buf.data);
rc = cr_senddata(rhnd->fd, rhnd->timeout, rhnd->buf.data, rhnd->buf.len);
if (rc != rhnd->buf.len) {
if (rc < 0)
return CREDIS_ERR_SEND;
return CREDIS_ERR_TIMEOUT;
}
if (recvtype != CR_NONE)
rc = cr_receivereply(rhnd, recvtype);
return rc;
}
/* Prepare message buffer for sending using a printf()-style formatting. */
__attribute__ ((format(printf,3,4)))
static int cr_sendfandreceive(REDIS rhnd, char recvtype, const char *format, ...)
{
int rc;
va_list ap;
cr_buffer *buf = &(rhnd->buf);
va_start(ap, format);
rc = vsnprintf(buf->data, buf->size, format, ap);
va_end(ap);
if (rc < 0) {
#ifdef WIN32
/* handle the fact that vnsprintf() returns -1 if the buffer is too small */
rc = buf->size * 2;
#else
return -1;
#endif
}
while (rc >= buf->size) {
DEBUG("truncated, get more memory and try again");
if (cr_moremem(buf, rc - buf->size + 1))
return CREDIS_ERR_NOMEM;
va_start(ap, format);
rc = vsnprintf(buf->data, buf->size, format, ap);
va_end(ap);
if (rc < 0) {
#ifdef WIN32
rc = buf->size * 2;
#else
return -1;
#endif
}
}
buf->len = rc;
return cr_sendandreceive(rhnd, recvtype);
}
char * credis_errorreply(REDIS rhnd)
{
return rhnd->reply.line;
}
void credis_close(REDIS rhnd)
{
if (rhnd) {
if (rhnd->fd > 0)
close(rhnd->fd);
#ifdef WIN32
WSACleanup();
#endif
cr_delete(rhnd);
}
}
/* Requests Redis server information and tries to fill handle with server version
* information */
static int cr_getredisversion(REDIS rhnd)
{
/* We can receive 2 version formats: x.yz and x.y.z, where x.yz was only used prior
* first 1.1.0 release(?), e.g. stable releases 1.02 and 1.2.6 */
/* TODO check returned error string, "-ERR operation not permitted", to detect if
* server require password? */
if (cr_sendfandreceive(rhnd, CR_BULK, "INFO\r\n") == 0) {
int items = sscanf(rhnd->reply.bulk,
"redis_version:%d.%d.%d\r\n",
&(rhnd->version.major),
&(rhnd->version.minor),
&(rhnd->version.patch));
if (items == 2) {
rhnd->version.patch = rhnd->version.minor;
rhnd->version.minor = 0;
}
DEBUG("Connected to Redis version: %d.%d.%d\n",
rhnd->version.major, rhnd->version.minor, rhnd->version.patch);
}
return 0;
}
REDIS credis_connect(const char *host, int port, int timeout)
{
int fd, rc, flags, yes = 1;
struct sockaddr_in sa;
REDIS rhnd;
#ifdef WIN32
unsigned long addr;
WSADATA data;
if (WSAStartup(MAKEWORD(2,2), &data) != 0) {
DEBUG("Failed to init Windows Sockets DLL\n");
return NULL;
}
#endif
if ((rhnd = cr_new()) == NULL)
return NULL;
if (host == NULL)
host = "127.0.0.1";
if (port == 0)
port = 6379;
#ifdef WIN32
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ||
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char *)&yes, sizeof(yes)) == -1 ||
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char *)&yes, sizeof(yes)) == -1)
goto error;
#else
if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ||
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void *)&yes, sizeof(yes)) == -1 ||
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void *)&yes, sizeof(yes)) == -1)
goto error;
#endif
sa.sin_family = AF_INET;
sa.sin_port = htons(port);
#ifdef WIN32
struct hostent *he;
/* TODO use getaddrinfo() instead! */
addr = inet_addr(host);
if (addr == INADDR_NONE)
he = gethostbyname(host);
else
he = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET);
if (he == NULL)
goto error;
memcpy(&sa.sin_addr, he->h_addr, sizeof(struct in_addr));
#else
int err;
struct addrinfo hints, *info;
if (inet_aton(host, &sa.sin_addr) == 0) {
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
err = getaddrinfo(host, NULL, &hints, &info);
if (err)
DEBUG("getaddrinfo error: %s\n", gai_strerror(err));
memcpy(&sa.sin_addr.s_addr, &(info->ai_addr->sa_data[2]), sizeof(in_addr_t));
freeaddrinfo(info);
}
#endif
/* connect with user specified timeout */
flags = fcntl(fd, F_GETFL);
if ((rc = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) < 0) {
DEBUG("Setting socket non-blocking failed with: %d\n", rc);
}
if (connect(fd, (struct sockaddr *)&sa, sizeof(sa)) != 0) {
if (errno != EINPROGRESS)
goto error;
if (cr_selectwritable(fd, timeout) > 0) {
int err;
unsigned int len = sizeof(err);
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len) == -1 || err)
goto error;
}
else /* timeout or select error */
goto error;
}
/* else connect completed immediately */
strcpy(rhnd->ip, inet_ntoa(sa.sin_addr));
rhnd->port = port;
rhnd->fd = fd;
rhnd->timeout = timeout;
if (cr_getredisversion(rhnd) != 0)
goto error;
return rhnd;
error:
if (fd > 0)
close(fd);
cr_delete(rhnd);
return NULL;
}
void credis_settimeout(REDIS rhnd, int timeout)
{
rhnd->timeout = timeout;
}
int credis_set(REDIS rhnd, const char *key, const char *val)
{
return cr_sendfandreceive(rhnd, CR_INLINE, "SET %s %zu\r\n%s\r\n",
key, strlen(val), val);
}
int credis_setex(REDIS rhnd, const char *key, const char *val, int seconds)
{
return cr_sendfandreceive(rhnd, CR_INLINE, "SETEX %s %d %zu\r\n%s\r\n",
key, seconds, strlen(val), val);
}
int credis_get(REDIS rhnd, const char *key, char **val)
{
int rc = cr_sendfandreceive(rhnd, CR_BULK, "GET %s\r\n", key);
if (rc == 0 && (*val = rhnd->reply.bulk) == NULL)
return -1;
return rc;
}
int credis_getset(REDIS rhnd, const char *key, const char *set_val, char **get_val)
{
int rc = cr_sendfandreceive(rhnd, CR_BULK, "GETSET %s %zu\r\n%s\r\n",
key, strlen(set_val), set_val);
if (rc == 0 && (*get_val = rhnd->reply.bulk) == NULL)
return -1;
return rc;
}
int credis_ping(REDIS rhnd)
{
return cr_sendfandreceive(rhnd, CR_INLINE, "PING\r\n");
}
int credis_auth(REDIS rhnd, const char *password)
{
int rc = cr_sendfandreceive(rhnd, CR_INLINE, "AUTH %s\r\n", password);
/* Request Redis server version once we have been authenticated */
if (rc == 0)
return cr_getredisversion(rhnd);
return rc;
}
static int cr_multikeybulkcommand(REDIS rhnd, const char *cmd, int keyc,
const char **keyv, char ***valv)
{
cr_buffer *buf = &(rhnd->buf);
int rc;
buf->len = 0;
if ((rc = cr_appendstr(buf, cmd, 0)) != 0)
return rc;
if ((rc = cr_appendstrarray(buf, keyc, keyv, 1)) != 0)
return rc;
if ((rc = cr_sendandreceive(rhnd, CR_MULTIBULK)) == 0) {
*valv = rhnd->reply.multibulk.bulks;
rc = rhnd->reply.multibulk.len;
}
return rc;
}
static int cr_multikeystorecommand(REDIS rhnd, const char *cmd, const char *destkey,
int keyc, const char **keyv)
{
cr_buffer *buf = &(rhnd->buf);
int rc;
buf->len = 0;
if ((rc = cr_appendstr(buf, cmd, 0)) != 0)
return rc;
if ((rc = cr_appendstr(buf, destkey, 1)) != 0)
return rc;
if ((rc = cr_appendstrarray(buf, keyc, keyv, 1)) != 0)
return rc;
/* integer reply and not inline as documentation specifies */
if ((rc = cr_sendandreceive(rhnd, CR_INT)) == 0)
rc = rhnd->reply.integer;
return rc;
}
int credis_mget(REDIS rhnd, int keyc, const char **keyv, char ***valv)
{
return cr_multikeybulkcommand(rhnd, "MGET", keyc, keyv, valv);
}
int credis_setnx(REDIS rhnd, const char *key, const char *val)
{
int rc = cr_sendfandreceive(rhnd, CR_INT, "SETNX %s %zu\r\n%s\r\n",
key, strlen(val), val);
if (rc == 0 && rhnd->reply.integer == 0)
rc = -1;
return rc;
}
static int cr_incr(REDIS rhnd, int incr, int decr, const char *key, int *new_val)
{
int rc = 0;
if (incr == 1 || decr == 1)
rc = cr_sendfandreceive(rhnd, CR_INT, "%s %s\r\n",
incr>0?"INCR":"DECR", key);
else if (incr > 1 || decr > 1)
rc = cr_sendfandreceive(rhnd, CR_INT, "%s %s %d\r\n",
incr>0?"INCRBY":"DECRBY", key, incr>0?incr:decr);
if (rc == 0 && new_val != NULL)
*new_val = rhnd->reply.integer;
return rc;
}
int credis_incr(REDIS rhnd, const char *key, int *new_val)
{
return cr_incr(rhnd, 1, 0, key, new_val);
}
int credis_decr(REDIS rhnd, const char *key, int *new_val)
{
return cr_incr(rhnd, 0, 1, key, new_val);
}
int credis_incrby(REDIS rhnd, const char *key, int incr_val, int *new_val)
{
return cr_incr(rhnd, incr_val, 0, key, new_val);
}
int credis_decrby(REDIS rhnd, const char *key, int decr_val, int *new_val)
{
return cr_incr(rhnd, 0, decr_val, key, new_val);
}