]>
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_NOTUSED(V) ((void) V)
50 static struct config
{
59 int raw_output
; /* output mode per command */
60 int tty
; /* flag for default output format */
61 int stdinarg
; /* get last arg from stdin. (-x option) */
67 static int cliReadReply(int fd
);
70 /* Connect to the client. If force is not zero the connection is performed
71 * even if there is already a connected socket. */
72 static int cliConnect(int force
) {
73 char err
[ANET_ERR_LEN
];
74 static int fd
= ANET_ERR
;
76 if (fd
== ANET_ERR
|| force
) {
78 fd
= anetTcpConnect(err
,config
.hostip
,config
.hostport
);
80 fprintf(stderr
, "Could not connect to Redis at %s:%d: %s", config
.hostip
, config
.hostport
, err
);
83 anetTcpNoDelay(NULL
,fd
);
88 static sds
cliReadLine(int fd
) {
89 sds line
= sdsempty();
99 } else if ((ret
== 0) || (c
== '\n')) {
102 line
= sdscatlen(line
,&c
,1);
105 return sdstrim(line
,"\r\n");
108 static int cliReadSingleLineReply(int fd
, int quiet
) {
109 sds reply
= cliReadLine(fd
);
111 if (reply
== NULL
) return 1;
118 static void printStringRepr(char *s
, int len
) {
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;
135 printf("\\x%02x",(unsigned char)*s
);
143 static int cliReadBulkReply(int fd
) {
144 sds replylen
= cliReadLine(fd
);
145 char *reply
, crlf
[2];
148 if (replylen
== NULL
) return 1;
149 bulklen
= atoi(replylen
);
155 reply
= zmalloc(bulklen
);
156 anetRead(fd
,reply
,bulklen
);
158 if (config
.raw_output
|| !config
.tty
) {
159 if (bulklen
&& fwrite(reply
,bulklen
,1,stdout
) == 0) {
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
);
172 static int cliReadMultiBulkReply(int fd
) {
173 sds replylen
= cliReadLine(fd
);
177 if (replylen
== NULL
) return 1;
178 elements
= atoi(replylen
);
179 if (elements
== -1) {
185 printf("(empty list or set)\n");
188 if (config
.tty
) printf("%d. ", c
);
189 if (cliReadReply(fd
)) retval
= 1;
190 if (elements
) printf("%c",config
.mb_sep
);
196 static int cliReadReply(int fd
) {
200 if ((nread
= anetRead(fd
,&type
,1)) <= 0) {
201 if (config
.shutdown
) return 0;
202 if (config
.interactive
&&
203 (nread
== 0 || (nread
== -1 && errno
== ECONNRESET
)))
207 printf("I/O error while reading from socket: %s",strerror(errno
));
213 if (config
.tty
) printf("(error) ");
214 cliReadSingleLineReply(fd
,0);
217 return cliReadSingleLineReply(fd
,0);
219 if (config
.tty
) printf("(integer) ");
220 return cliReadSingleLineReply(fd
,0);
222 return cliReadBulkReply(fd
);
224 return cliReadMultiBulkReply(fd
);
226 printf("protocol error, got '%c' as reply type byte", type
);
231 static int selectDb(int fd
) {
236 if (config
.dbnum
== 0)
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);
251 static void showInteractiveHelp(void) {
254 "Welcome to redis-cli " REDIS_VERSION
"!\n"
255 "Just type any valid Redis command to see a pretty printed output.\n"
257 "It is possible to quote strings, like in:\n"
258 " set \"my key\" \"some string \\xff\\n\"\n"
260 "You can find a list of valid Redis commands at\n"
261 " http://code.google.com/p/redis/wiki/CommandReference\n"
263 "Note: redis-cli supports line editing, use up/down arrows for history."
267 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
268 char *command
= argv
[0];
269 int fd
, j
, retval
= 0;
272 config
.raw_output
= !strcasecmp(command
,"info");
273 if (!strcasecmp(command
,"help")) {
274 showInteractiveHelp();
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;
281 if ((fd
= cliConnect(0)) == -1) return 1;
283 /* Select db number */
284 retval
= selectDb(fd
);
286 fprintf(stderr
,"Error setting DB num\n");
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);
300 anetWrite(fd
,cmd
,sdslen(cmd
));
301 while (config
.monitor_mode
) {
302 if (cliReadSingleLineReply(fd
,0)) exit(1);
306 if (config
.pubsub_mode
) {
307 printf("Reading messages... (press Ctrl-c to quit)\n");
314 retval
= cliReadReply(fd
);
315 if (!config
.raw_output
&& config
.tty
) printf("\n");
316 if (retval
) return retval
;
321 static int parseOptions(int argc
, char **argv
) {
324 for (i
= 1; i
< argc
; i
++) {
325 int lastarg
= i
==argc
-1;
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
]);
335 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
337 } else if (!strcmp(argv
[i
],"-x")) {
339 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
340 config
.hostport
= atoi(argv
[i
+1]);
342 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
343 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
345 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
346 config
.dbnum
= atoi(argv
[i
+1]);
348 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
349 config
.auth
= argv
[i
+1];
351 } else if (!strcmp(argv
[i
],"-i")) {
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"
356 } else if (!strcmp(argv
[i
],"-c")) {
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"
362 } else if (!strcmp(argv
[i
],"-v")) {
363 printf("redis-cli shipped with Redis version %s\n", REDIS_VERSION
);
372 static sds
readArgFromStdin(void) {
374 sds arg
= sdsempty();
377 int nread
= read(fileno(stdin
),buf
,1024);
379 if (nread
== 0) break;
380 else if (nread
== -1) {
381 perror("Reading from standard input");
384 arg
= sdscatlen(arg
,buf
,nread
);
389 static void usage() {
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");
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");
393 fprintf(stderr
, "example: redis-cli get my_passwd\n");
394 fprintf(stderr
, "example: redis-cli -r 100 lpush mylist x\n");
395 fprintf(stderr
, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
399 /* Turn the plain C strings into Sds strings */
400 static char **convertToSds(int count
, char** args
) {
402 char **sds
= zmalloc(sizeof(char*)*count
);
404 for(j
= 0; j
< count
; j
++)
405 sds
[j
] = sdsnew(args
[j
]);
410 #define LINE_BUFLEN 4096
416 config
.interactive
= 1;
417 while((line
= linenoise("redis> ")) != NULL
) {
418 if (line
[0] != '\0') {
419 argv
= sdssplitargs(line
,&argc
);
420 linenoiseHistoryAdd(line
);
421 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
423 printf("Invalid argument(s)\n");
425 } else if (argc
> 0) {
426 if (strcasecmp(argv
[0],"quit") == 0 ||
427 strcasecmp(argv
[0],"exit") == 0)
433 if ((err
= cliSendCommand(argc
, argv
, 1)) != 0) {
434 if (err
== ECONNRESET
) {
435 printf("Reconnecting... ");
437 if (cliConnect(1) == -1) exit(1);
439 cliSendCommand(argc
,argv
,1);
444 /* Free the argument vector */
445 for (j
= 0; j
< argc
; j
++)
449 /* linenoise() returns malloc-ed lines like readline() */
455 static int noninteractive(int argc
, char **argv
) {
457 if (config
.stdinarg
) {
458 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
459 argv
[argc
] = readArgFromStdin();
460 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
462 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
463 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
468 int main(int argc
, char **argv
) {
471 config
.hostip
= "127.0.0.1";
472 config
.hostport
= 6379;
475 config
.interactive
= 0;
477 config
.monitor_mode
= 0;
478 config
.pubsub_mode
= 0;
479 config
.raw_output
= 0;
482 config
.historyfile
= NULL
;
483 config
.tty
= isatty(fileno(stdout
)) || (getenv("FAKETTY") != NULL
);
484 config
.mb_sep
= '\n';
486 if (getenv("HOME") != NULL
) {
487 config
.historyfile
= malloc(256);
488 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
489 linenoiseHistoryLoad(config
.historyfile
);
492 firstarg
= parseOptions(argc
,argv
);
496 if (config
.auth
!= NULL
) {
498 int dbnum
= config
.dbnum
;
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. */
504 authargv
[0] = "AUTH";
505 authargv
[1] = config
.auth
;
506 cliSendCommand(2, convertToSds(2, authargv
), 1);
507 config
.dbnum
= dbnum
; /* restore the right DB number */
510 /* Start interactive mode when no command is provided */
511 if (argc
== 0) repl();
512 /* Otherwise, we have some arguments to execute */
513 return noninteractive(argc
,convertToSds(argc
,argv
));