]>
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.
47 #include "linenoise.h"
49 #define REDIS_NOTUSED(V) ((void) V)
51 static struct config
{
61 int raw_output
; /* output mode per command */
62 int tty
; /* flag for default output format */
63 int stdinarg
; /* get last arg from stdin. (-x option) */
69 static int cliReadReply(int fd
);
72 /*------------------------------------------------------------------------------
74 *--------------------------------------------------------------------------- */
76 static long long mstime(void) {
80 gettimeofday(&tv
, NULL
);
81 mst
= ((long)tv
.tv_sec
)*1000;
82 mst
+= tv
.tv_usec
/1000;
86 static void printStringRepr(char *s
, int len
) {
94 case '\n': printf("\\n"); break;
95 case '\r': printf("\\r"); break;
96 case '\t': printf("\\t"); break;
97 case '\a': printf("\\a"); break;
98 case '\b': printf("\\b"); break;
103 printf("\\x%02x",(unsigned char)*s
);
111 /*------------------------------------------------------------------------------
112 * Networking / parsing
113 *--------------------------------------------------------------------------- */
115 /* Connect to the client. If force is not zero the connection is performed
116 * even if there is already a connected socket. */
117 static int cliConnect(int force
) {
118 char err
[ANET_ERR_LEN
];
119 static int fd
= ANET_ERR
;
121 if (fd
== ANET_ERR
|| force
) {
122 if (force
) close(fd
);
123 if (config
.hostsocket
== NULL
) {
124 fd
= anetTcpConnect(err
,config
.hostip
,config
.hostport
);
126 fd
= anetUnixConnect(err
,config
.hostsocket
);
128 if (fd
== ANET_ERR
) {
129 fprintf(stderr
,"Could not connect to Redis at ");
130 if (config
.hostsocket
== NULL
)
131 fprintf(stderr
,"%s:%d: %s",config
.hostip
,config
.hostport
,err
);
133 fprintf(stderr
,"%s: %s",config
.hostsocket
,err
);
136 anetTcpNoDelay(NULL
,fd
);
141 static sds
cliReadLine(int fd
) {
142 sds line
= sdsempty();
152 } else if ((ret
== 0) || (c
== '\n')) {
155 line
= sdscatlen(line
,&c
,1);
158 return sdstrim(line
,"\r\n");
161 static int cliReadSingleLineReply(int fd
, int quiet
) {
162 sds reply
= cliReadLine(fd
);
164 if (reply
== NULL
) return 1;
171 static int cliReadBulkReply(int fd
) {
172 sds replylen
= cliReadLine(fd
);
173 char *reply
, crlf
[2];
176 if (replylen
== NULL
) return 1;
177 bulklen
= atoi(replylen
);
183 reply
= zmalloc(bulklen
);
184 anetRead(fd
,reply
,bulklen
);
186 if (config
.raw_output
|| !config
.tty
) {
187 if (bulklen
&& fwrite(reply
,bulklen
,1,stdout
) == 0) {
192 /* If you are producing output for the standard output we want
193 * a more interesting output with quoted characters and so forth */
194 printStringRepr(reply
,bulklen
);
200 static int cliReadMultiBulkReply(int fd
) {
201 sds replylen
= cliReadLine(fd
);
205 if (replylen
== NULL
) return 1;
206 elements
= atoi(replylen
);
207 if (elements
== -1) {
213 printf("(empty list or set)\n");
216 if (config
.tty
) printf("%d. ", c
);
217 if (cliReadReply(fd
)) retval
= 1;
218 if (elements
) printf("%c",config
.mb_sep
);
224 static int cliReadReply(int fd
) {
228 if ((nread
= anetRead(fd
,&type
,1)) <= 0) {
229 if (config
.shutdown
) return 0;
230 if (config
.interactive
&&
231 (nread
== 0 || (nread
== -1 && errno
== ECONNRESET
)))
235 printf("I/O error while reading from socket: %s",strerror(errno
));
241 if (config
.tty
) printf("(error) ");
242 cliReadSingleLineReply(fd
,0);
245 return cliReadSingleLineReply(fd
,0);
247 if (config
.tty
) printf("(integer) ");
248 return cliReadSingleLineReply(fd
,0);
250 return cliReadBulkReply(fd
);
252 return cliReadMultiBulkReply(fd
);
254 printf("protocol error, got '%c' as reply type byte", type
);
259 static int selectDb(int fd
) {
264 if (config
.dbnum
== 0)
268 cmd
= sdscatprintf(cmd
,"SELECT %d\r\n",config
.dbnum
);
269 anetWrite(fd
,cmd
,sdslen(cmd
));
270 anetRead(fd
,&type
,1);
271 if (type
<= 0 || type
!= '+') return 1;
272 retval
= cliReadSingleLineReply(fd
,1);
279 static void showInteractiveHelp(void) {
282 "Welcome to redis-cli " REDIS_VERSION
"!\n"
283 "Just type any valid Redis command to see a pretty printed output.\n"
285 "It is possible to quote strings, like in:\n"
286 " set \"my key\" \"some string \\xff\\n\"\n"
288 "You can find a list of valid Redis commands at\n"
289 " http://code.google.com/p/redis/wiki/CommandReference\n"
291 "Note: redis-cli supports line editing, use up/down arrows for history."
295 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
296 char *command
= argv
[0];
297 int fd
, j
, retval
= 0;
300 config
.raw_output
= !strcasecmp(command
,"info");
301 if (!strcasecmp(command
,"help")) {
302 showInteractiveHelp();
305 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
306 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
307 if (!strcasecmp(command
,"subscribe") ||
308 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
309 if ((fd
= cliConnect(0)) == -1) return 1;
311 /* Select db number */
312 retval
= selectDb(fd
);
314 fprintf(stderr
,"Error setting DB num\n");
318 /* Build the command to send */
319 cmd
= sdscatprintf(sdsempty(),"*%d\r\n",argc
);
320 for (j
= 0; j
< argc
; j
++) {
321 cmd
= sdscatprintf(cmd
,"$%lu\r\n",
322 (unsigned long)sdslen(argv
[j
]));
323 cmd
= sdscatlen(cmd
,argv
[j
],sdslen(argv
[j
]));
324 cmd
= sdscatlen(cmd
,"\r\n",2);
328 anetWrite(fd
,cmd
,sdslen(cmd
));
329 while (config
.monitor_mode
) {
330 if (cliReadSingleLineReply(fd
,0)) exit(1);
334 if (config
.pubsub_mode
) {
335 printf("Reading messages... (press Ctrl-c to quit)\n");
342 retval
= cliReadReply(fd
);
343 if (!config
.raw_output
&& config
.tty
) printf("\n");
344 if (retval
) return retval
;
349 /*------------------------------------------------------------------------------
351 *--------------------------------------------------------------------------- */
353 static int parseOptions(int argc
, char **argv
) {
356 for (i
= 1; i
< argc
; i
++) {
357 int lastarg
= i
==argc
-1;
359 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
360 char *ip
= zmalloc(32);
361 if (anetResolve(NULL
,argv
[i
+1],ip
) == ANET_ERR
) {
362 printf("Can't resolve %s\n", argv
[i
]);
367 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
369 } else if (!strcmp(argv
[i
],"-x")) {
371 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
372 config
.hostport
= atoi(argv
[i
+1]);
374 } else if (!strcmp(argv
[i
],"-s") && !lastarg
) {
375 config
.hostsocket
= argv
[i
+1];
377 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
378 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
380 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
381 config
.dbnum
= atoi(argv
[i
+1]);
383 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
384 config
.auth
= argv
[i
+1];
386 } else if (!strcmp(argv
[i
],"-i")) {
388 "Starting interactive mode using -i is deprecated. Interactive mode is started\n"
389 "by default when redis-cli is executed without a command to execute.\n"
391 } else if (!strcmp(argv
[i
],"-c")) {
393 "Reading last argument from standard input using -c is deprecated.\n"
394 "When standard input is connected to a pipe or regular file, it is\n"
395 "automatically used as last argument.\n"
397 } else if (!strcmp(argv
[i
],"-v")) {
398 printf("redis-cli shipped with Redis version %s\n", REDIS_VERSION
);
407 static sds
readArgFromStdin(void) {
409 sds arg
= sdsempty();
412 int nread
= read(fileno(stdin
),buf
,1024);
414 if (nread
== 0) break;
415 else if (nread
== -1) {
416 perror("Reading from standard input");
419 arg
= sdscatlen(arg
,buf
,nread
);
424 static void usage() {
425 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");
426 fprintf(stderr
, "usage: echo \"argN\" | redis-cli -x [options] cmd arg1 arg2 ... arg(N-1)\n\n");
427 fprintf(stderr
, "example: cat /etc/passwd | redis-cli -x set my_passwd\n");
428 fprintf(stderr
, "example: redis-cli get my_passwd\n");
429 fprintf(stderr
, "example: redis-cli -r 100 lpush mylist x\n");
430 fprintf(stderr
, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
434 /* Turn the plain C strings into Sds strings */
435 static char **convertToSds(int count
, char** args
) {
437 char **sds
= zmalloc(sizeof(char*)*count
);
439 for(j
= 0; j
< count
; j
++)
440 sds
[j
] = sdsnew(args
[j
]);
445 #define LINE_BUFLEN 4096
451 config
.interactive
= 1;
452 while((line
= linenoise("redis> ")) != NULL
) {
453 if (line
[0] != '\0') {
454 argv
= sdssplitargs(line
,&argc
);
455 linenoiseHistoryAdd(line
);
456 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
458 printf("Invalid argument(s)\n");
460 } else if (argc
> 0) {
461 if (strcasecmp(argv
[0],"quit") == 0 ||
462 strcasecmp(argv
[0],"exit") == 0)
467 long long start_time
= mstime(), elapsed
;
469 if ((err
= cliSendCommand(argc
, argv
, 1)) != 0) {
470 if (err
== ECONNRESET
) {
471 printf("Reconnecting... ");
473 if (cliConnect(1) == -1) exit(1);
475 cliSendCommand(argc
,argv
,1);
478 elapsed
= mstime()-start_time
;
479 if (elapsed
> 500) printf("%.2f seconds\n",
480 (double)elapsed
/1000);
483 /* Free the argument vector */
484 for (j
= 0; j
< argc
; j
++)
488 /* linenoise() returns malloc-ed lines like readline() */
494 static int noninteractive(int argc
, char **argv
) {
496 if (config
.stdinarg
) {
497 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
498 argv
[argc
] = readArgFromStdin();
499 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
501 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
502 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
507 int main(int argc
, char **argv
) {
510 config
.hostip
= "127.0.0.1";
511 config
.hostport
= 6379;
512 config
.hostsocket
= NULL
;
515 config
.interactive
= 0;
517 config
.monitor_mode
= 0;
518 config
.pubsub_mode
= 0;
519 config
.raw_output
= 0;
522 config
.historyfile
= NULL
;
523 config
.tty
= isatty(fileno(stdout
)) || (getenv("FAKETTY") != NULL
);
524 config
.mb_sep
= '\n';
526 if (getenv("HOME") != NULL
) {
527 config
.historyfile
= malloc(256);
528 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
529 linenoiseHistoryLoad(config
.historyfile
);
532 firstarg
= parseOptions(argc
,argv
);
536 if (config
.auth
!= NULL
) {
538 int dbnum
= config
.dbnum
;
540 /* We need to save the real configured database number and set it to
541 * zero here, otherwise cliSendCommand() will try to perform the
542 * SELECT command before the authentication, and it will fail. */
544 authargv
[0] = "AUTH";
545 authargv
[1] = config
.auth
;
546 cliSendCommand(2, convertToSds(2, authargv
), 1);
547 config
.dbnum
= dbnum
; /* restore the right DB number */
550 /* Start interactive mode when no command is provided */
551 if (argc
== 0) repl();
552 /* Otherwise, we have some arguments to execute */
553 return noninteractive(argc
,convertToSds(argc
,argv
));