]>
git.saurik.com Git - redis.git/blob - src/redis-cli.c
1 /* Redis CLI (command line interface)
3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
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.
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.
46 #include "linenoise.h"
48 #define REDIS_CMD_INLINE 1
49 #define REDIS_CMD_BULK 2
50 #define REDIS_CMD_MULTIBULK 4
52 #define REDIS_NOTUSED(V) ((void) V)
54 static struct config
{
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) */
72 static int cliReadReply(int fd
);
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
;
81 if (fd
== ANET_ERR
|| force
) {
83 if (config
.hostsocket
== NULL
) {
84 fd
= anetTcpConnect(err
,config
.hostip
,config
.hostport
);
86 fd
= anetUnixConnect(err
,config
.hostsocket
);
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
);
93 fprintf(stderr
,"%s: %s",config
.hostsocket
,err
);
96 anetTcpNoDelay(NULL
,fd
);
101 static sds
cliReadLine(int fd
) {
102 sds line
= sdsempty();
112 } else if ((ret
== 0) || (c
== '\n')) {
115 line
= sdscatlen(line
,&c
,1);
118 return sdstrim(line
,"\r\n");
121 static int cliReadSingleLineReply(int fd
, int quiet
) {
122 sds reply
= cliReadLine(fd
);
124 if (reply
== NULL
) return 1;
131 static void printStringRepr(char *s
, int len
) {
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;
148 printf("\\x%02x",(unsigned char)*s
);
156 static int cliReadBulkReply(int fd
) {
157 sds replylen
= cliReadLine(fd
);
158 char *reply
, crlf
[2];
161 if (replylen
== NULL
) return 1;
162 bulklen
= atoi(replylen
);
168 reply
= zmalloc(bulklen
);
169 anetRead(fd
,reply
,bulklen
);
171 if (config
.raw_output
|| !config
.tty
) {
172 if (bulklen
&& fwrite(reply
,bulklen
,1,stdout
) == 0) {
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
);
185 static int cliReadMultiBulkReply(int fd
) {
186 sds replylen
= cliReadLine(fd
);
190 if (replylen
== NULL
) return 1;
191 elements
= atoi(replylen
);
192 if (elements
== -1) {
198 printf("(empty list or set)\n");
201 if (config
.tty
) printf("%d. ", c
);
202 if (cliReadReply(fd
)) retval
= 1;
203 if (elements
) printf("%c",config
.mb_sep
);
209 static int cliReadReply(int fd
) {
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
)))
220 printf("I/O error while reading from socket: %s",strerror(errno
));
226 if (config
.tty
) printf("(error) ");
227 cliReadSingleLineReply(fd
,0);
230 return cliReadSingleLineReply(fd
,0);
232 if (config
.tty
) printf("(integer) ");
233 return cliReadSingleLineReply(fd
,0);
235 return cliReadBulkReply(fd
);
237 return cliReadMultiBulkReply(fd
);
239 printf("protocol error, got '%c' as reply type byte", type
);
244 static int selectDb(int fd
) {
249 if (config
.dbnum
== 0)
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);
264 static void showInteractiveHelp(void) {
267 "Welcome to redis-cli " REDIS_VERSION
"!\n"
268 "Just type any valid Redis command to see a pretty printed output.\n"
270 "It is possible to quote strings, like in:\n"
271 " set \"my key\" \"some string \\xff\\n\"\n"
273 "You can find a list of valid Redis commands at\n"
274 " http://code.google.com/p/redis/wiki/CommandReference\n"
276 "Note: redis-cli supports line editing, use up/down arrows for history."
280 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
281 char *command
= argv
[0];
282 int fd
, j
, retval
= 0;
285 config
.raw_output
= !strcasecmp(command
,"info");
286 if (!strcasecmp(command
,"help")) {
287 showInteractiveHelp();
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;
296 /* Select db number */
297 retval
= selectDb(fd
);
299 fprintf(stderr
,"Error setting DB num\n");
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);
313 anetWrite(fd
,cmd
,sdslen(cmd
));
314 while (config
.monitor_mode
) {
315 if (cliReadSingleLineReply(fd
,0)) exit(1);
319 if (config
.pubsub_mode
) {
320 printf("Reading messages... (press Ctrl-c to quit)\n");
327 retval
= cliReadReply(fd
);
328 if (!config
.raw_output
&& config
.tty
) printf("\n");
329 if (retval
) return retval
;
334 static int parseOptions(int argc
, char **argv
) {
337 for (i
= 1; i
< argc
; i
++) {
338 int lastarg
= i
==argc
-1;
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
]);
348 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
350 } else if (!strcmp(argv
[i
],"-x")) {
352 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
353 config
.hostport
= atoi(argv
[i
+1]);
355 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
356 config
.hostsocket
= argv
[i
+1];
358 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
359 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
361 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
362 config
.dbnum
= atoi(argv
[i
+1]);
364 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
365 config
.auth
= argv
[i
+1];
367 } else if (!strcmp(argv
[i
],"-i")) {
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"
372 } else if (!strcmp(argv
[i
],"-c")) {
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"
378 } else if (!strcmp(argv
[i
],"-v")) {
379 printf("redis-cli shipped with Redis version %s\n", REDIS_VERSION
);
388 static sds
readArgFromStdin(void) {
390 sds arg
= sdsempty();
393 int nread
= read(fileno(stdin
),buf
,1024);
395 if (nread
== 0) break;
396 else if (nread
== -1) {
397 perror("Reading from standard input");
400 arg
= sdscatlen(arg
,buf
,nread
);
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");
415 /* Turn the plain C strings into Sds strings */
416 static char **convertToSds(int count
, char** args
) {
418 char **sds
= zmalloc(sizeof(char*)*count
);
420 for(j
= 0; j
< count
; j
++)
421 sds
[j
] = sdsnew(args
[j
]);
426 #define LINE_BUFLEN 4096
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
);
439 printf("Invalid argument(s)\n");
441 } else if (argc
> 0) {
442 if (strcasecmp(argv
[0],"quit") == 0 ||
443 strcasecmp(argv
[0],"exit") == 0)
449 if ((err
= cliSendCommand(argc
, argv
, 1)) != 0) {
450 if (err
== ECONNRESET
) {
451 printf("Reconnecting... ");
453 if (cliConnect(1) == -1) exit(1);
455 cliSendCommand(argc
,argv
,1);
460 /* Free the argument vector */
461 for (j
= 0; j
< argc
; j
++)
465 /* linenoise() returns malloc-ed lines like readline() */
471 static int noninteractive(int argc
, char **argv
) {
473 if (config
.stdinarg
) {
474 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
475 argv
[argc
] = readArgFromStdin();
476 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
478 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
479 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
484 int main(int argc
, char **argv
) {
487 config
.hostip
= "127.0.0.1";
488 config
.hostport
= 6379;
489 config
.hostsocket
= NULL
;
492 config
.interactive
= 0;
494 config
.monitor_mode
= 0;
495 config
.pubsub_mode
= 0;
496 config
.raw_output
= 0;
499 config
.historyfile
= NULL
;
500 config
.tty
= isatty(fileno(stdout
)) || (getenv("FAKETTY") != NULL
);
501 config
.mb_sep
= '\n';
503 if (getenv("HOME") != NULL
) {
504 config
.historyfile
= malloc(256);
505 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
506 linenoiseHistoryLoad(config
.historyfile
);
509 firstarg
= parseOptions(argc
,argv
);
513 if (config
.auth
!= NULL
) {
515 int dbnum
= config
.dbnum
;
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. */
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 */
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
));