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