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