forked from phpredis/phpredis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.c
2371 lines (2037 loc) · 67.2 KB
/
library.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
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "common.h"
#include "php_network.h"
#include <sys/types.h>
#ifndef _MSC_VER
#include <netinet/tcp.h> /* TCP_NODELAY */
#include <sys/socket.h>
#endif
#ifdef HAVE_REDIS_IGBINARY
#include "igbinary/igbinary.h"
#endif
#include <zend_exceptions.h>
#include "php_redis.h"
#include "library.h"
#include "redis_commands.h"
#include <ext/standard/php_rand.h>
#define UNSERIALIZE_NONE 0
#define UNSERIALIZE_KEYS 1
#define UNSERIALIZE_VALS 2
#define UNSERIALIZE_ALL 3
#define SCORE_DECODE_NONE 0
#define SCORE_DECODE_INT 1
#define SCORE_DECODE_DOUBLE 2
#ifdef PHP_WIN32
# if PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION <= 4
/* This proto is available from 5.5 on only */
PHP_REDIS_API int usleep(unsigned int useconds);
# endif
#endif
#if (PHP_MAJOR_VERSION < 7)
int (*_add_next_index_string)(zval *, const char *, int) = &add_next_index_string;
int (*_add_next_index_stringl)(zval *, const char *, uint, int) = &add_next_index_stringl;
int (*_add_assoc_bool_ex)(zval *, const char *, uint, int) = &add_assoc_bool_ex;
int (*_add_assoc_long_ex)(zval *, const char *, uint, long) = &add_assoc_long_ex;
int (*_add_assoc_double_ex)(zval *, const char *, uint, double) = &add_assoc_double_ex;
int (*_add_assoc_string_ex)(zval *, const char *, uint, char *, int) = &add_assoc_string_ex;
int (*_add_assoc_stringl_ex)(zval *, const char *, uint, char *, uint, int) = &add_assoc_stringl_ex;
int (*_add_assoc_zval_ex)(zval *, const char *, uint, zval *) = &add_assoc_zval_ex;
void (*_php_var_serialize)(smart_str *, zval **, php_serialize_data_t * TSRMLS_DC) = &php_var_serialize;
int (*_php_var_unserialize)(zval **, const unsigned char **, const unsigned char *, php_unserialize_data_t * TSRMLS_DC) = &php_var_unserialize;
#endif
extern zend_class_entry *redis_ce;
extern zend_class_entry *redis_exception_ce;
/* Helper to reselect the proper DB number when we reconnect */
static int reselect_db(RedisSock *redis_sock TSRMLS_DC) {
char *cmd, *response;
int cmd_len, response_len;
cmd_len = redis_cmd_format_static(&cmd, "SELECT", "d", redis_sock->dbNumber);
if (redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) {
efree(cmd);
return -1;
}
efree(cmd);
if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) {
return -1;
}
if (strncmp(response, "+OK", 3)) {
efree(response);
return -1;
}
efree(response);
return 0;
}
/* Helper to resend AUTH <password> in the case of a reconnect */
static int resend_auth(RedisSock *redis_sock TSRMLS_DC) {
char *cmd, *response;
int cmd_len, response_len;
cmd_len = redis_cmd_format_static(&cmd, "AUTH", "s", redis_sock->auth,
strlen(redis_sock->auth));
if (redis_sock_write(redis_sock, cmd, cmd_len TSRMLS_CC) < 0) {
efree(cmd);
return -1;
}
efree(cmd);
response = redis_sock_read(redis_sock, &response_len TSRMLS_CC);
if (response == NULL) {
return -1;
}
if (strncmp(response, "+OK", 3)) {
efree(response);
return -1;
}
efree(response);
return 0;
}
/* Helper function that will throw an exception for a small number of ERR codes
* returned by Redis. Typically we just return FALSE to the caller in the event
* of an ERROR reply, but for the following error types:
* 1) MASTERDOWN
* 2) AUTH
* 3) LOADING
*/
static void redis_error_throw(char *err, size_t err_len TSRMLS_DC) {
/* Handle stale data error (slave syncing with master) */
if (err_len == sizeof(REDIS_ERR_SYNC_MSG) - 1 &&
!memcmp(err,REDIS_ERR_SYNC_KW,sizeof(REDIS_ERR_SYNC_KW)-1))
{
zend_throw_exception(redis_exception_ce,
"SYNC with master in progress or master down!", 0 TSRMLS_CC);
} else if (err_len == sizeof(REDIS_ERR_LOADING_MSG) - 1 &&
!memcmp(err,REDIS_ERR_LOADING_KW,sizeof(REDIS_ERR_LOADING_KW)-1))
{
zend_throw_exception(redis_exception_ce,
"Redis is LOADING the dataset", 0 TSRMLS_CC);
} else if (err_len == sizeof(REDIS_ERR_AUTH_MSG) -1 &&
!memcmp(err,REDIS_ERR_AUTH_KW,sizeof(REDIS_ERR_AUTH_KW)-1))
{
zend_throw_exception(redis_exception_ce,
"Failed to AUTH connection", 0 TSRMLS_CC);
}
}
PHP_REDIS_API void redis_stream_close(RedisSock *redis_sock TSRMLS_DC) {
if (!redis_sock->persistent) {
php_stream_close(redis_sock->stream);
} else {
php_stream_pclose(redis_sock->stream);
}
}
PHP_REDIS_API int redis_check_eof(RedisSock *redis_sock, int no_throw TSRMLS_DC)
{
int eof;
int count = 0;
if (!redis_sock->stream) {
return -1;
}
/* NOITCE: set errno = 0 here
*
* There is a bug in php socket stream to check liveness of a connection:
* if (0 >= recv(sock->socket, &buf, sizeof(buf), MSG_PEEK) && php_socket_errno() != EWOULDBLOCK) {
* alive = 0;
* }
* If last errno is EWOULDBLOCK and recv returns 0 because of connection closed, alive would not be
* set to 0. However, the connection is close indeed. The php_stream_eof is not reliable. This will
* cause a "read error on connection" exception when use a closed persistent connection.
*
* We work around this by set errno = 0 first.
*
* Bug fix of php: https://github.com/php/php-src/pull/1456
* */
errno = 0;
eof = php_stream_eof(redis_sock->stream);
for (; eof; count++) {
if((MULTI == redis_sock->mode) || redis_sock->watching || count == 10) {
/* too many failures */
if(redis_sock->stream) { /* close stream if still here */
REDIS_STREAM_CLOSE_MARK_FAILED(redis_sock);
}
if(!no_throw) {
zend_throw_exception(redis_exception_ce, "Connection lost",
0 TSRMLS_CC);
}
return -1;
}
if(redis_sock->stream) { /* close existing stream before reconnecting */
redis_stream_close(redis_sock TSRMLS_CC);
redis_sock->stream = NULL;
redis_sock->mode = ATOMIC;
redis_sock->watching = 0;
}
// Wait for a while before trying to reconnect
if (redis_sock->retry_interval) {
// Random factor to avoid having several (or many) concurrent connections trying to reconnect at the same time
long retry_interval = (count ? redis_sock->retry_interval : (php_rand(TSRMLS_C) % redis_sock->retry_interval));
usleep(retry_interval);
}
redis_sock_connect(redis_sock TSRMLS_CC); /* reconnect */
if(redis_sock->stream) { /* check for EOF again. */
errno = 0;
eof = php_stream_eof(redis_sock->stream);
}
}
/* We've connected if we have a count */
if (count) {
/* If we're using a password, attempt a reauthorization */
if (redis_sock->auth && resend_auth(redis_sock TSRMLS_CC) != 0) {
return -1;
}
/* If we're using a non-zero db, reselect it */
if (redis_sock->dbNumber && reselect_db(redis_sock TSRMLS_CC) != 0) {
return -1;
}
}
/* Success */
return 0;
}
PHP_REDIS_API int
redis_sock_read_scan_reply(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock,
REDIS_SCAN_TYPE type, zend_long *iter)
{
REDIS_REPLY_TYPE reply_type;
long reply_info;
char *p_iter;
/* Our response should have two multibulk replies */
if(redis_read_reply_type(redis_sock, &reply_type, &reply_info TSRMLS_CC)<0
|| reply_type != TYPE_MULTIBULK || reply_info != 2)
{
return -1;
}
/* The BULK response iterator */
if(redis_read_reply_type(redis_sock, &reply_type, &reply_info TSRMLS_CC)<0
|| reply_type != TYPE_BULK)
{
return -1;
}
/* Attempt to read the iterator */
if(!(p_iter = redis_sock_read_bulk_reply(redis_sock, reply_info TSRMLS_CC))) {
return -1;
}
/* Push the iterator out to the caller */
*iter = atol(p_iter);
efree(p_iter);
/* Read our actual keys/members/etc differently depending on what kind of
scan command this is. They all come back in slightly different ways */
switch(type) {
case TYPE_SCAN:
return redis_mbulk_reply_raw(INTERNAL_FUNCTION_PARAM_PASSTHRU,
redis_sock, NULL, NULL);
case TYPE_SSCAN:
return redis_sock_read_multibulk_reply(
INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, NULL, NULL);
case TYPE_ZSCAN:
return redis_mbulk_reply_zipped_keys_dbl(INTERNAL_FUNCTION_PARAM_PASSTHRU,
redis_sock, NULL, NULL);
case TYPE_HSCAN:
return redis_mbulk_reply_zipped_vals(INTERNAL_FUNCTION_PARAM_PASSTHRU,
redis_sock, NULL, NULL);
default:
return -1;
}
}
PHP_REDIS_API int redis_subscribe_response(INTERNAL_FUNCTION_PARAMETERS,
RedisSock *redis_sock, zval *z_tab,
void *ctx)
{
subscribeContext *sctx = (subscribeContext*)ctx;
zval *z_tmp, z_resp;
// Consume response(s) from subscribe, which will vary on argc
while(sctx->argc--) {
if (!redis_sock_read_multibulk_reply_zval(
INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, &z_resp)
) {
efree(sctx);
return -1;
}
// We'll need to find the command response
if ((z_tmp = zend_hash_index_find(Z_ARRVAL(z_resp), 0)) == NULL) {
zval_dtor(&z_resp);
efree(sctx);
return -1;
}
// Make sure the command response matches the command we called
if(strcasecmp(Z_STRVAL_P(z_tmp), sctx->kw) !=0) {
zval_dtor(&z_resp);
efree(sctx);
return -1;
}
zval_dtor(&z_resp);
}
#if (PHP_MAJOR_VERSION < 7)
zval *z_ret, **z_args[4];
sctx->cb.retval_ptr_ptr = &z_ret;
#else
zval z_ret, z_args[4];
sctx->cb.retval = &z_ret;
#endif
sctx->cb.params = z_args;
sctx->cb.no_separation = 0;
/* Multibulk response, {[pattern], type, channel, payload } */
while(1) {
zval *z_type, *z_chan, *z_pat = NULL, *z_data;
HashTable *ht_tab;
int tab_idx=1, is_pmsg;
if (!redis_sock_read_multibulk_reply_zval(
INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, &z_resp)) break;
ht_tab = Z_ARRVAL(z_resp);
if ((z_type = zend_hash_index_find(ht_tab, 0)) == NULL ||
Z_TYPE_P(z_type) != IS_STRING
) {
break;
}
// Check for message or pmessage
if(!strncmp(Z_STRVAL_P(z_type), "message", 7) ||
!strncmp(Z_STRVAL_P(z_type), "pmessage", 8))
{
is_pmsg = *Z_STRVAL_P(z_type)=='p';
} else {
break;
}
// Extract pattern if it's a pmessage
if(is_pmsg) {
if ((z_pat = zend_hash_index_find(ht_tab, tab_idx++)) == NULL) {
break;
}
}
// Extract channel and data
if ((z_chan = zend_hash_index_find(ht_tab, tab_idx++)) == NULL ||
(z_data = zend_hash_index_find(ht_tab, tab_idx++)) == NULL
) {
break;
}
// Different args for SUBSCRIBE and PSUBSCRIBE
#if (PHP_MAJOR_VERSION < 7)
z_args[0] = &getThis();
if(is_pmsg) {
z_args[1] = &z_pat;
z_args[2] = &z_chan;
z_args[3] = &z_data;
} else {
z_args[1] = &z_chan;
z_args[2] = &z_data;
}
#else
z_args[0] = *getThis();
if(is_pmsg) {
z_args[1] = *z_pat;
z_args[2] = *z_chan;
z_args[3] = *z_data;
} else {
z_args[1] = *z_chan;
z_args[2] = *z_data;
}
#endif
// Set arg count
sctx->cb.param_count = tab_idx;
// Execute callback
if(zend_call_function(&(sctx->cb), &(sctx->cb_cache) TSRMLS_CC)
==FAILURE)
{
break;
}
// If we have a return value free it
zval_ptr_dtor(&z_ret);
zval_dtor(&z_resp);
}
// This is an error state, clean up
zval_dtor(&z_resp);
efree(sctx);
return -1;
}
PHP_REDIS_API int redis_unsubscribe_response(INTERNAL_FUNCTION_PARAMETERS,
RedisSock *redis_sock, zval *z_tab,
void *ctx)
{
subscribeContext *sctx = (subscribeContext*)ctx;
zval *z_chan, zv, *z_ret = &zv, z_resp;
int i;
array_init(z_ret);
for (i = 0; i < sctx->argc; i++) {
if (!redis_sock_read_multibulk_reply_zval(
INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, &z_resp) ||
(z_chan = zend_hash_index_find(Z_ARRVAL(z_resp), 1)) == NULL
) {
zval_dtor(z_ret);
return -1;
}
add_assoc_bool(z_ret, Z_STRVAL_P(z_chan), 1);
zval_dtor(&z_resp);
}
efree(sctx);
RETVAL_ZVAL(z_ret, 0, 1);
// Success
return 0;
}
PHP_REDIS_API zval *
redis_sock_read_multibulk_reply_zval(INTERNAL_FUNCTION_PARAMETERS,
RedisSock *redis_sock, zval *z_tab)
{
char inbuf[1024];
int numElems;
if(-1 == redis_check_eof(redis_sock, 0 TSRMLS_CC)) {
return NULL;
}
if(php_stream_gets(redis_sock->stream, inbuf, 1024) == NULL) {
REDIS_STREAM_CLOSE_MARK_FAILED(redis_sock);
zend_throw_exception(redis_exception_ce,
"read error on connection", 0 TSRMLS_CC);
return NULL;
}
if(inbuf[0] != '*') {
return NULL;
}
numElems = atoi(inbuf+1);
array_init(z_tab);
redis_mbulk_reply_loop(INTERNAL_FUNCTION_PARAM_PASSTHRU, redis_sock, z_tab,
numElems, UNSERIALIZE_ALL);
return z_tab;
}
/**
* redis_sock_read_bulk_reply
*/
PHP_REDIS_API char *redis_sock_read_bulk_reply(RedisSock *redis_sock, int bytes TSRMLS_DC)
{
int offset = 0;
size_t got;
char *reply, c[2];
if (-1 == bytes || -1 == redis_check_eof(redis_sock, 0 TSRMLS_CC)) {
return NULL;
}
reply = emalloc(bytes+1);
while(offset < bytes) {
got = php_stream_read(redis_sock->stream, reply + offset,
bytes-offset);
if (got <= 0) {
/* Error or EOF */
zend_throw_exception(redis_exception_ce,
"socket error on read socket", 0 TSRMLS_CC);
break;
}
offset += got;
}
php_stream_read(redis_sock->stream, c, 2);
reply[bytes] = 0;
return reply;
}
/**
* redis_sock_read
*/
PHP_REDIS_API char *redis_sock_read(RedisSock *redis_sock, int *buf_len TSRMLS_DC)
{
char inbuf[1024];
size_t err_len;
*buf_len = 0;
if(-1 == redis_check_eof(redis_sock, 0 TSRMLS_CC)) {
return NULL;
}
if(php_stream_gets(redis_sock->stream, inbuf, 1024) == NULL) {
REDIS_STREAM_CLOSE_MARK_FAILED(redis_sock);
zend_throw_exception(redis_exception_ce, "read error on connection",
0 TSRMLS_CC);
return NULL;
}
switch(inbuf[0]) {
case '-':
err_len = strlen(inbuf+1) - 2;
redis_sock_set_err(redis_sock, inbuf+1, err_len);
/* Filter our ERROR through the few that should actually throw */
redis_error_throw(inbuf + 1, err_len TSRMLS_CC);
/* Handle stale data error */
if(memcmp(inbuf + 1, "-ERR SYNC ", 10) == 0) {
zend_throw_exception(redis_exception_ce,
"SYNC with master in progress", 0 TSRMLS_CC);
}
return NULL;
case '$':
*buf_len = atoi(inbuf + 1);
return redis_sock_read_bulk_reply(redis_sock, *buf_len TSRMLS_CC);
case '*':
/* For null multi-bulk replies (like timeouts from brpoplpush): */
if(memcmp(inbuf + 1, "-1", 2) == 0) {
return NULL;
}
/* fall through */
case '+':
case ':':
/* Single Line Reply */
/* :123\r\n */
*buf_len = strlen(inbuf) - 2;
if(*buf_len >= 2) {
return estrndup(inbuf, *buf_len);
}
default:
zend_throw_exception_ex(
redis_exception_ce,
0 TSRMLS_CC,
"protocol error, got '%c' as reply type byte\n",
inbuf[0]
);
}
return NULL;
}
int
integer_length(int i) {
int sz = 0;
int ci = abs(i);
while (ci > 0) {
ci /= 10;
sz++;
}
if (i == 0) { /* log 0 doesn't make sense. */
sz = 1;
} else if (i < 0) { /* allow for neg sign as well. */
sz++;
}
return sz;
}
int
redis_cmd_format_header(char **ret, char *keyword, int arg_count) {
/* Our return buffer */
smart_string buf = {0};
/* Keyword length */
int l = strlen(keyword);
smart_string_appendc(&buf, '*');
smart_string_append_long(&buf, arg_count + 1);
smart_string_appendl(&buf, _NL, sizeof(_NL) -1);
smart_string_appendc(&buf, '$');
smart_string_append_long(&buf, l);
smart_string_appendl(&buf, _NL, sizeof(_NL) -1);
smart_string_appendl(&buf, keyword, l);
smart_string_appendl(&buf, _NL, sizeof(_NL) - 1);
/* Set our return pointer */
*ret = buf.c;
/* Return the length */
return buf.len;
}
int
redis_cmd_format_static(char **ret, char *keyword, char *format, ...)
{
char *p = format;
va_list ap;
smart_string buf = {0};
int l = strlen(keyword);
zend_string *dbl_str;
va_start(ap, format);
/* add header */
smart_string_appendc(&buf, '*');
smart_string_append_long(&buf, strlen(format) + 1);
smart_string_appendl(&buf, _NL, sizeof(_NL) - 1);
smart_string_appendc(&buf, '$');
smart_string_append_long(&buf, l);
smart_string_appendl(&buf, _NL, sizeof(_NL) - 1);
smart_string_appendl(&buf, keyword, l);
smart_string_appendl(&buf, _NL, sizeof(_NL) - 1);
while (*p) {
smart_string_appendc(&buf, '$');
switch(*p) {
case 's': {
char *val = va_arg(ap, char*);
int val_len = va_arg(ap, int);
smart_string_append_long(&buf, val_len);
smart_string_appendl(&buf, _NL, sizeof(_NL) - 1);
smart_string_appendl(&buf, val, val_len);
}
break;
case 'f':
case 'F': {
double d = va_arg(ap, double);
REDIS_DOUBLE_TO_STRING(dbl_str, d);
smart_string_append_long(&buf, dbl_str->len);
smart_string_appendl(&buf, _NL, sizeof(_NL) - 1);
smart_string_appendl(&buf, dbl_str->val, dbl_str->len);
zend_string_release(dbl_str);
}
break;
case 'i':
case 'd': {
int i = va_arg(ap, int);
char tmp[32];
int tmp_len = snprintf(tmp, sizeof(tmp), "%d", i);
smart_string_append_long(&buf, tmp_len);
smart_string_appendl(&buf, _NL, sizeof(_NL) - 1);
smart_string_appendl(&buf, tmp, tmp_len);
}
break;
case 'l':
case 'L': {
long l = va_arg(ap, long);
char tmp[32];
int tmp_len = snprintf(tmp, sizeof(tmp), "%ld", l);
smart_string_append_long(&buf, tmp_len);
smart_string_appendl(&buf, _NL, sizeof(_NL) -1);
smart_string_appendl(&buf, tmp, tmp_len);
}
break;
}
p++;
smart_string_appendl(&buf, _NL, sizeof(_NL) - 1);
}
smart_string_0(&buf);
*ret = buf.c;
return buf.len;
}
/**
* This command behave somehow like printf, except that strings need 2
* arguments:
* Their data and their size (strlen).
* Supported formats are: %d, %i, %s, %l
*/
int
redis_cmd_format(char **ret, char *format, ...) {
smart_string buf = {0};
va_list ap;
char *p = format;
zend_string *dbl_str;
va_start(ap, format);
while (*p) {
if (*p == '%') {
switch (*(++p)) {
case 's': {
char *tmp = va_arg(ap, char*);
int tmp_len = va_arg(ap, int);
smart_string_appendl(&buf, tmp, tmp_len);
}
break;
case 'F':
case 'f': {
double d = va_arg(ap, double);
REDIS_DOUBLE_TO_STRING(dbl_str, d);
smart_string_append_long(&buf, dbl_str->len);
smart_string_appendl(&buf, _NL, sizeof(_NL) - 1);
smart_string_appendl(&buf, dbl_str->val, dbl_str->len);
zend_string_release(dbl_str);
}
break;
case 'd':
case 'i': {
int i = va_arg(ap, int);
char tmp[32];
int tmp_len = snprintf(tmp, sizeof(tmp), "%d", i);
smart_string_appendl(&buf, tmp, tmp_len);
}
break;
}
} else {
smart_string_appendc(&buf, *p);
}
p++;
}
smart_string_0(&buf);
*ret = buf.c;
return buf.len;
}
/*
* Append a command sequence to a Redis command
*/
int redis_cmd_append_str(char **cmd, int cmd_len, char *append, int append_len) {
/* Smart string buffer */
smart_string buf = {0};
/* Append the current command to our smart_string */
smart_string_appendl(&buf, *cmd, cmd_len);
/* Append our new command sequence */
smart_string_appendc(&buf, '$');
smart_string_append_long(&buf, append_len);
smart_string_appendl(&buf, _NL, sizeof(_NL) -1);
smart_string_appendl(&buf, append, append_len);
smart_string_appendl(&buf, _NL, sizeof(_NL) -1);
/* Free our old command */
efree(*cmd);
/* Set our return pointer */
*cmd = buf.c;
/* Return new command length */
return buf.len;
}
/*
* Given a smart string, number of arguments, a keyword, and the length of the keyword
* initialize our smart string with the proper Redis header for the command to follow
*/
int redis_cmd_init_sstr(smart_string *str, int num_args, char *keyword, int keyword_len) {
smart_string_appendc(str, '*');
smart_string_append_long(str, num_args + 1);
smart_string_appendl(str, _NL, sizeof(_NL) -1);
smart_string_appendc(str, '$');
smart_string_append_long(str, keyword_len);
smart_string_appendl(str, _NL, sizeof(_NL) - 1);
smart_string_appendl(str, keyword, keyword_len);
smart_string_appendl(str, _NL, sizeof(_NL) - 1);
return str->len;
}
/*
* Append a command sequence to a smart_string
*/
int redis_cmd_append_sstr(smart_string *str, char *append, int append_len) {
smart_string_appendc(str, '$');
smart_string_append_long(str, append_len);
smart_string_appendl(str, _NL, sizeof(_NL) - 1);
smart_string_appendl(str, append, append_len);
smart_string_appendl(str, _NL, sizeof(_NL) - 1);
/* Return our new length */
return str->len;
}
/*
* Append an integer to a smart string command
*/
int redis_cmd_append_sstr_int(smart_string *str, int append) {
char int_buf[32];
int int_len = snprintf(int_buf, sizeof(int_buf), "%d", append);
return redis_cmd_append_sstr(str, int_buf, int_len);
}
/*
* Append a long to a smart string command
*/
int redis_cmd_append_sstr_long(smart_string *str, long append) {
char long_buf[32];
int long_len = snprintf(long_buf, sizeof(long_buf), "%ld", append);
return redis_cmd_append_sstr(str, long_buf, long_len);
}
/*
* Append a double to a smart string command
*/
int redis_cmd_append_sstr_dbl(smart_string *str, double value) {
zend_string *dbl_str;
int retval;
/* Convert to double */
REDIS_DOUBLE_TO_STRING(dbl_str, value);
// Append the string
retval = redis_cmd_append_sstr(str, dbl_str->val, dbl_str->len);
/* Free our double string */
zend_string_release(dbl_str);
/* Return new length */
return retval;
}
/*
* Append an integer command to a Redis command
*/
int redis_cmd_append_int(char **cmd, int cmd_len, int append) {
char int_buf[32];
int int_len;
// Conver to an int, capture length
int_len = snprintf(int_buf, sizeof(int_buf), "%d", append);
/* Return the new length */
return redis_cmd_append_str(cmd, cmd_len, int_buf, int_len);
}
PHP_REDIS_API void redis_bulk_double_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) {
char *response;
int response_len;
double ret;
if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) {
IF_MULTI_OR_PIPELINE() {
add_next_index_bool(z_tab, 0);
return;
} else {
RETURN_FALSE;
}
}
ret = atof(response);
efree(response);
IF_MULTI_OR_PIPELINE() {
add_next_index_double(z_tab, ret);
} else {
RETURN_DOUBLE(ret);
}
}
PHP_REDIS_API void redis_type_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) {
char *response;
int response_len;
long l;
if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) {
IF_MULTI_OR_PIPELINE() {
add_next_index_bool(z_tab, 0);
return;
} else {
RETURN_FALSE;
}
}
if (strncmp(response, "+string", 7) == 0) {
l = REDIS_STRING;
} else if (strncmp(response, "+set", 4) == 0){
l = REDIS_SET;
} else if (strncmp(response, "+list", 5) == 0){
l = REDIS_LIST;
} else if (strncmp(response, "+zset", 5) == 0){
l = REDIS_ZSET;
} else if (strncmp(response, "+hash", 5) == 0){
l = REDIS_HASH;
} else {
l = REDIS_NOT_FOUND;
}
efree(response);
IF_MULTI_OR_PIPELINE() {
add_next_index_long(z_tab, l);
} else {
RETURN_LONG(l);
}
}
PHP_REDIS_API void redis_info_response(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab, void *ctx) {
char *response;
int response_len;
zval zv, *z_ret = &zv;
/* Read bulk response */
if ((response = redis_sock_read(redis_sock, &response_len TSRMLS_CC)) == NULL) {
RETURN_FALSE;
}
/* Parse it into a zval array */
redis_parse_info_response(response, z_ret);
/* Free source response */
efree(response);
IF_MULTI_OR_PIPELINE() {
add_next_index_zval(z_tab, z_ret);
} else {
RETVAL_ZVAL(z_ret, 0, 1);
}
}
PHP_REDIS_API void
redis_parse_info_response(char *response, zval *z_ret)
{
char *key, *value, *p, *cur, *pos;
int is_numeric;
array_init(z_ret);
cur = response;
while(1) {
/* skip comments and empty lines */
if(*cur == '#' || *cur == '\r') {
if(!(cur = strchr(cur, '\n')))
break;
cur++;
continue;
}
/* key */
pos = strchr(cur, ':');
if(pos == NULL) {
break;
}
key = estrndup(cur, pos - cur);
/* value */
cur = pos + 1;
pos = strchr(cur, '\r');
if(pos == NULL) {
efree(key);
break;
}
value = estrndup(cur, pos - cur);
pos += 2; /* \r, \n */
cur = pos;
is_numeric = 1;
for(p = value; *p; ++p) {
if(*p < '0' || *p > '9') {
is_numeric = 0;
break;
}
}
if(is_numeric == 1) {
add_assoc_long(z_ret, key, atol(value));
} else {
add_assoc_string(z_ret, key, value);
}
efree(value);
efree(key);
}
}
/*
* Specialized handling of the CLIENT LIST output so it comes out in a simple way for PHP userland code
* to handle.
*/
PHP_REDIS_API void redis_client_list_reply(INTERNAL_FUNCTION_PARAMETERS, RedisSock *redis_sock, zval *z_tab) {
char *resp;
int resp_len;
/* Make sure we can read the bulk response from Redis */
if ((resp = redis_sock_read(redis_sock, &resp_len TSRMLS_CC)) == NULL) {
RETURN_FALSE;
}
zval zv, *z_ret = &zv;
#if (PHP_MAJOR_VERSION < 7)
MAKE_STD_ZVAL(z_ret);
#endif
/* Parse it out */
redis_parse_client_list_response(resp, z_ret);
/* Free our response */
efree(resp);