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