d6cb06a0fb49044b889ca8a2a28eb3605087d35a
[redis.git] / redis-cli.c
1 /* Redis CLI (command line interface)
2 *
3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * * Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * * Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * * Neither the name of Redis nor the names of its contributors may be used
15 * to endorse or promote products derived from this software without
16 * specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 * POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #include "fmacros.h"
32
33 #include <stdio.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <ctype.h>
38
39 #include "anet.h"
40 #include "sds.h"
41 #include "adlist.h"
42 #include "zmalloc.h"
43 #include "linenoise.h"
44
45 #define REDIS_CMD_INLINE 1
46 #define REDIS_CMD_BULK 2
47 #define REDIS_CMD_MULTIBULK 4
48
49 #define REDIS_NOTUSED(V) ((void) V)
50
51 static struct config {
52 char *hostip;
53 int hostport;
54 long repeat;
55 int dbnum;
56 int interactive;
57 char *auth;
58 } config;
59
60 struct redisCommand {
61 char *name;
62 int arity;
63 int flags;
64 };
65
66 static struct redisCommand cmdTable[] = {
67 {"auth",2,REDIS_CMD_INLINE},
68 {"get",2,REDIS_CMD_INLINE},
69 {"set",3,REDIS_CMD_BULK},
70 {"setnx",3,REDIS_CMD_BULK},
71 {"setex",4,REDIS_CMD_BULK},
72 {"append",3,REDIS_CMD_BULK},
73 {"substr",4,REDIS_CMD_INLINE},
74 {"del",-2,REDIS_CMD_INLINE},
75 {"exists",2,REDIS_CMD_INLINE},
76 {"incr",2,REDIS_CMD_INLINE},
77 {"decr",2,REDIS_CMD_INLINE},
78 {"rpush",3,REDIS_CMD_BULK},
79 {"lpush",3,REDIS_CMD_BULK},
80 {"rpop",2,REDIS_CMD_INLINE},
81 {"lpop",2,REDIS_CMD_INLINE},
82 {"brpop",-3,REDIS_CMD_INLINE},
83 {"blpop",-3,REDIS_CMD_INLINE},
84 {"llen",2,REDIS_CMD_INLINE},
85 {"lindex",3,REDIS_CMD_INLINE},
86 {"lset",4,REDIS_CMD_BULK},
87 {"lrange",4,REDIS_CMD_INLINE},
88 {"ltrim",4,REDIS_CMD_INLINE},
89 {"lrem",4,REDIS_CMD_BULK},
90 {"rpoplpush",3,REDIS_CMD_BULK},
91 {"sadd",3,REDIS_CMD_BULK},
92 {"srem",3,REDIS_CMD_BULK},
93 {"smove",4,REDIS_CMD_BULK},
94 {"sismember",3,REDIS_CMD_BULK},
95 {"scard",2,REDIS_CMD_INLINE},
96 {"spop",2,REDIS_CMD_INLINE},
97 {"srandmember",2,REDIS_CMD_INLINE},
98 {"sinter",-2,REDIS_CMD_INLINE},
99 {"sinterstore",-3,REDIS_CMD_INLINE},
100 {"sunion",-2,REDIS_CMD_INLINE},
101 {"sunionstore",-3,REDIS_CMD_INLINE},
102 {"sdiff",-2,REDIS_CMD_INLINE},
103 {"sdiffstore",-3,REDIS_CMD_INLINE},
104 {"smembers",2,REDIS_CMD_INLINE},
105 {"zadd",4,REDIS_CMD_BULK},
106 {"zincrby",4,REDIS_CMD_BULK},
107 {"zrem",3,REDIS_CMD_BULK},
108 {"zremrangebyscore",4,REDIS_CMD_INLINE},
109 {"zmerge",-3,REDIS_CMD_INLINE},
110 {"zmergeweighed",-4,REDIS_CMD_INLINE},
111 {"zrange",-4,REDIS_CMD_INLINE},
112 {"zrank",3,REDIS_CMD_BULK},
113 {"zrevrank",3,REDIS_CMD_BULK},
114 {"zrangebyscore",-4,REDIS_CMD_INLINE},
115 {"zcount",4,REDIS_CMD_INLINE},
116 {"zrevrange",-4,REDIS_CMD_INLINE},
117 {"zcard",2,REDIS_CMD_INLINE},
118 {"zscore",3,REDIS_CMD_BULK},
119 {"incrby",3,REDIS_CMD_INLINE},
120 {"decrby",3,REDIS_CMD_INLINE},
121 {"getset",3,REDIS_CMD_BULK},
122 {"randomkey",1,REDIS_CMD_INLINE},
123 {"select",2,REDIS_CMD_INLINE},
124 {"move",3,REDIS_CMD_INLINE},
125 {"rename",3,REDIS_CMD_INLINE},
126 {"renamenx",3,REDIS_CMD_INLINE},
127 {"keys",2,REDIS_CMD_INLINE},
128 {"dbsize",1,REDIS_CMD_INLINE},
129 {"ping",1,REDIS_CMD_INLINE},
130 {"echo",2,REDIS_CMD_BULK},
131 {"save",1,REDIS_CMD_INLINE},
132 {"bgsave",1,REDIS_CMD_INLINE},
133 {"rewriteaof",1,REDIS_CMD_INLINE},
134 {"bgrewriteaof",1,REDIS_CMD_INLINE},
135 {"shutdown",1,REDIS_CMD_INLINE},
136 {"lastsave",1,REDIS_CMD_INLINE},
137 {"type",2,REDIS_CMD_INLINE},
138 {"flushdb",1,REDIS_CMD_INLINE},
139 {"flushall",1,REDIS_CMD_INLINE},
140 {"sort",-2,REDIS_CMD_INLINE},
141 {"info",1,REDIS_CMD_INLINE},
142 {"mget",-2,REDIS_CMD_INLINE},
143 {"expire",3,REDIS_CMD_INLINE},
144 {"expireat",3,REDIS_CMD_INLINE},
145 {"ttl",2,REDIS_CMD_INLINE},
146 {"slaveof",3,REDIS_CMD_INLINE},
147 {"debug",-2,REDIS_CMD_INLINE},
148 {"mset",-3,REDIS_CMD_MULTIBULK},
149 {"msetnx",-3,REDIS_CMD_MULTIBULK},
150 {"monitor",1,REDIS_CMD_INLINE},
151 {"multi",1,REDIS_CMD_INLINE},
152 {"exec",1,REDIS_CMD_INLINE},
153 {"discard",1,REDIS_CMD_INLINE},
154 {"hset",4,REDIS_CMD_MULTIBULK},
155 {"hget",3,REDIS_CMD_BULK},
156 {"hmset",-4,REDIS_CMD_MULTIBULK},
157 {"hmget",-3,REDIS_CMD_MULTIBULK},
158 {"hincrby",4,REDIS_CMD_INLINE},
159 {"hdel",3,REDIS_CMD_BULK},
160 {"hlen",2,REDIS_CMD_INLINE},
161 {"hkeys",2,REDIS_CMD_INLINE},
162 {"hvals",2,REDIS_CMD_INLINE},
163 {"hgetall",2,REDIS_CMD_INLINE},
164 {"hexists",3,REDIS_CMD_BULK},
165 {"config",-2,REDIS_CMD_BULK},
166 {"subscribe",-2,REDIS_CMD_INLINE},
167 {"unsubscribe",-1,REDIS_CMD_INLINE},
168 {"publish",3,REDIS_CMD_BULK},
169 {NULL,0,0}
170 };
171
172 static int cliReadReply(int fd);
173 static void usage();
174
175 static struct redisCommand *lookupCommand(char *name) {
176 int j = 0;
177 while(cmdTable[j].name != NULL) {
178 if (!strcasecmp(name,cmdTable[j].name)) return &cmdTable[j];
179 j++;
180 }
181 return NULL;
182 }
183
184 static int cliConnect(void) {
185 char err[ANET_ERR_LEN];
186 static int fd = ANET_ERR;
187
188 if (fd == ANET_ERR) {
189 fd = anetTcpConnect(err,config.hostip,config.hostport);
190 if (fd == ANET_ERR) {
191 fprintf(stderr, "Could not connect to Redis at %s:%d: %s", config.hostip, config.hostport, err);
192 return -1;
193 }
194 anetTcpNoDelay(NULL,fd);
195 }
196 return fd;
197 }
198
199 static sds cliReadLine(int fd) {
200 sds line = sdsempty();
201
202 while(1) {
203 char c;
204 ssize_t ret;
205
206 ret = read(fd,&c,1);
207 if (ret == -1) {
208 sdsfree(line);
209 return NULL;
210 } else if ((ret == 0) || (c == '\n')) {
211 break;
212 } else {
213 line = sdscatlen(line,&c,1);
214 }
215 }
216 return sdstrim(line,"\r\n");
217 }
218
219 static int cliReadSingleLineReply(int fd, int quiet) {
220 sds reply = cliReadLine(fd);
221
222 if (reply == NULL) return 1;
223 if (!quiet)
224 printf("%s\n", reply);
225 sdsfree(reply);
226 return 0;
227 }
228
229 static void printStringRepr(char *s, int len) {
230 printf("\"");
231 while(len--) {
232 switch(*s) {
233 case '\\':
234 case '"':
235 printf("\\%c",*s);
236 break;
237 case '\n': printf("\\n"); break;
238 case '\r': printf("\\r"); break;
239 case '\t': printf("\\t"); break;
240 case '\a': printf("\\a"); break;
241 case '\b': printf("\\b"); break;
242 default:
243 if (isprint(*s))
244 printf("%c",*s);
245 else
246 printf("\\x%02x",(unsigned char)*s);
247 break;
248 }
249 s++;
250 }
251 printf("\"\n");
252 }
253
254 static int cliReadBulkReply(int fd) {
255 sds replylen = cliReadLine(fd);
256 char *reply, crlf[2];
257 int bulklen;
258
259 if (replylen == NULL) return 1;
260 bulklen = atoi(replylen);
261 if (bulklen == -1) {
262 sdsfree(replylen);
263 printf("(nil)\n");
264 return 0;
265 }
266 reply = zmalloc(bulklen);
267 anetRead(fd,reply,bulklen);
268 anetRead(fd,crlf,2);
269 if (!isatty(fileno(stdout))) {
270 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
271 zfree(reply);
272 return 1;
273 }
274 } else {
275 /* If you are producing output for the standard output we want
276 * a more interesting output with quoted characters and so forth */
277 printStringRepr(reply,bulklen);
278 }
279 zfree(reply);
280 return 0;
281 }
282
283 static int cliReadMultiBulkReply(int fd) {
284 sds replylen = cliReadLine(fd);
285 int elements, c = 1;
286
287 if (replylen == NULL) return 1;
288 elements = atoi(replylen);
289 if (elements == -1) {
290 sdsfree(replylen);
291 printf("(nil)\n");
292 return 0;
293 }
294 if (elements == 0) {
295 printf("(empty list or set)\n");
296 }
297 while(elements--) {
298 printf("%d. ", c);
299 if (cliReadReply(fd)) return 1;
300 c++;
301 }
302 return 0;
303 }
304
305 static int cliReadReply(int fd) {
306 char type;
307
308 if (anetRead(fd,&type,1) <= 0) exit(1);
309 switch(type) {
310 case '-':
311 printf("(error) ");
312 cliReadSingleLineReply(fd,0);
313 return 1;
314 case '+':
315 return cliReadSingleLineReply(fd,0);
316 case ':':
317 printf("(integer) ");
318 return cliReadSingleLineReply(fd,0);
319 case '$':
320 return cliReadBulkReply(fd);
321 case '*':
322 return cliReadMultiBulkReply(fd);
323 default:
324 printf("protocol error, got '%c' as reply type byte\n", type);
325 return 1;
326 }
327 }
328
329 static int selectDb(int fd) {
330 int retval;
331 sds cmd;
332 char type;
333
334 if (config.dbnum == 0)
335 return 0;
336
337 cmd = sdsempty();
338 cmd = sdscatprintf(cmd,"SELECT %d\r\n",config.dbnum);
339 anetWrite(fd,cmd,sdslen(cmd));
340 anetRead(fd,&type,1);
341 if (type <= 0 || type != '+') return 1;
342 retval = cliReadSingleLineReply(fd,1);
343 if (retval) {
344 return retval;
345 }
346 return 0;
347 }
348
349 static int cliSendCommand(int argc, char **argv, int repeat) {
350 struct redisCommand *rc = lookupCommand(argv[0]);
351 int fd, j, retval = 0;
352 int read_forever = 0;
353 sds cmd;
354
355 if (!rc) {
356 fprintf(stderr,"Unknown command '%s'\n",argv[0]);
357 return 1;
358 }
359
360 if ((rc->arity > 0 && argc != rc->arity) ||
361 (rc->arity < 0 && argc < -rc->arity)) {
362 fprintf(stderr,"Wrong number of arguments for '%s'\n",rc->name);
363 return 1;
364 }
365 if (!strcasecmp(rc->name,"monitor")) read_forever = 1;
366 if ((fd = cliConnect()) == -1) return 1;
367
368 /* Select db number */
369 retval = selectDb(fd);
370 if (retval) {
371 fprintf(stderr,"Error setting DB num\n");
372 return 1;
373 }
374
375 while(repeat--) {
376 /* Build the command to send */
377 cmd = sdsempty();
378 if (rc->flags & REDIS_CMD_MULTIBULK) {
379 cmd = sdscatprintf(cmd,"*%d\r\n",argc);
380 for (j = 0; j < argc; j++) {
381 cmd = sdscatprintf(cmd,"$%lu\r\n",
382 (unsigned long)sdslen(argv[j]));
383 cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));
384 cmd = sdscatlen(cmd,"\r\n",2);
385 }
386 } else {
387 for (j = 0; j < argc; j++) {
388 if (j != 0) cmd = sdscat(cmd," ");
389 if (j == argc-1 && rc->flags & REDIS_CMD_BULK) {
390 cmd = sdscatprintf(cmd,"%lu",
391 (unsigned long)sdslen(argv[j]));
392 } else {
393 cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));
394 }
395 }
396 cmd = sdscat(cmd,"\r\n");
397 if (rc->flags & REDIS_CMD_BULK) {
398 cmd = sdscatlen(cmd,argv[argc-1],sdslen(argv[argc-1]));
399 cmd = sdscatlen(cmd,"\r\n",2);
400 }
401 }
402 anetWrite(fd,cmd,sdslen(cmd));
403 sdsfree(cmd);
404
405 while (read_forever) {
406 cliReadSingleLineReply(fd,0);
407 }
408
409 retval = cliReadReply(fd);
410 if (retval) {
411 return retval;
412 }
413 }
414 return 0;
415 }
416
417 static int parseOptions(int argc, char **argv) {
418 int i;
419
420 for (i = 1; i < argc; i++) {
421 int lastarg = i==argc-1;
422
423 if (!strcmp(argv[i],"-h") && !lastarg) {
424 char *ip = zmalloc(32);
425 if (anetResolve(NULL,argv[i+1],ip) == ANET_ERR) {
426 printf("Can't resolve %s\n", argv[i]);
427 exit(1);
428 }
429 config.hostip = ip;
430 i++;
431 } else if (!strcmp(argv[i],"-h") && lastarg) {
432 usage();
433 } else if (!strcmp(argv[i],"-p") && !lastarg) {
434 config.hostport = atoi(argv[i+1]);
435 i++;
436 } else if (!strcmp(argv[i],"-r") && !lastarg) {
437 config.repeat = strtoll(argv[i+1],NULL,10);
438 i++;
439 } else if (!strcmp(argv[i],"-n") && !lastarg) {
440 config.dbnum = atoi(argv[i+1]);
441 i++;
442 } else if (!strcmp(argv[i],"-a") && !lastarg) {
443 config.auth = argv[i+1];
444 i++;
445 } else if (!strcmp(argv[i],"-i")) {
446 config.interactive = 1;
447 } else {
448 break;
449 }
450 }
451 return i;
452 }
453
454 static sds readArgFromStdin(void) {
455 char buf[1024];
456 sds arg = sdsempty();
457
458 while(1) {
459 int nread = read(fileno(stdin),buf,1024);
460
461 if (nread == 0) break;
462 else if (nread == -1) {
463 perror("Reading from standard input");
464 exit(1);
465 }
466 arg = sdscatlen(arg,buf,nread);
467 }
468 return arg;
469 }
470
471 static void usage() {
472 fprintf(stderr, "usage: redis-cli [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] [-i] cmd arg1 arg2 arg3 ... argN\n");
473 fprintf(stderr, "usage: echo \"argN\" | redis-cli [-h host] [-a authpw] [-p port] [-r repeat_times] [-n db_num] cmd arg1 arg2 ... arg(N-1)\n");
474 fprintf(stderr, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");
475 fprintf(stderr, "example: cat /etc/passwd | redis-cli set my_passwd\n");
476 fprintf(stderr, "example: redis-cli get my_passwd\n");
477 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
478 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
479 exit(1);
480 }
481
482 /* Turn the plain C strings into Sds strings */
483 static char **convertToSds(int count, char** args) {
484 int j;
485 char **sds = zmalloc(sizeof(char*)*count+1);
486
487 for(j = 0; j < count; j++)
488 sds[j] = sdsnew(args[j]);
489
490 return sds;
491 }
492
493 static char **splitArguments(char *line, int *argc) {
494 char *p = line;
495 char *current = NULL;
496 char **vector = NULL;
497
498 *argc = 0;
499 while(1) {
500 /* skip blanks */
501 while(*p && isspace(*p)) p++;
502 if (*p) {
503 /* get a token */
504 int inq=0; /* set to 1 if we are in "quotes" */
505 int done = 0;
506
507 if (current == NULL) current = sdsempty();
508 while(!done) {
509 if (inq) {
510 if (*p == '\\' && *(p+1)) {
511 char c;
512
513 p++;
514 switch(*p) {
515 case 'n': c = '\n'; break;
516 case 'r': c = '\r'; break;
517 case 't': c = '\t'; break;
518 case 'b': c = '\b'; break;
519 case 'a': c = '\a'; break;
520 default: c = *p; break;
521 }
522 current = sdscatlen(current,&c,1);
523 } else if (*p == '"') {
524 done = 1;
525 } else {
526 current = sdscatlen(current,p,1);
527 }
528 } else {
529 switch(*p) {
530 case ' ':
531 case '\n':
532 case '\r':
533 case '\t':
534 case '\0':
535 done=1;
536 break;
537 case '"':
538 inq=1;
539 break;
540 default:
541 current = sdscatlen(current,p,1);
542 break;
543 }
544 }
545 if (*p) p++;
546 }
547 /* add the token to the vector */
548 vector = zrealloc(vector,((*argc)+1)*sizeof(char*));
549 vector[*argc] = current;
550 (*argc)++;
551 current = NULL;
552 } else {
553 return vector;
554 }
555 }
556 }
557
558 #define LINE_BUFLEN 4096
559 static void repl() {
560 int argc, j;
561 char *line, **argv;
562
563 while((line = linenoise("redis> ")) != NULL) {
564 if (line[0] != '\0') {
565 argv = splitArguments(line,&argc);
566 linenoiseHistoryAdd(line);
567 if (argc > 0) {
568 if (strcasecmp(argv[0],"quit") == 0 ||
569 strcasecmp(argv[0],"exit") == 0)
570 exit(0);
571 else
572 cliSendCommand(argc, argv, 1);
573 }
574 /* Free the argument vector */
575 for (j = 0; j < argc; j++)
576 sdsfree(argv[j]);
577 free(argv);
578 }
579 /* linenoise() returns malloc-ed lines like readline() */
580 free(line);
581 }
582 exit(0);
583 }
584
585 int main(int argc, char **argv) {
586 int firstarg;
587 char **argvcopy;
588 struct redisCommand *rc;
589
590 config.hostip = "127.0.0.1";
591 config.hostport = 6379;
592 config.repeat = 1;
593 config.dbnum = 0;
594 config.interactive = 0;
595 config.auth = NULL;
596
597 firstarg = parseOptions(argc,argv);
598 argc -= firstarg;
599 argv += firstarg;
600
601 if (config.auth != NULL) {
602 char *authargv[2];
603
604 authargv[0] = "AUTH";
605 authargv[1] = config.auth;
606 cliSendCommand(2, convertToSds(2, authargv), 1);
607 }
608
609 if (argc == 0 || config.interactive == 1) repl();
610
611 argvcopy = convertToSds(argc, argv);
612
613 /* Read the last argument from stdandard input if needed */
614 if ((rc = lookupCommand(argv[0])) != NULL) {
615 if (rc->arity > 0 && argc == rc->arity-1) {
616 sds lastarg = readArgFromStdin();
617 argvcopy[argc] = lastarg;
618 argc++;
619 }
620 }
621
622 return cliSendCommand(argc, argvcopy, config.repeat);
623 }