-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsquirrel.c
2105 lines (1852 loc) · 64.1 KB
/
squirrel.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 (c) 2010 - 2011, Liexusong <[email protected]>
* All rights reserved.
* Please visit http://code.google.com/p/squirrel-message-queue/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 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.
*/
/*
* commands:=======================================
* Put item into the queue: (PUTF/PUTL)
* Pop item from the queue: (POPF/POPL/POPP/POPS)
* Get item from the queue: (GETF/GETL/GETP/GETS)
* Get status of the queue: (STAT/SLAB)
* Get the size of the queue: (SIZE)
* Auth the server: (AUTH)
* Or more ......
*=================================================
* d(>_<)b
* liexusong
* @旭松_Lie
*=================================================
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/signal.h>
#include <sys/resource.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <time.h>
#include <pthread.h>
/* lua libs */
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
/* squirrel libs */
#include "ae.h"
#include "zmalloc.h"
#include "config.h"
#include "slabs.h"
#include "dlist.h"
/* defined DEBUG macro can show the message on console */
#if 0
#define DEBUG 1
#endif
#define SQUIRREL_VERSION "1.3 Final"
#define DEFAULT_PORT 6061
#define CLIENT_CACHES_SIZE 1000
#define RDB_HEADER_BLOCK "SQUIRREL0013"
#define QUE_RDB_FILENAME "squirrel.db"
#define RECV_BUFF_SIZE 2048
#define SEND_BUFF_SIZE 2048
#define IGNORE_BUFF_SIZE 2048
#define LOG_ERROR 2
#define LOG_NOTICE 1
#define LOG_DEBUG 2
#define TOKEN_MAX_LEN 256
#define TOKEN_DEFAULT_SIZE 20
typedef enum
{
RECV_STATE, /* read state */
NRECV_STATE, /* nread state */
CRLF_STATE, /* crlf state */
IGNORE_STATE,/* ignore state */
SEND_STATE, /* write state */
MSEND_STATE, /* msend state */
CLOSE_STATE /* close state */
} smq_status_t;
typedef struct smq_client_s smq_client_t;
struct smq_client_s {
int fd;
int flag;
smq_status_t state;
char cRecvBuffer[RECV_BUFF_SIZE];
int cRecvBytes;
int cRecvWhere;
short crlf_bytes;
char cSendBuffer[SEND_BUFF_SIZE];
int cSendBytes;
int cSendWhere;
char cIgnoreBuffer[IGNORE_BUFF_SIZE];
int cIgnoreBytes;
struct list *replyList;
int replyStage;
time_t lastTransportTime;
char *mSendBuffer;
char *mRecvBuffer;
int isauth;
smq_client_t *prev;
smq_client_t *next;
};
typedef struct {
int fd;
short listingPort;
aeEventLoop *eventLoop;
struct list *queue;
smq_client_t *clientCaches[CLIENT_CACHES_SIZE];
int clientCachesUsed;
int secondsToSaveDisk;
int memoryLimitUsed;
int memoryUsedTotal;
pid_t bgSaveChildpid;
time_t lastSaveTime;
int clientExpiredTime;
int dirty;
int chagesToSaveDisk;
int cronLoops;
int daemonize;
int connections;
int enableauth;
char *authpwd;
char *luaFilePath;
char *luaMainFunction;
char *pidFilePath;
smq_client_t *clientListHead;
smq_client_t *clientListTail;
} smq_server_t;
struct config_t {
char *key;
char *val;
struct config_t *next;
};
typedef struct {
int refcount;
int blockSize;
char block[0];
} smq_block_t;
typedef struct {
char token[TOKEN_MAX_LEN + 1];
} token_t;
typedef int (*do_command_cb)(smq_client_t *conn, token_t *tokens, int tokencount);
typedef struct {
char *cmdname;
do_command_cb cb;
int argc;
} command_cb_t;
int putf_command(smq_client_t *conn, token_t *tokens, int tokencount);
int putl_command(smq_client_t *conn, token_t *tokens, int tokencount);
int popf_command(smq_client_t *conn, token_t *tokens, int tokencount);
int popl_command(smq_client_t *conn, token_t *tokens, int tokencount);
int popp_command(smq_client_t *conn, token_t *tokens, int tokencount);
int pops_command(smq_client_t *conn, token_t *tokens, int tokencount);
int getf_command(smq_client_t *conn, token_t *tokens, int tokencount);
int getl_command(smq_client_t *conn, token_t *tokens, int tokencount);
int getp_command(smq_client_t *conn, token_t *tokens, int tokencount);
int gets_command(smq_client_t *conn, token_t *tokens, int tokencount);
int stat_command(smq_client_t *conn, token_t *tokens, int tokencount);
int slab_command(smq_client_t *conn, token_t *tokens, int tokencount);
int size_command(smq_client_t *conn, token_t *tokens, int tokencount);
int close_command(smq_client_t *conn, token_t *tokens, int tokencount);
static command_cb_t callbacks[] = {
{"PUTF", putf_command, 2},
{"PUTL", putl_command, 2},
{"POPF", popf_command, 1},
{"POPL", popl_command, 1},
{"POPP", popp_command, 2},
{"POPS", pops_command, 2},
{"GETF", getf_command, 1},
{"GETL", getl_command, 1},
{"GETP", getp_command, 2},
{"GETS", gets_command, 2},
{"STAT", stat_command, 1},
{"SLAB", slab_command, 1},
{"SIZE", size_command, 1},
{"CLOSE", close_command, 1},
{"QUIT", close_command, 1},
{"EXIT", close_command, 1},
{NULL, NULL, 0}
};
void machine(smq_client_t *conn);
void clientCloseRemove(smq_client_t *conn);
int serverCron(struct aeEventLoop *eventLoop, long long id, void *clientData);
int doItemDecrRefcount(void *item);
#define do_connection_status(conn, _state) ((conn)->state = _state)
#define do_connection_recv_empty(conn) do \
{\
(conn)->cRecvBytes = 0;\
(conn)->cRecvWhere = 0;\
} while(0)
#define do_connection_send_empty(conn) do \
{\
(conn)->cSendBytes = 0;\
(conn)->cSendWhere = 0;\
} while(0)
#define do_connection_nrecvbuf_empty(conn) ((conn)->mRecvBuffer = NULL)
#define do_connection_nsendbuf_empty(conn) ((conn)->mSendBuffer = NULL)
#define do_client_link(conn) do \
{\
conn->prev = NULL;\
conn->next = server.clientListHead;\
if (server.clientListHead)\
server.clientListHead->prev = conn;\
server.clientListHead = conn;\
if (!server.clientListTail)\
server.clientListTail = server.clientListHead;\
} while(0)
#define do_client_unlink(conn) do \
{\
if (conn->prev)\
conn->prev->next = conn->next;\
else\
server.clientListHead = conn->next;\
if (conn->next)\
conn->next->prev = conn->prev;\
else\
server.clientListTail = conn->prev;\
} while(0)
#define thread_lock_list() pthread_mutex_lock(&listGlobalLock)
#define thread_unlock_list() pthread_mutex_unlock(&listGlobalLock)
/* There are global varibles for server */
static smq_server_t server;
static struct config_t *config_item_head = NULL;
static pthread_mutex_t listGlobalLock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t listGlobalCondition = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t serverGlobalLock = PTHREAD_MUTEX_INITIALIZER;
void smqLog(int level, const char *fmt, ...) {
va_list ap;
FILE *fp;
char log_path[1024];
struct tm *tm;
time_t ts;
#if defined(DEBUG) && DEBUG
fp = stdout;
#else
ts = time(NULL);
tm = gmtime(&ts);
sprintf(log_path, "RaSqueue.%d%d.log", tm->tm_year + 1900, tm->tm_mon + 1);
fp = fopen(log_path, "a+");
if (!fp) return;
#endif
va_start(ap, fmt);
char *c = "-*+";
char buf[64];
time_t now;
now = time(NULL);
strftime(buf, 64, "[%d %b %H:%M:%S]", gmtime(&now));
fprintf(fp, "%s %c ", buf, c[level]);
vfprintf(fp, fmt, ap);
fprintf(fp, "\n");
fflush(fp);
va_end(ap);
#ifndef DEBUG
fclose(fp);
#endif
}
int setNonblock(int fd) {
int flags;
if ((flags = fcntl(fd, F_GETFL, 0)) < 0 || fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0)
return -1;
return 0;
}
void eventActionFunction(struct aeEventLoop *eventLoop, int fd, void *clientData, int mask) {
smq_client_t *conn = (smq_client_t *)clientData;
if (conn->fd != fd) {
clientCloseRemove(conn);
smqLog(LOG_NOTICE, "catastrophic, event fd doesn't match conn fd!\n");
return;
}
machine(conn);
return;
}
smq_client_t *clientAllocObject(int fd, smq_status_t state, int flag) {
smq_client_t *conn = NULL;
pthread_mutex_lock(&serverGlobalLock);
if (server.clientCachesUsed > 0)
conn = server.clientCaches[--server.clientCachesUsed];
pthread_mutex_unlock(&serverGlobalLock);
if (NULL == conn) {
conn = (smq_client_t *)malloc(sizeof(smq_client_t));
if (!conn) {
smqLog(LOG_NOTICE, "Not enough memory to alloc squirrelClient");
return NULL;
}
conn->replyList = list_init((list_destroy_function_t)doItemDecrRefcount, 128);
if (!conn->replyList) {
free(conn);
smqLog(LOG_NOTICE, "Not enough memory to alloc replyList");
return NULL;
}
}
conn->fd = fd;
conn->flag = flag;
do_connection_status(conn, state);
do_connection_recv_empty(conn);
do_connection_send_empty(conn);
conn->crlf_bytes = 0;
conn->cIgnoreBytes = 0;
conn->replyStage = 0;
conn->mSendBuffer = NULL;
conn->mRecvBuffer = NULL;
conn->lastTransportTime = time(NULL);
conn->isauth = 0;
pthread_mutex_lock(&serverGlobalLock);
aeCreateFileEvent(server.eventLoop, conn->fd, AE_READABLE, eventActionFunction, (void *)conn);
do_client_link(conn);
server.connections++;
pthread_mutex_unlock(&serverGlobalLock);
return conn;
}
void clientCloseRemove(smq_client_t *conn) {
if (conn == NULL)
return;
close(conn->fd);
pthread_mutex_lock(&serverGlobalLock);
aeDeleteFileEvent(server.eventLoop, conn->fd, AE_READABLE | AE_WRITABLE);
do_client_unlink(conn);
server.connections--;
if (server.clientCachesUsed < CLIENT_CACHES_SIZE) {
server.clientCaches[server.clientCachesUsed++] = conn;
pthread_mutex_unlock(&serverGlobalLock);
return;
}
pthread_mutex_unlock(&serverGlobalLock);
list_destroy(conn->replyList);
free(conn);
return;
}
#if 0
void acceptActionFunction(struct aeEventLoop *eventLoop, int fd, void *clientData, int mask) {
int cfd, flags = 1;
socklen_t addrlen;
struct sockaddr addr;
smq_client_t *nc;
addrlen = sizeof(addr);
if ((cfd = accept(fd, &addr, &addrlen)) == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
smqLog(LOG_ERROR, "Unable accept client connection");
}
goto EXIT_FALG;
}
if (setNonblock(cfd) == -1) {
smqLog(LOG_ERROR, "Unable set file to nonblock mode");
close(cfd);
goto EXIT_FALG;
}
nc = clientAllocObject(cfd, RECV_STATE, AE_READABLE);
if (!nc) {
smqLog(LOG_ERROR, "Unable create new client connection");
close(cfd);
}
EXIT_FALG:
return;
}
#endif
void *acceptThreadFunction(void *arg) {
fd_set read_fd;
int sfd = server.fd, cfd;
int flags = 1;
socklen_t addrlen;
struct sockaddr addr;
smq_client_t *conn;
int retval;
FD_ZERO(&read_fd);
FD_SET(sfd, &read_fd);
while (1) {
retval = select(sfd + 1, &read_fd, NULL, NULL, NULL);
switch (retval) {
case -1:
FD_ZERO(&read_fd);
FD_SET(sfd, &read_fd);
perror("select()");
continue;
break;
case 0:
continue;
break;
}
if (FD_ISSET(sfd, &read_fd)) {
addrlen = sizeof(addr);
if ((cfd = accept(sfd, &addr, &addrlen)) == -1) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
smqLog(LOG_ERROR, "Unable accept client connection");
}
continue;
}
if (setNonblock(cfd) == -1) {
smqLog(LOG_ERROR, "Unable set file to nonblock mode");
close(cfd);
continue;
}
conn = clientAllocObject(cfd, RECV_STATE, AE_READABLE);
if (!conn) {
smqLog(LOG_ERROR, "Unable create new client connection");
close(cfd);
continue;
}
} else {
FD_ZERO(&read_fd);
FD_SET(sfd, &read_fd);
continue;
}
}
pthread_exit(NULL);
}
static char *skipSpace(char *string) {
int len;
while (*string == ' ' || *string == '\t')
string++;
len = strlen(string);
if (string[len - 2] == '\r')/* windows? */
string[len - 2] = '\0';
if (string[len - 1] == '\n')
string[len - 1] = '\0';
return string;
}
void loadConfigFile(const char *file) {
FILE *handle;
char buf[1024], *cursor;
char key[256], val[512];
struct config_t *item;
handle = fopen(file, "r");
if (NULL == handle) {
fprintf(stderr, "[Fatal] Unable open configure file.\n");
exit(-1);
}
while (fgets(buf, 1024, handle)) {
cursor = skipSpace(buf);
if (*cursor == '#')/* comments */
continue;
sscanf(cursor, "%[^ ]%*[ ]%512[^ #]", key, val);
item = (struct config_t *)malloc(sizeof(*item));
if (NULL == item) {
fprintf(stderr, "[Fatal] Not enough memory to alloc config entry.\n");
exit(-1);
}
item->key = strdup(key);
item->val = strdup(val);
item->next = config_item_head;
config_item_head = item;
}
fclose(handle);
}
void loadConfig() {
struct config_t *item = config_item_head, *temp;
if (NULL == item) {
fprintf(stderr, "[Fatal] Haven't load config file yet.\n");
exit(-1);
}
while (item) {
if (!strcasecmp(item->key, "listingport"))
server.listingPort = atoi(item->val);
else if (!strcasecmp(item->key, "memorylimitused"))
server.memoryLimitUsed = atoi(item->val);
else if (!strcasecmp(item->key, "secondstosavedisk"))
server.secondsToSaveDisk = atoi(item->val);
else if (!strcasecmp(item->key, "chagestosavedisk"))
server.chagesToSaveDisk = atoi(item->val);
else if (!strcasecmp(item->key, "clientexpiredtime"))
server.clientExpiredTime = atoi(item->val);
else if (!strcasecmp(item->key, "cronloops"))
server.cronLoops = atoi(item->val);
else if (!strcasecmp(item->key, "daemonize"))
server.daemonize = atoi(item->val);
else if (!strcasecmp(item->key, "enableauth"))
server.enableauth = atoi(item->val);
else if (!strcasecmp(item->key, "authpwd"))
server.authpwd = strdup(item->val);
else if (!strcasecmp(item->key, "luafilepath"))
server.luaFilePath = strdup(item->val);
else if (!strcasecmp(item->key, "luamainfunction"))
server.luaMainFunction = strdup(item->val);
else if (!strcasecmp(item->key, "pidfilepath"))
server.pidFilePath = strdup(item->val);
else
fprintf(stderr, "[Warning] Not found the config option (%s => %s)\n",
item->key, item->val);
temp = item->next;
free(item);
item = temp;
}
return;
}
void initServer()
{
struct linger ling = {0, 0};
struct sockaddr_in addr;
int flags = 1;
server.fd = socket(AF_INET, SOCK_STREAM, 0);
if (server.fd == -1) {
fprintf(stderr, "[Fatal] Unable create socket\n");
exit(-1);
}
if (setNonblock(server.fd) == -1) {
fprintf(stderr, "[Fatal] Unable set nonblock\n");
exit(-1);
}
setsockopt(server.fd, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags));
setsockopt(server.fd, SOL_SOCKET, SO_KEEPALIVE, &flags, sizeof(flags));
setsockopt(server.fd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));
#if !defined(TCP_NOPUSH)
setsockopt(server.fd, IPPROTO_TCP, TCP_NODELAY, &flags, sizeof(flags));
#endif
addr.sin_family = AF_INET;
addr.sin_port = htons(server.listingPort);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(server.fd, (struct sockaddr *) &addr, sizeof(addr)) == -1) {
fprintf(stderr, "[Fatal] Unable bind socket\n");
close(server.fd);
exit(-1);
}
if (listen(server.fd, 1024) == -1) {
fprintf(stderr, "[Fatal] Unable bind listen\n");
close(server.fd);
exit(-1);
}
server.eventLoop = aeCreateEventLoop();
if (!server.eventLoop) {
fprintf(stderr, "[Fatal] Unable alloc EventLoop.\n");
exit(-1);
}
server.queue = list_init((list_destroy_function_t)doItemDecrRefcount, 2048);
if (!server.queue) {
fprintf(stderr, "[Fatal] Unable alloc DoubleList.\n");
exit(-1);
}
server.clientListHead = NULL;
server.clientListTail = NULL;
server.clientCachesUsed = 0;
server.memoryUsedTotal = 0;
server.bgSaveChildpid = -1;
server.lastSaveTime = 0;
server.dirty = 0;
server.connections = 0;
/* Remove it: accept client connect */
/* aeCreateFileEvent(server.eventLoop, server.fd, AE_READABLE, acceptActionFunction, NULL); */
aeCreateTimeEvent(server.eventLoop, 1, serverCron, NULL, NULL);
return;
}
/* send $SUC when success, send #ERR when faild */
void doSendReply(smq_client_t *conn, char *str, int createEvent) {
int len;
len = strlen(str);
if (len + 2 > SEND_BUFF_SIZE) {
/* ought to be always enough. just fail for simplicity */
str = "#ERR: Output string too long";
len = strlen(str);
}
strcpy(conn->cSendBuffer, str);
strcat(conn->cSendBuffer, "\r\n");
conn->cSendBytes = len + 2;
conn->cSendWhere = 0;
do_connection_status(conn, SEND_STATE);
/* send the string to client */
if (createEvent)
aeCreateFileEvent(server.eventLoop, conn->fd, AE_WRITABLE, eventActionFunction, conn);
return;
}
smq_block_t *doItemAlloc(int size) {
smq_block_t *item;
int doAllocSize = sizeof(smq_block_t) + size;
item = slabs_alloc(doAllocSize);
if (item) {
item->refcount = 1;
item->blockSize = size;
server.memoryUsedTotal += size;
}
return item;
}
smq_block_t *doItemAllocString(const char *string) {
smq_block_t *item;
int size = strlen(string);
int doAllocSize = sizeof(smq_block_t) + size;
item = slabs_alloc(doAllocSize);
if (item) {
item->refcount = 1;
item->blockSize = size;
memcpy(item->block, string, size);
server.memoryUsedTotal += size;
}
return item;
}
int doItemIncrRefcount(smq_block_t *item) {
return item->refcount++;/* return last item refcount number */
}
int doItemDecrRefcount(void *item) {
if (item) {
smq_block_t *it = (smq_block_t *)item;
if (--it->refcount == 0) {
int doAllocSize = it->blockSize + sizeof(smq_block_t);
slabs_free(it, doAllocSize);
server.memoryUsedTotal -= it->blockSize;
}
return 0;
}
return -1;
}
/* make crlf item */
smq_block_t *makeNLObject() {
smq_block_t *it = doItemAlloc(2);
if (it) {
it->block[0] = '\r';
it->block[1] = '\n';
} else {
smqLog(LOG_ERROR, "Slabs not enough memory to alloc CRLF item");
return NULL;
}
return it;
}
int parseToken(const char *str, token_t *tokens, int *count) {
int begin = 0, end = 0;
int index = 0;
int tokenLen;
const char *sptr = str;
for (; *sptr; sptr++, end++) {
if (*sptr == ' ') {
tokenLen = end - begin;
if (tokenLen > TOKEN_MAX_LEN) {
fprintf(stderr, "[Fatal] Token too long.\n");
return -1;
}
memcpy(tokens[index++].token, str + begin, tokenLen);
begin = end + 1;
if (index == TOKEN_DEFAULT_SIZE) {
fprintf(stderr, "[Fatal] Tokens too must.\n");
*count = index;
return -1;
}
}
}
memcpy(tokens[index++].token, str + begin, end - begin); /* must copy the last token */
*count = index;
return 0;
}
command_cb_t lookupCommand(char *cmdname) {
command_cb_t cb;
int i = 0;
while (1) {
cb = callbacks[i];
if (!cb.cmdname || !strcasecmp(cb.cmdname, cmdname))
break;
i++;
}
return cb;
}
void tryProcessCommand(smq_client_t *conn) {
char *el, *cont;
token_t tokens[TOKEN_DEFAULT_SIZE];
int tokencount;
int where, retval;
int authCmd = 0;
command_cb_t cb;
if (conn->cRecvWhere <= 0)
return;
el = memchr(conn->cRecvBuffer, '\n', conn->cRecvWhere);
if (!el)
return;
cont = el + 1;
if (el - conn->cRecvBuffer > 1 && *(el - 1) == '\r')
el--;
*el = '\0';
memset(tokens, 0, sizeof(tokens));
if (parseToken(conn->cRecvBuffer, tokens, &tokencount) != 0) {
doSendReply(conn, "#ERR: Tokens too must", 1);
return;
}
/* Login check */
if (server.enableauth && !conn->isauth) {
if (!strcasecmp(tokens[0].token, "AUTH")) {
authCmd = 1;
} else {
do_connection_status(conn, CLOSE_STATE);/* close this connection */
return;
}
}
if (authCmd) {
if (tokencount != 2) {
doSendReply(conn, "#ERR: Command parameters wrong", 1);
return;
}
if (!strcmp(tokens[1].token, server.authpwd)) {
conn->isauth = 1;
doSendReply(conn, "+FIN: OK", 1);
return;
} else {
conn->isauth = 0;
doSendReply(conn, "#ERR: Password is incorrect", 1);
return;
}
}
cb = lookupCommand(tokens[0].token);
if (!cb.cb) {
doSendReply(conn, "#ERR: Not found this command in system", 1);
return;
}
if (tokencount != cb.argc) {
doSendReply(conn, "#ERR: Command parameters wrong", 1);
return;
}
cb.cb(conn, tokens, tokencount);
return;
}
/* drive machine: all event proccess in this function */
void machine(smq_client_t *conn) {
int exit = 0;
int flags = 1;
int retval;
while (!exit)
{
switch(conn->state)
{
case RECV_STATE: {
if (conn->cRecvWhere >= RECV_BUFF_SIZE) {/* command line too long? */
do_connection_status(conn, CLOSE_STATE);
fprintf(stderr, "[Fatal] Command line too long\n");
break;
}
retval = read(conn->fd, conn->cRecvBuffer + conn->cRecvWhere, RECV_BUFF_SIZE - conn->cRecvWhere);
if (retval == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
exit = 1;
break;
} else {
fprintf(stderr, "[Fatal] Failed to read, and not due to blocking\n");
do_connection_status(conn, CLOSE_STATE);
break;
}
} else if (retval == 0) {/* This client connection was closed */
do_connection_status(conn, CLOSE_STATE);
break;
}
conn->cRecvWhere += retval;
conn->lastTransportTime = time(NULL);
tryProcessCommand(conn);
break;
}
case NRECV_STATE: {
if (conn->cRecvBytes <= 0) {
conn->crlf_bytes = 0;
do_connection_status(conn, CRLF_STATE);
break;
}
retval = read(conn->fd, conn->mRecvBuffer + conn->cRecvWhere, conn->cRecvBytes);
if (retval == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
exit = 1;
break;
} else {
fprintf(stderr, "[Fatal] Failed to read, and not due to blocking\n");
do_connection_status(conn, CLOSE_STATE);
break;
}
} else if (retval == 0) {/* This client connection was closed */
do_connection_status(conn, CLOSE_STATE);
break;
}
conn->cRecvWhere += retval;
conn->cRecvBytes -= retval;
conn->lastTransportTime = time(NULL);
break;
}
case IGNORE_STATE: {
if (conn->cIgnoreBytes <= 0) {
conn->crlf_bytes = 0;
do_connection_status(conn, CRLF_STATE);
break;
}
retval = read(conn->fd, conn->cIgnoreBuffer,
(conn->cIgnoreBytes > IGNORE_BUFF_SIZE ? IGNORE_BUFF_SIZE : conn->cIgnoreBytes));
if (retval == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
exit = 1;
break;
} else {
fprintf(stderr, "[Fatal] Failed to read, and not due to blocking\n");
do_connection_status(conn, CLOSE_STATE);
break;
}
} else if (retval == 0) {
do_connection_status(conn, CLOSE_STATE);
break;
}
conn->cIgnoreBytes -= retval;
conn->lastTransportTime = time(NULL);
break;
}
case CRLF_STATE: {
char crlf_buf[2];
retval = read(conn->fd, crlf_buf, 2 - conn->crlf_bytes);
if (retval == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
exit = 1;
break;
} else {
fprintf(stderr, "[Fatal] Failed to read, and not due to blocking\n");
do_connection_status(conn, CLOSE_STATE);
break;
}
} else if (retval == 0) {/* This client connection was closed */
do_connection_status(conn, CLOSE_STATE);
break;
}
conn->crlf_bytes += retval;
conn->lastTransportTime = time(NULL);
if (conn->crlf_bytes >= 2) {
conn->crlf_bytes = 0;
doSendReply(conn, "+FIN: OK", 1);
break;
}
}
case SEND_STATE: {
if (conn->cSendBytes <= 0) {/* Each status would do it */
aeDeleteFileEvent(server.eventLoop, conn->fd, AE_WRITABLE);
do_connection_status(conn, RECV_STATE);/* back to recv state after send state */
do_connection_send_empty(conn);
do_connection_recv_empty(conn);
do_connection_nrecvbuf_empty(conn);
do_connection_nsendbuf_empty(conn);
break;
}
retval = write(conn->fd, conn->cSendBuffer + conn->cSendWhere, conn->cSendBytes - conn->cSendWhere);
if (retval == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
exit = 1;
break;
} else {
fprintf(stderr, "[Fatal] Failed to read, and not due to blocking\n");
do_connection_status(conn, CLOSE_STATE);
break;
}
} else if (retval == 0) {
do_connection_status(conn, CLOSE_STATE);
break;
}
conn->cSendWhere += retval;
conn->cSendBytes -= retval;
conn->lastTransportTime = time(NULL);
break;
}
case MSEND_STATE: {
void *item;
if (conn->cSendBytes > 0) {
retval = write(conn->fd, conn->mSendBuffer + conn->cSendWhere, conn->cSendBytes - conn->cSendWhere);
if (retval == -1) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
exit = 1;
break;
} else {
fprintf(stderr, "[Fatal] Failed to read, and not due to blocking\n");
do_connection_status(conn, CLOSE_STATE);
break;
}
} else if (retval == 0) {
do_connection_status(conn, CLOSE_STATE);
break;
}
conn->cSendWhere += retval;
conn->cSendBytes -= retval;
conn->lastTransportTime = time(NULL);
}
else
{
switch (conn->replyStage) {
case 1:/* Get item data */
item = list_fetch_head(conn->replyList);
conn->mSendBuffer = (char *)((smq_block_t *)item)->block;
conn->cSendBytes = ((smq_block_t *)item)->blockSize + 2;/* require "\r\n" */