]> git.saurik.com Git - redis.git/blame - src/redis-cli.c
Removed unused command flags
[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
ed9b544e 48#define REDIS_NOTUSED(V) ((void) V)
49
50static struct config {
51 char *hostip;
52 int hostport;
5762b7f0 53 long repeat;
62e920df 54 int dbnum;
5d15b520 55 int interactive;
36e5db6d 56 int shutdown;
249c3a7d 57 int monitor_mode;
58 int pubsub_mode;
f2dd4769 59 int raw_output; /* output mode per command */
123a10f7 60 int tty; /* flag for default output format */
bc63407b 61 int stdinarg; /* get last arg from stdin. (-x option) */
3a51bff0 62 char mb_sep;
288799e0 63 char *auth;
99628c1a 64 char *historyfile;
ed9b544e 65} config;
66
c937aa89 67static int cliReadReply(int fd);
a9158272 68static void usage();
c937aa89 69
c0b3d423 70/* Connect to the client. If force is not zero the connection is performed
71 * even if there is already a connected socket. */
72static int cliConnect(int force) {
ed9b544e 73 char err[ANET_ERR_LEN];
6fa24622 74 static int fd = ANET_ERR;
ed9b544e 75
c0b3d423 76 if (fd == ANET_ERR || force) {
77 if (force) close(fd);
6fa24622
DJMM
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);
ed9b544e 84 }
ed9b544e 85 return fd;
86}
87
88static sds cliReadLine(int fd) {
89 sds line = sdsempty();
90
91 while(1) {
92 char c;
b91f03a4 93 ssize_t ret;
ed9b544e 94
b91f03a4 95 ret = read(fd,&c,1);
e0e1c195 96 if (ret <= 0) {
ed9b544e 97 sdsfree(line);
98 return NULL;
b91f03a4 99 } else if ((ret == 0) || (c == '\n')) {
ed9b544e 100 break;
101 } else {
102 line = sdscatlen(line,&c,1);
103 }
104 }
105 return sdstrim(line,"\r\n");
106}
107
62e920df 108static int cliReadSingleLineReply(int fd, int quiet) {
ed9b544e 109 sds reply = cliReadLine(fd);
110
111 if (reply == NULL) return 1;
62e920df 112 if (!quiet)
3a51bff0 113 printf("%s", reply);
621d5c19 114 sdsfree(reply);
ed9b544e 115 return 0;
116}
117
21cdc9f0 118static 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 }
07242c0c 140 printf("\"");
21cdc9f0 141}
142
c937aa89 143static int cliReadBulkReply(int fd) {
ed9b544e 144 sds replylen = cliReadLine(fd);
145 char *reply, crlf[2];
c937aa89 146 int bulklen;
ed9b544e 147
148 if (replylen == NULL) return 1;
ed9b544e 149 bulklen = atoi(replylen);
c937aa89 150 if (bulklen == -1) {
ed9b544e 151 sdsfree(replylen);
060f6be6 152 printf("(nil)\n");
ed9b544e 153 return 0;
154 }
ed9b544e 155 reply = zmalloc(bulklen);
156 anetRead(fd,reply,bulklen);
157 anetRead(fd,crlf,2);
123a10f7 158 if (config.raw_output || !config.tty) {
21cdc9f0 159 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
160 zfree(reply);
161 return 1;
162 }
21cdc9f0 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);
ed9b544e 167 }
ed9b544e 168 zfree(reply);
c937aa89 169 return 0;
ed9b544e 170}
171
172static int cliReadMultiBulkReply(int fd) {
173 sds replylen = cliReadLine(fd);
174 int elements, c = 1;
b37ca6ed 175 int retval = 0;
ed9b544e 176
177 if (replylen == NULL) return 1;
c937aa89 178 elements = atoi(replylen);
179 if (elements == -1) {
ed9b544e 180 sdsfree(replylen);
181 printf("(nil)\n");
182 return 0;
183 }
c937aa89 184 if (elements == 0) {
185 printf("(empty list or set)\n");
186 }
ed9b544e 187 while(elements--) {
3a51bff0 188 if (config.tty) printf("%d. ", c);
b37ca6ed 189 if (cliReadReply(fd)) retval = 1;
3a51bff0 190 if (elements) printf("%c",config.mb_sep);
ed9b544e 191 c++;
192 }
b37ca6ed 193 return retval;
ed9b544e 194}
195
c937aa89 196static int cliReadReply(int fd) {
197 char type;
c0b3d423 198 int nread;
c937aa89 199
c0b3d423 200 if ((nread = anetRead(fd,&type,1)) <= 0) {
36e5db6d 201 if (config.shutdown) return 0;
c0b3d423 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 }
36e5db6d 210 }
c937aa89 211 switch(type) {
212 case '-':
3a51bff0 213 if (config.tty) printf("(error) ");
62e920df 214 cliReadSingleLineReply(fd,0);
c937aa89 215 return 1;
216 case '+':
62e920df 217 return cliReadSingleLineReply(fd,0);
c937aa89 218 case ':':
3a51bff0 219 if (config.tty) printf("(integer) ");
62e920df 220 return cliReadSingleLineReply(fd,0);
c937aa89 221 case '$':
222 return cliReadBulkReply(fd);
223 case '*':
224 return cliReadMultiBulkReply(fd);
225 default:
ae77016e 226 printf("protocol error, got '%c' as reply type byte", type);
c937aa89 227 return 1;
228 }
229}
230
6cf5882c 231static int selectDb(int fd) {
62e920df 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) {
6cf5882c 246 return retval;
62e920df 247 }
248 return 0;
249}
250
8079656a 251static 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
aab055ae 267static int cliSendCommand(int argc, char **argv, int repeat) {
37dc9e5a 268 char *command = argv[0];
ed9b544e 269 int fd, j, retval = 0;
5762b7f0 270 sds cmd;
ed9b544e 271
37dc9e5a 272 config.raw_output = !strcasecmp(command,"info");
8079656a 273 if (!strcasecmp(command,"help")) {
274 showInteractiveHelp();
275 return 0;
276 }
37dc9e5a
PN
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;
c0b3d423 281 if ((fd = cliConnect(0)) == -1) return 1;
ed9b544e 282
62e920df 283 /* Select db number */
284 retval = selectDb(fd);
285 if (retval) {
286 fprintf(stderr,"Error setting DB num\n");
287 return 1;
288 }
6cf5882c 289
a2f4f871
PN
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
aab055ae 299 while(repeat--) {
5762b7f0 300 anetWrite(fd,cmd,sdslen(cmd));
249c3a7d 301 while (config.monitor_mode) {
e0e1c195 302 if (cliReadSingleLineReply(fd,0)) exit(1);
303 printf("\n");
621d5c19 304 }
305
249c3a7d 306 if (config.pubsub_mode) {
307 printf("Reading messages... (press Ctrl-c to quit)\n");
308 while (1) {
309 cliReadReply(fd);
3a51bff0 310 printf("\n\n");
249c3a7d 311 }
312 }
313
5762b7f0 314 retval = cliReadReply(fd);
ae77016e
PN
315 if (!config.raw_output && config.tty) printf("\n");
316 if (retval) return retval;
ed9b544e 317 }
ed9b544e 318 return 0;
319}
320
321static int parseOptions(int argc, char **argv) {
322 int i;
323
324 for (i = 1; i < argc; i++) {
325 int lastarg = i==argc-1;
6cf5882c 326
ed9b544e 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++;
a9158272 335 } else if (!strcmp(argv[i],"-h") && lastarg) {
336 usage();
bc63407b 337 } else if (!strcmp(argv[i],"-x")) {
338 config.stdinarg = 1;
ed9b544e 339 } else if (!strcmp(argv[i],"-p") && !lastarg) {
340 config.hostport = atoi(argv[i+1]);
341 i++;
5762b7f0 342 } else if (!strcmp(argv[i],"-r") && !lastarg) {
343 config.repeat = strtoll(argv[i+1],NULL,10);
344 i++;
62e920df 345 } else if (!strcmp(argv[i],"-n") && !lastarg) {
346 config.dbnum = atoi(argv[i+1]);
347 i++;
fdfdae0f 348 } else if (!strcmp(argv[i],"-a") && !lastarg) {
288799e0 349 config.auth = argv[i+1];
fdfdae0f 350 i++;
6cf5882c 351 } else if (!strcmp(argv[i],"-i")) {
abb731e5
PN
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 );
37dc9e5a 356 } else if (!strcmp(argv[i],"-c")) {
b4b62c34
PN
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 );
185cabda 362 } else if (!strcmp(argv[i],"-v")) {
fdc0bde9 363 printf("redis-cli shipped with Redis version %s\n", REDIS_VERSION);
185cabda 364 exit(0);
ed9b544e 365 } else {
366 break;
367 }
368 }
369 return i;
370}
371
372static 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
a9158272 389static void usage() {
185cabda 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");
bc63407b 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");
a9158272 393 fprintf(stderr, "example: redis-cli get my_passwd\n");
394 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
d239ec59 395 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
a9158272 396 exit(1);
397}
398
6cf5882c
MMDJ
399/* Turn the plain C strings into Sds strings */
400static char **convertToSds(int count, char** args) {
401 int j;
37dc9e5a 402 char **sds = zmalloc(sizeof(char*)*count);
6cf5882c
MMDJ
403
404 for(j = 0; j < count; j++)
405 sds[j] = sdsnew(args[j]);
406
407 return sds;
408}
409
a88a2af6 410#define LINE_BUFLEN 4096
6cf5882c 411static void repl() {
a88a2af6 412 int argc, j;
cbce5171 413 char *line;
414 sds *argv;
6cf5882c 415
5d15b520 416 config.interactive = 1;
bc86d88e 417 while((line = linenoise("redis> ")) != NULL) {
cf87ebf2 418 if (line[0] != '\0') {
cbce5171 419 argv = sdssplitargs(line,&argc);
a88a2af6 420 linenoiseHistoryAdd(line);
99628c1a 421 if (config.historyfile) linenoiseHistorySave(config.historyfile);
0439d792
PN
422 if (argv == NULL) {
423 printf("Invalid argument(s)\n");
424 continue;
425 } else if (argc > 0) {
a88a2af6 426 if (strcasecmp(argv[0],"quit") == 0 ||
427 strcasecmp(argv[0],"exit") == 0)
c0b3d423 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 }
a88a2af6 443 }
444 /* Free the argument vector */
445 for (j = 0; j < argc; j++)
446 sdsfree(argv[j]);
8ff6a48b 447 zfree(argv);
6cf5882c 448 }
a88a2af6 449 /* linenoise() returns malloc-ed lines like readline() */
cf87ebf2 450 free(line);
6cf5882c 451 }
6cf5882c
MMDJ
452 exit(0);
453}
454
b4b62c34
PN
455static int noninteractive(int argc, char **argv) {
456 int retval = 0;
bc63407b 457 if (config.stdinarg) {
b4b62c34
PN
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
ed9b544e 468int main(int argc, char **argv) {
6cf5882c 469 int firstarg;
ed9b544e 470
471 config.hostip = "127.0.0.1";
472 config.hostport = 6379;
5762b7f0 473 config.repeat = 1;
62e920df 474 config.dbnum = 0;
5d15b520 475 config.interactive = 0;
36e5db6d 476 config.shutdown = 0;
249c3a7d 477 config.monitor_mode = 0;
478 config.pubsub_mode = 0;
f40b035d 479 config.raw_output = 0;
bc63407b 480 config.stdinarg = 0;
288799e0 481 config.auth = NULL;
99628c1a 482 config.historyfile = NULL;
cf0c6b78 483 config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL);
3a51bff0 484 config.mb_sep = '\n';
99628c1a 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 }
ed9b544e 491
492 firstarg = parseOptions(argc,argv);
493 argc -= firstarg;
494 argv += firstarg;
ed9b544e 495
aab055ae
MMDJ
496 if (config.auth != NULL) {
497 char *authargv[2];
93b2a771 498 int dbnum = config.dbnum;
aab055ae 499
93b2a771 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;
aab055ae
MMDJ
504 authargv[0] = "AUTH";
505 authargv[1] = config.auth;
506 cliSendCommand(2, convertToSds(2, authargv), 1);
93b2a771 507 config.dbnum = dbnum; /* restore the right DB number */
aab055ae
MMDJ
508 }
509
abb731e5
PN
510 /* Start interactive mode when no command is provided */
511 if (argc == 0) repl();
b4b62c34
PN
512 /* Otherwise, we have some arguments to execute */
513 return noninteractive(argc,convertToSds(argc,argv));
ed9b544e 514}