]>
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
{
63 int raw_output
; /* output mode per command */
64 int tty
; /* flag for default output format */
65 int stdinarg
; /* get last arg from stdin. (-x option) */
71 static int cliReadReply(int fd
);
74 /* Connect to the client. If force is not zero the connection is performed
75 * even if there is already a connected socket. */
76 static int cliConnect(int force
) {
77 char err
[ANET_ERR_LEN
];
78 static int fd
= ANET_ERR
;
80 if (fd
== ANET_ERR
|| force
) {
82 fd
= anetTcpConnect(err
,config
.hostip
,config
.hostport
);
84 fprintf(stderr
, "Could not connect to Redis at %s:%d: %s", config
.hostip
, config
.hostport
, err
);
87 anetTcpNoDelay(NULL
,fd
);
92 static sds
cliReadLine(int fd
) {
93 sds line
= sdsempty();
103 } else if ((ret
== 0) || (c
== '\n')) {
106 line
= sdscatlen(line
,&c
,1);
109 return sdstrim(line
,"\r\n");
112 static int cliReadSingleLineReply(int fd
, int quiet
) {
113 sds reply
= cliReadLine(fd
);
115 if (reply
== NULL
) return 1;
122 static void printStringRepr(char *s
, int len
) {
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;
139 printf("\\x%02x",(unsigned char)*s
);
147 static int cliReadBulkReply(int fd
) {
148 sds replylen
= cliReadLine(fd
);
149 char *reply
, crlf
[2];
152 if (replylen
== NULL
) return 1;
153 bulklen
= atoi(replylen
);
159 reply
= zmalloc(bulklen
);
160 anetRead(fd
,reply
,bulklen
);
162 if (config
.raw_output
|| !config
.tty
) {
163 if (bulklen
&& fwrite(reply
,bulklen
,1,stdout
) == 0) {
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
);
176 static int cliReadMultiBulkReply(int fd
) {
177 sds replylen
= cliReadLine(fd
);
181 if (replylen
== NULL
) return 1;
182 elements
= atoi(replylen
);
183 if (elements
== -1) {
189 printf("(empty list or set)\n");
192 if (config
.tty
) printf("%d. ", c
);
193 if (cliReadReply(fd
)) retval
= 1;
194 if (elements
) printf("%c",config
.mb_sep
);
200 static int cliReadReply(int fd
) {
204 if ((nread
= anetRead(fd
,&type
,1)) <= 0) {
205 if (config
.shutdown
) return 0;
206 if (config
.interactive
&&
207 (nread
== 0 || (nread
== -1 && errno
== ECONNRESET
)))
211 printf("I/O error while reading from socket: %s",strerror(errno
));
217 if (config
.tty
) printf("(error) ");
218 cliReadSingleLineReply(fd
,0);
221 return cliReadSingleLineReply(fd
,0);
223 if (config
.tty
) printf("(integer) ");
224 return cliReadSingleLineReply(fd
,0);
226 return cliReadBulkReply(fd
);
228 return cliReadMultiBulkReply(fd
);
230 printf("protocol error, got '%c' as reply type byte", type
);
235 static int selectDb(int fd
) {
240 if (config
.dbnum
== 0)
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);
255 static void showInteractiveHelp(void) {
258 "Welcome to redis-cli " REDIS_VERSION
"!\n"
259 "Just type any valid Redis command to see a pretty printed output.\n"
261 "It is possible to quote strings, like in:\n"
262 " set \"my key\" \"some string \\xff\\n\"\n"
264 "You can find a list of valid Redis commands at\n"
265 " http://code.google.com/p/redis/wiki/CommandReference\n"
267 "Note: redis-cli supports line editing, use up/down arrows for history."
271 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
272 char *command
= argv
[0];
273 int fd
, j
, retval
= 0;
276 config
.raw_output
= !strcasecmp(command
,"info");
277 if (!strcasecmp(command
,"help")) {
278 showInteractiveHelp();
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;
285 if ((fd
= cliConnect(0)) == -1) return 1;
287 /* Select db number */
288 retval
= selectDb(fd
);
290 fprintf(stderr
,"Error setting DB num\n");
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);
304 anetWrite(fd
,cmd
,sdslen(cmd
));
305 while (config
.monitor_mode
) {
306 if (cliReadSingleLineReply(fd
,0)) exit(1);
310 if (config
.pubsub_mode
) {
311 printf("Reading messages... (press Ctrl-c to quit)\n");
318 retval
= cliReadReply(fd
);
319 if (!config
.raw_output
&& config
.tty
) printf("\n");
320 if (retval
) return retval
;
325 static int parseOptions(int argc
, char **argv
) {
328 for (i
= 1; i
< argc
; i
++) {
329 int lastarg
= i
==argc
-1;
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
]);
339 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
341 } else if (!strcmp(argv
[i
],"-x")) {
343 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
344 config
.hostport
= atoi(argv
[i
+1]);
346 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
347 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
349 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
350 config
.dbnum
= atoi(argv
[i
+1]);
352 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
353 config
.auth
= argv
[i
+1];
355 } else if (!strcmp(argv
[i
],"-i")) {
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"
360 } else if (!strcmp(argv
[i
],"-c")) {
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"
366 } else if (!strcmp(argv
[i
],"-v")) {
367 printf("redis-cli shipped with Redis verison %s\n", REDIS_VERSION
);
376 static sds
readArgFromStdin(void) {
378 sds arg
= sdsempty();
381 int nread
= read(fileno(stdin
),buf
,1024);
383 if (nread
== 0) break;
384 else if (nread
== -1) {
385 perror("Reading from standard input");
388 arg
= sdscatlen(arg
,buf
,nread
);
393 static void usage() {
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");
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");
397 fprintf(stderr
, "example: redis-cli get my_passwd\n");
398 fprintf(stderr
, "example: redis-cli -r 100 lpush mylist x\n");
399 fprintf(stderr
, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
403 /* Turn the plain C strings into Sds strings */
404 static char **convertToSds(int count
, char** args
) {
406 char **sds
= zmalloc(sizeof(char*)*count
);
408 for(j
= 0; j
< count
; j
++)
409 sds
[j
] = sdsnew(args
[j
]);
414 #define LINE_BUFLEN 4096
420 config
.interactive
= 1;
421 while((line
= linenoise("redis> ")) != NULL
) {
422 if (line
[0] != '\0') {
423 argv
= sdssplitargs(line
,&argc
);
424 linenoiseHistoryAdd(line
);
425 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
427 printf("Invalid argument(s)\n");
429 } else if (argc
> 0) {
430 if (strcasecmp(argv
[0],"quit") == 0 ||
431 strcasecmp(argv
[0],"exit") == 0)
437 if ((err
= cliSendCommand(argc
, argv
, 1)) != 0) {
438 if (err
== ECONNRESET
) {
439 printf("Reconnecting... ");
441 if (cliConnect(1) == -1) exit(1);
443 cliSendCommand(argc
,argv
,1);
448 /* Free the argument vector */
449 for (j
= 0; j
< argc
; j
++)
453 /* linenoise() returns malloc-ed lines like readline() */
459 static int noninteractive(int argc
, char **argv
) {
461 if (config
.stdinarg
) {
462 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
463 argv
[argc
] = readArgFromStdin();
464 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
466 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
467 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
472 int main(int argc
, char **argv
) {
475 config
.hostip
= "127.0.0.1";
476 config
.hostport
= 6379;
479 config
.interactive
= 0;
481 config
.monitor_mode
= 0;
482 config
.pubsub_mode
= 0;
483 config
.raw_output
= 0;
486 config
.historyfile
= NULL
;
487 config
.tty
= isatty(fileno(stdout
)) || (getenv("FAKETTY") != NULL
);
488 config
.mb_sep
= '\n';
490 if (getenv("HOME") != NULL
) {
491 config
.historyfile
= malloc(256);
492 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
493 linenoiseHistoryLoad(config
.historyfile
);
496 firstarg
= parseOptions(argc
,argv
);
500 if (config
.auth
!= NULL
) {
502 int dbnum
= config
.dbnum
;
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. */
508 authargv
[0] = "AUTH";
509 authargv
[1] = config
.auth
;
510 cliSendCommand(2, convertToSds(2, authargv
), 1);
511 config
.dbnum
= dbnum
; /* restore the right DB number */
514 /* Start interactive mode when no command is provided */
515 if (argc
== 0) repl();
516 /* Otherwise, we have some arguments to execute */
517 return noninteractive(argc
,convertToSds(argc
,argv
));