]> git.saurik.com Git - redis.git/blame - src/redis-cli.c
Merge master with resolved conflict in src/redis-cli.c
[redis.git] / src / redis-cli.c
CommitLineData
ed9b544e 1/* Redis CLI (command line interface)
2 *
12d090d2 3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
ed9b544e 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
23d4709d 31#include "fmacros.h"
185cabda 32#include "version.h"
23d4709d 33
ed9b544e 34#include <stdio.h>
35#include <string.h>
36#include <stdlib.h>
37#include <unistd.h>
a88a2af6 38#include <ctype.h>
c0b3d423 39#include <errno.h>
b4b62c34 40#include <sys/stat.h>
ed9b544e 41
42#include "anet.h"
43#include "sds.h"
44#include "adlist.h"
45#include "zmalloc.h"
cf87ebf2 46#include "linenoise.h"
ed9b544e 47
48#define REDIS_CMD_INLINE 1
49#define REDIS_CMD_BULK 2
e17e0b05 50#define REDIS_CMD_MULTIBULK 4
ed9b544e 51
52#define REDIS_NOTUSED(V) ((void) V)
53
54static struct config {
55 char *hostip;
56 int hostport;
7e91f971 57 char *hostsocket;
5762b7f0 58 long repeat;
62e920df 59 int dbnum;
6cf5882c 60 int interactive;
36e5db6d 61 int shutdown;
249c3a7d 62 int monitor_mode;
63 int pubsub_mode;
f2dd4769 64 int raw_output; /* output mode per command */
123a10f7 65 int tty; /* flag for default output format */
bc63407b 66 int stdinarg; /* get last arg from stdin. (-x option) */
3a51bff0 67 char mb_sep;
288799e0 68 char *auth;
99628c1a 69 char *historyfile;
ed9b544e 70} config;
71
c937aa89 72static int cliReadReply(int fd);
a9158272 73static void usage();
c937aa89 74
c0b3d423 75/* Connect to the client. If force is not zero the connection is performed
76 * even if there is already a connected socket. */
77static int cliConnect(int force) {
ed9b544e 78 char err[ANET_ERR_LEN];
6fa24622 79 static int fd = ANET_ERR;
ed9b544e 80
c0b3d423 81 if (fd == ANET_ERR || force) {
82 if (force) close(fd);
7e91f971
PN
83 if (config.hostsocket == NULL) {
84 fd = anetTcpConnect(err,config.hostip,config.hostport);
85 } else {
86 fd = anetUnixConnect(err,config.hostsocket);
7e91f971 87 }
6fa24622 88 if (fd == ANET_ERR) {
7e91f971
PN
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);
6fa24622
DJMM
94 return -1;
95 }
96 anetTcpNoDelay(NULL,fd);
ed9b544e 97 }
ed9b544e 98 return fd;
99}
100
101static sds cliReadLine(int fd) {
102 sds line = sdsempty();
103
104 while(1) {
105 char c;
b91f03a4 106 ssize_t ret;
ed9b544e 107
b91f03a4 108 ret = read(fd,&c,1);
e0e1c195 109 if (ret <= 0) {
ed9b544e 110 sdsfree(line);
111 return NULL;
b91f03a4 112 } else if ((ret == 0) || (c == '\n')) {
ed9b544e 113 break;
114 } else {
115 line = sdscatlen(line,&c,1);
116 }
117 }
118 return sdstrim(line,"\r\n");
119}
120
62e920df 121static int cliReadSingleLineReply(int fd, int quiet) {
ed9b544e 122 sds reply = cliReadLine(fd);
123
124 if (reply == NULL) return 1;
62e920df 125 if (!quiet)
3a51bff0 126 printf("%s", reply);
621d5c19 127 sdsfree(reply);
ed9b544e 128 return 0;
129}
130
21cdc9f0 131static 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 }
07242c0c 153 printf("\"");
21cdc9f0 154}
155
c937aa89 156static int cliReadBulkReply(int fd) {
ed9b544e 157 sds replylen = cliReadLine(fd);
158 char *reply, crlf[2];
c937aa89 159 int bulklen;
ed9b544e 160
161 if (replylen == NULL) return 1;
ed9b544e 162 bulklen = atoi(replylen);
c937aa89 163 if (bulklen == -1) {
ed9b544e 164 sdsfree(replylen);
060f6be6 165 printf("(nil)\n");
ed9b544e 166 return 0;
167 }
ed9b544e 168 reply = zmalloc(bulklen);
169 anetRead(fd,reply,bulklen);
170 anetRead(fd,crlf,2);
123a10f7 171 if (config.raw_output || !config.tty) {
21cdc9f0 172 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
173 zfree(reply);
174 return 1;
175 }
21cdc9f0 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);
ed9b544e 180 }
ed9b544e 181 zfree(reply);
c937aa89 182 return 0;
ed9b544e 183}
184
185static int cliReadMultiBulkReply(int fd) {
186 sds replylen = cliReadLine(fd);
187 int elements, c = 1;
b37ca6ed 188 int retval = 0;
ed9b544e 189
190 if (replylen == NULL) return 1;
c937aa89 191 elements = atoi(replylen);
192 if (elements == -1) {
ed9b544e 193 sdsfree(replylen);
194 printf("(nil)\n");
195 return 0;
196 }
c937aa89 197 if (elements == 0) {
198 printf("(empty list or set)\n");
199 }
ed9b544e 200 while(elements--) {
3a51bff0 201 if (config.tty) printf("%d. ", c);
b37ca6ed 202 if (cliReadReply(fd)) retval = 1;
3a51bff0 203 if (elements) printf("%c",config.mb_sep);
ed9b544e 204 c++;
205 }
b37ca6ed 206 return retval;
ed9b544e 207}
208
c937aa89 209static int cliReadReply(int fd) {
210 char type;
c0b3d423 211 int nread;
c937aa89 212
c0b3d423 213 if ((nread = anetRead(fd,&type,1)) <= 0) {
36e5db6d 214 if (config.shutdown) return 0;
c0b3d423 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 }
36e5db6d 223 }
c937aa89 224 switch(type) {
225 case '-':
3a51bff0 226 if (config.tty) printf("(error) ");
62e920df 227 cliReadSingleLineReply(fd,0);
c937aa89 228 return 1;
229 case '+':
62e920df 230 return cliReadSingleLineReply(fd,0);
c937aa89 231 case ':':
3a51bff0 232 if (config.tty) printf("(integer) ");
62e920df 233 return cliReadSingleLineReply(fd,0);
c937aa89 234 case '$':
235 return cliReadBulkReply(fd);
236 case '*':
237 return cliReadMultiBulkReply(fd);
238 default:
ae77016e 239 printf("protocol error, got '%c' as reply type byte", type);
c937aa89 240 return 1;
241 }
242}
243
6cf5882c 244static int selectDb(int fd) {
62e920df 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) {
6cf5882c 259 return retval;
62e920df 260 }
261 return 0;
262}
263
8079656a 264static 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
aab055ae 280static int cliSendCommand(int argc, char **argv, int repeat) {
37dc9e5a 281 char *command = argv[0];
ed9b544e 282 int fd, j, retval = 0;
5762b7f0 283 sds cmd;
ed9b544e 284
37dc9e5a 285 config.raw_output = !strcasecmp(command,"info");
8079656a 286 if (!strcasecmp(command,"help")) {
287 showInteractiveHelp();
288 return 0;
289 }
37dc9e5a
PN
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;
c0b3d423 294 if ((fd = cliConnect(0)) == -1) return 1;
ed9b544e 295
62e920df 296 /* Select db number */
297 retval = selectDb(fd);
298 if (retval) {
299 fprintf(stderr,"Error setting DB num\n");
300 return 1;
301 }
6cf5882c 302
a2f4f871
PN
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
aab055ae 312 while(repeat--) {
5762b7f0 313 anetWrite(fd,cmd,sdslen(cmd));
249c3a7d 314 while (config.monitor_mode) {
e0e1c195 315 if (cliReadSingleLineReply(fd,0)) exit(1);
316 printf("\n");
621d5c19 317 }
318
249c3a7d 319 if (config.pubsub_mode) {
320 printf("Reading messages... (press Ctrl-c to quit)\n");
321 while (1) {
322 cliReadReply(fd);
3a51bff0 323 printf("\n\n");
249c3a7d 324 }
325 }
326
5762b7f0 327 retval = cliReadReply(fd);
ae77016e
PN
328 if (!config.raw_output && config.tty) printf("\n");
329 if (retval) return retval;
ed9b544e 330 }
ed9b544e 331 return 0;
332}
333
334static int parseOptions(int argc, char **argv) {
335 int i;
336
337 for (i = 1; i < argc; i++) {
338 int lastarg = i==argc-1;
6cf5882c 339
ed9b544e 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++;
a9158272 348 } else if (!strcmp(argv[i],"-h") && lastarg) {
349 usage();
bc63407b 350 } else if (!strcmp(argv[i],"-x")) {
351 config.stdinarg = 1;
ed9b544e 352 } else if (!strcmp(argv[i],"-p") && !lastarg) {
353 config.hostport = atoi(argv[i+1]);
354 i++;
7e91f971
PN
355 } else if (!strcmp(argv[i],"-s") && !lastarg) {
356 config.hostsocket = argv[i+1];
357 i++;
5762b7f0 358 } else if (!strcmp(argv[i],"-r") && !lastarg) {
359 config.repeat = strtoll(argv[i+1],NULL,10);
360 i++;
62e920df 361 } else if (!strcmp(argv[i],"-n") && !lastarg) {
362 config.dbnum = atoi(argv[i+1]);
363 i++;
fdfdae0f 364 } else if (!strcmp(argv[i],"-a") && !lastarg) {
288799e0 365 config.auth = argv[i+1];
fdfdae0f 366 i++;
6cf5882c 367 } else if (!strcmp(argv[i],"-i")) {
abb731e5
PN
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 );
37dc9e5a 372 } else if (!strcmp(argv[i],"-c")) {
b4b62c34
PN
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 );
185cabda 378 } else if (!strcmp(argv[i],"-v")) {
fdc0bde9 379 printf("redis-cli shipped with Redis version %s\n", REDIS_VERSION);
185cabda 380 exit(0);
ed9b544e 381 } else {
382 break;
383 }
384 }
385 return i;
386}
387
388static 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
a9158272 405static void usage() {
7e91f971 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");
bc63407b 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");
a9158272 409 fprintf(stderr, "example: redis-cli get my_passwd\n");
410 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
d239ec59 411 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
a9158272 412 exit(1);
413}
414
6cf5882c
MMDJ
415/* Turn the plain C strings into Sds strings */
416static char **convertToSds(int count, char** args) {
417 int j;
37dc9e5a 418 char **sds = zmalloc(sizeof(char*)*count);
6cf5882c
MMDJ
419
420 for(j = 0; j < count; j++)
421 sds[j] = sdsnew(args[j]);
422
423 return sds;
424}
425
a88a2af6 426#define LINE_BUFLEN 4096
6cf5882c 427static void repl() {
a88a2af6 428 int argc, j;
cbce5171 429 char *line;
430 sds *argv;
6cf5882c 431
5d15b520 432 config.interactive = 1;
bc86d88e 433 while((line = linenoise("redis> ")) != NULL) {
cf87ebf2 434 if (line[0] != '\0') {
cbce5171 435 argv = sdssplitargs(line,&argc);
a88a2af6 436 linenoiseHistoryAdd(line);
99628c1a 437 if (config.historyfile) linenoiseHistorySave(config.historyfile);
0439d792
PN
438 if (argv == NULL) {
439 printf("Invalid argument(s)\n");
440 continue;
441 } else if (argc > 0) {
a88a2af6 442 if (strcasecmp(argv[0],"quit") == 0 ||
443 strcasecmp(argv[0],"exit") == 0)
c0b3d423 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 }
a88a2af6 459 }
460 /* Free the argument vector */
461 for (j = 0; j < argc; j++)
462 sdsfree(argv[j]);
8ff6a48b 463 zfree(argv);
6cf5882c 464 }
a88a2af6 465 /* linenoise() returns malloc-ed lines like readline() */
cf87ebf2 466 free(line);
6cf5882c 467 }
6cf5882c
MMDJ
468 exit(0);
469}
470
b4b62c34
PN
471static int noninteractive(int argc, char **argv) {
472 int retval = 0;
bc63407b 473 if (config.stdinarg) {
b4b62c34
PN
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
ed9b544e 484int main(int argc, char **argv) {
6cf5882c 485 int firstarg;
ed9b544e 486
487 config.hostip = "127.0.0.1";
488 config.hostport = 6379;
7e91f971 489 config.hostsocket = NULL;
5762b7f0 490 config.repeat = 1;
62e920df 491 config.dbnum = 0;
6cf5882c 492 config.interactive = 0;
36e5db6d 493 config.shutdown = 0;
249c3a7d 494 config.monitor_mode = 0;
495 config.pubsub_mode = 0;
f40b035d 496 config.raw_output = 0;
bc63407b 497 config.stdinarg = 0;
288799e0 498 config.auth = NULL;
99628c1a 499 config.historyfile = NULL;
cf0c6b78 500 config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL);
3a51bff0 501 config.mb_sep = '\n';
99628c1a 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 }
ed9b544e 508
509 firstarg = parseOptions(argc,argv);
510 argc -= firstarg;
511 argv += firstarg;
ed9b544e 512
aab055ae
MMDJ
513 if (config.auth != NULL) {
514 char *authargv[2];
93b2a771 515 int dbnum = config.dbnum;
aab055ae 516
93b2a771 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;
aab055ae
MMDJ
521 authargv[0] = "AUTH";
522 authargv[1] = config.auth;
523 cliSendCommand(2, convertToSds(2, authargv), 1);
93b2a771 524 config.dbnum = dbnum; /* restore the right DB number */
aab055ae
MMDJ
525 }
526
abb731e5
PN
527 /* Start interactive mode when no command is provided */
528 if (argc == 0) repl();
b4b62c34
PN
529 /* Otherwise, we have some arguments to execute */
530 return noninteractive(argc,convertToSds(argc,argv));
ed9b544e 531}