]> git.saurik.com Git - redis.git/blob - src/redis-cli.c
0fef8cd9773c91e77c2d707ffe671eee1cb0e5e2
[redis.git] / src / 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 #include "version.h"
33
34 #include <stdio.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <ctype.h>
39
40 #include "anet.h"
41 #include "sds.h"
42 #include "adlist.h"
43 #include "zmalloc.h"
44 #include "linenoise.h"
45
46 #define REDIS_CMD_INLINE 1
47 #define REDIS_CMD_BULK 2
48 #define REDIS_CMD_MULTIBULK 4
49
50 #define REDIS_NOTUSED(V) ((void) V)
51
52 static struct config {
53 char *hostip;
54 int hostport;
55 long repeat;
56 int dbnum;
57 int argn_from_stdin;
58 int interactive;
59 int shutdown;
60 int monitor_mode;
61 int pubsub_mode;
62 int raw_output; /* output mode per command */
63 int tty; /* flag for default output format */
64 char mb_sep;
65 char *auth;
66 char *historyfile;
67 } config;
68
69 static int cliReadReply(int fd);
70 static void usage();
71
72 static int cliConnect(void) {
73 char err[ANET_ERR_LEN];
74 static int fd = ANET_ERR;
75
76 if (fd == ANET_ERR) {
77 fd = anetTcpConnect(err,config.hostip,config.hostport);
78 if (fd == ANET_ERR) {
79 fprintf(stderr, "Could not connect to Redis at %s:%d: %s", config.hostip, config.hostport, err);
80 return -1;
81 }
82 anetTcpNoDelay(NULL,fd);
83 }
84 return fd;
85 }
86
87 static sds cliReadLine(int fd) {
88 sds line = sdsempty();
89
90 while(1) {
91 char c;
92 ssize_t ret;
93
94 ret = read(fd,&c,1);
95 if (ret == -1) {
96 sdsfree(line);
97 return NULL;
98 } else if ((ret == 0) || (c == '\n')) {
99 break;
100 } else {
101 line = sdscatlen(line,&c,1);
102 }
103 }
104 return sdstrim(line,"\r\n");
105 }
106
107 static int cliReadSingleLineReply(int fd, int quiet) {
108 sds reply = cliReadLine(fd);
109
110 if (reply == NULL) return 1;
111 if (!quiet)
112 printf("%s", reply);
113 sdsfree(reply);
114 return 0;
115 }
116
117 static void printStringRepr(char *s, int len) {
118 printf("\"");
119 while(len--) {
120 switch(*s) {
121 case '\\':
122 case '"':
123 printf("\\%c",*s);
124 break;
125 case '\n': printf("\\n"); break;
126 case '\r': printf("\\r"); break;
127 case '\t': printf("\\t"); break;
128 case '\a': printf("\\a"); break;
129 case '\b': printf("\\b"); break;
130 default:
131 if (isprint(*s))
132 printf("%c",*s);
133 else
134 printf("\\x%02x",(unsigned char)*s);
135 break;
136 }
137 s++;
138 }
139 printf("\"");
140 }
141
142 static int cliReadBulkReply(int fd) {
143 sds replylen = cliReadLine(fd);
144 char *reply, crlf[2];
145 int bulklen;
146
147 if (replylen == NULL) return 1;
148 bulklen = atoi(replylen);
149 if (bulklen == -1) {
150 sdsfree(replylen);
151 printf("(nil)\n");
152 return 0;
153 }
154 reply = zmalloc(bulklen);
155 anetRead(fd,reply,bulklen);
156 anetRead(fd,crlf,2);
157 if (config.raw_output || !config.tty) {
158 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
159 zfree(reply);
160 return 1;
161 }
162 } else {
163 /* If you are producing output for the standard output we want
164 * a more interesting output with quoted characters and so forth */
165 printStringRepr(reply,bulklen);
166 }
167 zfree(reply);
168 return 0;
169 }
170
171 static int cliReadMultiBulkReply(int fd) {
172 sds replylen = cliReadLine(fd);
173 int elements, c = 1;
174
175 if (replylen == NULL) return 1;
176 elements = atoi(replylen);
177 if (elements == -1) {
178 sdsfree(replylen);
179 printf("(nil)\n");
180 return 0;
181 }
182 if (elements == 0) {
183 printf("(empty list or set)\n");
184 }
185 while(elements--) {
186 if (config.tty) printf("%d. ", c);
187 if (cliReadReply(fd)) return 1;
188 if (elements) printf("%c",config.mb_sep);
189 c++;
190 }
191 return 0;
192 }
193
194 static int cliReadReply(int fd) {
195 char type;
196
197 if (anetRead(fd,&type,1) <= 0) {
198 if (config.shutdown) return 0;
199 exit(1);
200 }
201 switch(type) {
202 case '-':
203 if (config.tty) printf("(error) ");
204 cliReadSingleLineReply(fd,0);
205 return 1;
206 case '+':
207 return cliReadSingleLineReply(fd,0);
208 case ':':
209 if (config.tty) printf("(integer) ");
210 return cliReadSingleLineReply(fd,0);
211 case '$':
212 return cliReadBulkReply(fd);
213 case '*':
214 return cliReadMultiBulkReply(fd);
215 default:
216 printf("protocol error, got '%c' as reply type byte\n", type);
217 return 1;
218 }
219 }
220
221 static int selectDb(int fd) {
222 int retval;
223 sds cmd;
224 char type;
225
226 if (config.dbnum == 0)
227 return 0;
228
229 cmd = sdsempty();
230 cmd = sdscatprintf(cmd,"SELECT %d\r\n",config.dbnum);
231 anetWrite(fd,cmd,sdslen(cmd));
232 anetRead(fd,&type,1);
233 if (type <= 0 || type != '+') return 1;
234 retval = cliReadSingleLineReply(fd,1);
235 if (retval) {
236 return retval;
237 }
238 return 0;
239 }
240
241 static int cliSendCommand(int argc, char **argv, int repeat) {
242 char *command = argv[0];
243 int fd, j, retval = 0;
244 sds cmd;
245
246 config.raw_output = !strcasecmp(command,"info");
247 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
248 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
249 if (!strcasecmp(command,"subscribe") ||
250 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
251 if ((fd = cliConnect()) == -1) return 1;
252
253 /* Select db number */
254 retval = selectDb(fd);
255 if (retval) {
256 fprintf(stderr,"Error setting DB num\n");
257 return 1;
258 }
259
260 /* Build the command to send */
261 cmd = sdscatprintf(sdsempty(),"*%d\r\n",argc);
262 for (j = 0; j < argc; j++) {
263 cmd = sdscatprintf(cmd,"$%lu\r\n",
264 (unsigned long)sdslen(argv[j]));
265 cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));
266 cmd = sdscatlen(cmd,"\r\n",2);
267 }
268
269 while(repeat--) {
270 anetWrite(fd,cmd,sdslen(cmd));
271 while (config.monitor_mode) {
272 cliReadSingleLineReply(fd,0);
273 }
274
275 if (config.pubsub_mode) {
276 printf("Reading messages... (press Ctrl-c to quit)\n");
277 while (1) {
278 cliReadReply(fd);
279 printf("\n\n");
280 }
281 }
282
283 retval = cliReadReply(fd);
284 if (retval) {
285 return retval;
286 }
287 if (!config.raw_output && config.tty) {
288 printf("\n");
289 }
290 }
291 return 0;
292 }
293
294 static int parseOptions(int argc, char **argv) {
295 int i;
296
297 for (i = 1; i < argc; i++) {
298 int lastarg = i==argc-1;
299
300 if (!strcmp(argv[i],"-h") && !lastarg) {
301 char *ip = zmalloc(32);
302 if (anetResolve(NULL,argv[i+1],ip) == ANET_ERR) {
303 printf("Can't resolve %s\n", argv[i]);
304 exit(1);
305 }
306 config.hostip = ip;
307 i++;
308 } else if (!strcmp(argv[i],"-h") && lastarg) {
309 usage();
310 } else if (!strcmp(argv[i],"-p") && !lastarg) {
311 config.hostport = atoi(argv[i+1]);
312 i++;
313 } else if (!strcmp(argv[i],"-r") && !lastarg) {
314 config.repeat = strtoll(argv[i+1],NULL,10);
315 i++;
316 } else if (!strcmp(argv[i],"-n") && !lastarg) {
317 config.dbnum = atoi(argv[i+1]);
318 i++;
319 } else if (!strcmp(argv[i],"-a") && !lastarg) {
320 config.auth = argv[i+1];
321 i++;
322 } else if (!strcmp(argv[i],"-i")) {
323 config.interactive = 1;
324 } else if (!strcmp(argv[i],"-c")) {
325 config.argn_from_stdin = 1;
326 } else if (!strcmp(argv[i],"-v")) {
327 printf("redis-cli shipped with Redis verison %s\n", REDIS_VERSION);
328 exit(0);
329 } else {
330 break;
331 }
332 }
333 return i;
334 }
335
336 static sds readArgFromStdin(void) {
337 char buf[1024];
338 sds arg = sdsempty();
339
340 while(1) {
341 int nread = read(fileno(stdin),buf,1024);
342
343 if (nread == 0) break;
344 else if (nread == -1) {
345 perror("Reading from standard input");
346 exit(1);
347 }
348 arg = sdscatlen(arg,buf,nread);
349 }
350 return arg;
351 }
352
353 static void usage() {
354 fprintf(stderr, "usage: redis-cli [-iv] [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 arg3 ... argN\n");
355 fprintf(stderr, "usage: echo \"argN\" | redis-cli -c [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 ... arg(N-1)\n");
356 fprintf(stderr, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");
357 fprintf(stderr, "example: cat /etc/passwd | redis-cli set my_passwd\n");
358 fprintf(stderr, "example: redis-cli get my_passwd\n");
359 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
360 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
361 exit(1);
362 }
363
364 /* Turn the plain C strings into Sds strings */
365 static char **convertToSds(int count, char** args) {
366 int j;
367 char **sds = zmalloc(sizeof(char*)*count);
368
369 for(j = 0; j < count; j++)
370 sds[j] = sdsnew(args[j]);
371
372 return sds;
373 }
374
375 static char **splitArguments(char *line, int *argc) {
376 char *p = line;
377 char *current = NULL;
378 char **vector = NULL;
379
380 *argc = 0;
381 while(1) {
382 /* skip blanks */
383 while(*p && isspace(*p)) p++;
384 if (*p) {
385 /* get a token */
386 int inq=0; /* set to 1 if we are in "quotes" */
387 int done=0;
388
389 if (current == NULL) current = sdsempty();
390 while(!done) {
391 if (inq) {
392 if (*p == '\\' && *(p+1)) {
393 char c;
394
395 p++;
396 switch(*p) {
397 case 'n': c = '\n'; break;
398 case 'r': c = '\r'; break;
399 case 't': c = '\t'; break;
400 case 'b': c = '\b'; break;
401 case 'a': c = '\a'; break;
402 default: c = *p; break;
403 }
404 current = sdscatlen(current,&c,1);
405 } else if (*p == '"') {
406 /* closing quote must be followed by a space */
407 if (*(p+1) && !isspace(*(p+1))) goto err;
408 done=1;
409 } else if (!*p) {
410 /* unterminated quotes */
411 goto err;
412 } else {
413 current = sdscatlen(current,p,1);
414 }
415 } else {
416 switch(*p) {
417 case ' ':
418 case '\n':
419 case '\r':
420 case '\t':
421 case '\0':
422 done=1;
423 break;
424 case '"':
425 inq=1;
426 break;
427 default:
428 current = sdscatlen(current,p,1);
429 break;
430 }
431 }
432 if (*p) p++;
433 }
434 /* add the token to the vector */
435 vector = zrealloc(vector,((*argc)+1)*sizeof(char*));
436 vector[*argc] = current;
437 (*argc)++;
438 current = NULL;
439 } else {
440 return vector;
441 }
442 }
443
444 err:
445 while(*argc--)
446 sdsfree(vector[*argc]);
447 zfree(vector);
448 if (current) sdsfree(current);
449 return NULL;
450 }
451
452 #define LINE_BUFLEN 4096
453 static void repl() {
454 int argc, j;
455 char *line, **argv;
456
457 while((line = linenoise("redis> ")) != NULL) {
458 if (line[0] != '\0') {
459 argv = splitArguments(line,&argc);
460 linenoiseHistoryAdd(line);
461 if (config.historyfile) linenoiseHistorySave(config.historyfile);
462 if (argv == NULL) {
463 printf("Invalid argument(s)\n");
464 continue;
465 } else if (argc > 0) {
466 if (strcasecmp(argv[0],"quit") == 0 ||
467 strcasecmp(argv[0],"exit") == 0)
468 exit(0);
469 else
470 cliSendCommand(argc, argv, 1);
471 }
472 /* Free the argument vector */
473 for (j = 0; j < argc; j++)
474 sdsfree(argv[j]);
475 zfree(argv);
476 }
477 /* linenoise() returns malloc-ed lines like readline() */
478 free(line);
479 }
480 exit(0);
481 }
482
483 int main(int argc, char **argv) {
484 int firstarg;
485 char **argvcopy;
486
487 config.hostip = "127.0.0.1";
488 config.hostport = 6379;
489 config.repeat = 1;
490 config.dbnum = 0;
491 config.argn_from_stdin = 0;
492 config.shutdown = 0;
493 config.interactive = 0;
494 config.monitor_mode = 0;
495 config.pubsub_mode = 0;
496 config.raw_output = 0;
497 config.auth = NULL;
498 config.historyfile = NULL;
499 config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL);
500 config.mb_sep = '\n';
501
502 if (getenv("HOME") != NULL) {
503 config.historyfile = malloc(256);
504 snprintf(config.historyfile,256,"%s/.rediscli_history",getenv("HOME"));
505 linenoiseHistoryLoad(config.historyfile);
506 }
507
508 firstarg = parseOptions(argc,argv);
509 argc -= firstarg;
510 argv += firstarg;
511
512 if (config.auth != NULL) {
513 char *authargv[2];
514
515 authargv[0] = "AUTH";
516 authargv[1] = config.auth;
517 cliSendCommand(2, convertToSds(2, authargv), 1);
518 }
519
520 if (argc == 0 || config.interactive == 1) {
521 config.interactive = 1;
522 repl();
523 }
524
525 argvcopy = convertToSds(argc+1, argv);
526 if (config.argn_from_stdin) {
527 sds lastarg = readArgFromStdin();
528 argvcopy[argc] = lastarg;
529 argc++;
530 }
531 return cliSendCommand(argc, argvcopy, config.repeat);
532 }