]>
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 */
70 static int cliReadReply(int fd
);
73 /* Connect to the client. If force is not zero the connection is performed
74 * even if there is already a connected socket. */
75 static int cliConnect(int force
) {
76 char err
[ANET_ERR_LEN
];
77 static int fd
= ANET_ERR
;
79 if (fd
== ANET_ERR
|| force
) {
81 fd
= anetTcpConnect(err
,config
.hostip
,config
.hostport
);
83 fprintf(stderr
, "Could not connect to Redis at %s:%d: %s", config
.hostip
, config
.hostport
, err
);
86 anetTcpNoDelay(NULL
,fd
);
91 static sds
cliReadLine(int fd
) {
92 sds line
= sdsempty();
102 } else if ((ret
== 0) || (c
== '\n')) {
105 line
= sdscatlen(line
,&c
,1);
108 return sdstrim(line
,"\r\n");
111 static int cliReadSingleLineReply(int fd
, int quiet
) {
112 sds reply
= cliReadLine(fd
);
114 if (reply
== NULL
) return 1;
121 static void printStringRepr(char *s
, int len
) {
129 case '\n': printf("\\n"); break;
130 case '\r': printf("\\r"); break;
131 case '\t': printf("\\t"); break;
132 case '\a': printf("\\a"); break;
133 case '\b': printf("\\b"); break;
138 printf("\\x%02x",(unsigned char)*s
);
146 static int cliReadBulkReply(int fd
) {
147 sds replylen
= cliReadLine(fd
);
148 char *reply
, crlf
[2];
151 if (replylen
== NULL
) return 1;
152 bulklen
= atoi(replylen
);
158 reply
= zmalloc(bulklen
);
159 anetRead(fd
,reply
,bulklen
);
161 if (config
.raw_output
|| !config
.tty
) {
162 if (bulklen
&& fwrite(reply
,bulklen
,1,stdout
) == 0) {
167 /* If you are producing output for the standard output we want
168 * a more interesting output with quoted characters and so forth */
169 printStringRepr(reply
,bulklen
);
175 static int cliReadMultiBulkReply(int fd
) {
176 sds replylen
= cliReadLine(fd
);
180 if (replylen
== NULL
) return 1;
181 elements
= atoi(replylen
);
182 if (elements
== -1) {
188 printf("(empty list or set)\n");
191 if (config
.tty
) printf("%d. ", c
);
192 if (cliReadReply(fd
)) retval
= 1;
193 if (elements
) printf("%c",config
.mb_sep
);
199 static int cliReadReply(int fd
) {
203 if ((nread
= anetRead(fd
,&type
,1)) <= 0) {
204 if (config
.shutdown
) return 0;
205 if (config
.interactive
&&
206 (nread
== 0 || (nread
== -1 && errno
== ECONNRESET
)))
210 printf("I/O error while reading from socket: %s",strerror(errno
));
216 if (config
.tty
) printf("(error) ");
217 cliReadSingleLineReply(fd
,0);
220 return cliReadSingleLineReply(fd
,0);
222 if (config
.tty
) printf("(integer) ");
223 return cliReadSingleLineReply(fd
,0);
225 return cliReadBulkReply(fd
);
227 return cliReadMultiBulkReply(fd
);
229 printf("protocol error, got '%c' as reply type byte", type
);
234 static int selectDb(int fd
) {
239 if (config
.dbnum
== 0)
243 cmd
= sdscatprintf(cmd
,"SELECT %d\r\n",config
.dbnum
);
244 anetWrite(fd
,cmd
,sdslen(cmd
));
245 anetRead(fd
,&type
,1);
246 if (type
<= 0 || type
!= '+') return 1;
247 retval
= cliReadSingleLineReply(fd
,1);
254 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
255 char *command
= argv
[0];
256 int fd
, j
, retval
= 0;
259 config
.raw_output
= !strcasecmp(command
,"info");
260 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
261 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
262 if (!strcasecmp(command
,"subscribe") ||
263 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
264 if ((fd
= cliConnect(0)) == -1) return 1;
266 /* Select db number */
267 retval
= selectDb(fd
);
269 fprintf(stderr
,"Error setting DB num\n");
273 /* Build the command to send */
274 cmd
= sdscatprintf(sdsempty(),"*%d\r\n",argc
);
275 for (j
= 0; j
< argc
; j
++) {
276 cmd
= sdscatprintf(cmd
,"$%lu\r\n",
277 (unsigned long)sdslen(argv
[j
]));
278 cmd
= sdscatlen(cmd
,argv
[j
],sdslen(argv
[j
]));
279 cmd
= sdscatlen(cmd
,"\r\n",2);
283 anetWrite(fd
,cmd
,sdslen(cmd
));
284 while (config
.monitor_mode
) {
285 if (cliReadSingleLineReply(fd
,0)) exit(1);
289 if (config
.pubsub_mode
) {
290 printf("Reading messages... (press Ctrl-c to quit)\n");
297 retval
= cliReadReply(fd
);
298 if (!config
.raw_output
&& config
.tty
) printf("\n");
299 if (retval
) return retval
;
304 static int parseOptions(int argc
, char **argv
) {
307 for (i
= 1; i
< argc
; i
++) {
308 int lastarg
= i
==argc
-1;
310 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
311 char *ip
= zmalloc(32);
312 if (anetResolve(NULL
,argv
[i
+1],ip
) == ANET_ERR
) {
313 printf("Can't resolve %s\n", argv
[i
]);
318 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
320 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
321 config
.hostport
= atoi(argv
[i
+1]);
323 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
324 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
326 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
327 config
.dbnum
= atoi(argv
[i
+1]);
329 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
330 config
.auth
= argv
[i
+1];
332 } else if (!strcmp(argv
[i
],"-i")) {
334 "Starting interactive mode using -i is deprecated. Interactive mode is started\n"
335 "by default when redis-cli is executed without a command to execute.\n"
337 } else if (!strcmp(argv
[i
],"-c")) {
339 "Reading last argument from standard input using -c is deprecated.\n"
340 "When standard input is connected to a pipe or regular file, it is\n"
341 "automatically used as last argument.\n"
343 } else if (!strcmp(argv
[i
],"-v")) {
344 printf("redis-cli shipped with Redis verison %s\n", REDIS_VERSION
);
353 static sds
readArgFromStdin(void) {
355 sds arg
= sdsempty();
358 int nread
= read(fileno(stdin
),buf
,1024);
360 if (nread
== 0) break;
361 else if (nread
== -1) {
362 perror("Reading from standard input");
365 arg
= sdscatlen(arg
,buf
,nread
);
370 static void usage() {
371 fprintf(stderr
, "usage: redis-cli [-iv] [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 arg3 ... argN\n");
372 fprintf(stderr
, "usage: echo \"argN\" | redis-cli [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 ... arg(N-1)\n");
373 fprintf(stderr
, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");
374 fprintf(stderr
, "example: cat /etc/passwd | redis-cli set my_passwd\n");
375 fprintf(stderr
, "example: redis-cli get my_passwd\n");
376 fprintf(stderr
, "example: redis-cli -r 100 lpush mylist x\n");
377 fprintf(stderr
, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
381 /* Turn the plain C strings into Sds strings */
382 static char **convertToSds(int count
, char** args
) {
384 char **sds
= zmalloc(sizeof(char*)*count
);
386 for(j
= 0; j
< count
; j
++)
387 sds
[j
] = sdsnew(args
[j
]);
392 #define LINE_BUFLEN 4096
398 config
.interactive
= 1;
399 while((line
= linenoise("redis> ")) != NULL
) {
400 if (line
[0] != '\0') {
401 argv
= sdssplitargs(line
,&argc
);
402 linenoiseHistoryAdd(line
);
403 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
405 printf("Invalid argument(s)\n");
407 } else if (argc
> 0) {
408 if (strcasecmp(argv
[0],"quit") == 0 ||
409 strcasecmp(argv
[0],"exit") == 0)
415 if ((err
= cliSendCommand(argc
, argv
, 1)) != 0) {
416 if (err
== ECONNRESET
) {
417 printf("Reconnecting... ");
419 if (cliConnect(1) == -1) exit(1);
421 cliSendCommand(argc
,argv
,1);
426 /* Free the argument vector */
427 for (j
= 0; j
< argc
; j
++)
431 /* linenoise() returns malloc-ed lines like readline() */
437 static int noninteractive(int argc
, char **argv
) {
440 fstat(fileno(stdin
), &s
);
441 if (S_ISFIFO(s
.st_mode
) || S_ISREG(s
.st_mode
)) { /* pipe, regular file */
442 argv
= zrealloc(argv
, (argc
+1)*sizeof(char*));
443 argv
[argc
] = readArgFromStdin();
444 retval
= cliSendCommand(argc
+1, argv
, config
.repeat
);
446 /* stdin is probably a tty, can be tested with S_ISCHR(s.st_mode) */
447 retval
= cliSendCommand(argc
, argv
, config
.repeat
);
452 int main(int argc
, char **argv
) {
455 config
.hostip
= "127.0.0.1";
456 config
.hostport
= 6379;
459 config
.interactive
= 0;
461 config
.monitor_mode
= 0;
462 config
.pubsub_mode
= 0;
463 config
.raw_output
= 0;
465 config
.historyfile
= NULL
;
466 config
.tty
= isatty(fileno(stdout
)) || (getenv("FAKETTY") != NULL
);
467 config
.mb_sep
= '\n';
469 if (getenv("HOME") != NULL
) {
470 config
.historyfile
= malloc(256);
471 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
472 linenoiseHistoryLoad(config
.historyfile
);
475 firstarg
= parseOptions(argc
,argv
);
479 if (config
.auth
!= NULL
) {
481 int dbnum
= config
.dbnum
;
483 /* We need to save the real configured database number and set it to
484 * zero here, otherwise cliSendCommand() will try to perform the
485 * SELECT command before the authentication, and it will fail. */
487 authargv
[0] = "AUTH";
488 authargv
[1] = config
.auth
;
489 cliSendCommand(2, convertToSds(2, authargv
), 1);
490 config
.dbnum
= dbnum
; /* restore the right DB number */
493 /* Start interactive mode when no command is provided */
494 if (argc
== 0) repl();
495 /* Otherwise, we have some arguments to execute */
496 return noninteractive(argc
,convertToSds(argc
,argv
));