]>
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.
45 #include "linenoise.h"
47 #define REDIS_CMD_INLINE 1
48 #define REDIS_CMD_BULK 2
49 #define REDIS_CMD_MULTIBULK 4
51 #define REDIS_NOTUSED(V) ((void) V)
53 static struct config
{
62 int raw_output
; /* output mode per command */
63 int tty
; /* flag for default output format */
69 static int cliReadReply(int fd
);
72 /* Connect to the client. If force is not zero the connection is performed
73 * even if there is already a connected socket. */
74 static int cliConnect(int force
) {
75 char err
[ANET_ERR_LEN
];
76 static int fd
= ANET_ERR
;
78 if (fd
== ANET_ERR
|| force
) {
80 fd
= anetTcpConnect(err
,config
.hostip
,config
.hostport
);
82 fprintf(stderr
, "Could not connect to Redis at %s:%d: %s", config
.hostip
, config
.hostport
, err
);
85 anetTcpNoDelay(NULL
,fd
);
90 static sds
cliReadLine(int fd
) {
91 sds line
= sdsempty();
101 } else if ((ret
== 0) || (c
== '\n')) {
104 line
= sdscatlen(line
,&c
,1);
107 return sdstrim(line
,"\r\n");
110 static int cliReadSingleLineReply(int fd
, int quiet
) {
111 sds reply
= cliReadLine(fd
);
113 if (reply
== NULL
) return 1;
120 static void printStringRepr(char *s
, int len
) {
128 case '\n': printf("\\n"); break;
129 case '\r': printf("\\r"); break;
130 case '\t': printf("\\t"); break;
131 case '\a': printf("\\a"); break;
132 case '\b': printf("\\b"); break;
137 printf("\\x%02x",(unsigned char)*s
);
145 static int cliReadBulkReply(int fd
) {
146 sds replylen
= cliReadLine(fd
);
147 char *reply
, crlf
[2];
150 if (replylen
== NULL
) return 1;
151 bulklen
= atoi(replylen
);
157 reply
= zmalloc(bulklen
);
158 anetRead(fd
,reply
,bulklen
);
160 if (config
.raw_output
|| !config
.tty
) {
161 if (bulklen
&& fwrite(reply
,bulklen
,1,stdout
) == 0) {
166 /* If you are producing output for the standard output we want
167 * a more interesting output with quoted characters and so forth */
168 printStringRepr(reply
,bulklen
);
174 static int cliReadMultiBulkReply(int fd
) {
175 sds replylen
= cliReadLine(fd
);
179 if (replylen
== NULL
) return 1;
180 elements
= atoi(replylen
);
181 if (elements
== -1) {
187 printf("(empty list or set)\n");
190 if (config
.tty
) printf("%d. ", c
);
191 if (cliReadReply(fd
)) retval
= 1;
192 if (elements
) printf("%c",config
.mb_sep
);
198 static int cliReadReply(int fd
) {
202 if ((nread
= anetRead(fd
,&type
,1)) <= 0) {
203 if (config
.shutdown
) return 0;
204 if (config
.interactive
&&
205 (nread
== 0 || (nread
== -1 && errno
== ECONNRESET
)))
209 printf("I/O error while reading from socket: %s",strerror(errno
));
215 if (config
.tty
) printf("(error) ");
216 cliReadSingleLineReply(fd
,0);
219 return cliReadSingleLineReply(fd
,0);
221 if (config
.tty
) printf("(integer) ");
222 return cliReadSingleLineReply(fd
,0);
224 return cliReadBulkReply(fd
);
226 return cliReadMultiBulkReply(fd
);
228 printf("protocol error, got '%c' as reply type byte\n", type
);
233 static int selectDb(int fd
) {
238 if (config
.dbnum
== 0)
242 cmd
= sdscatprintf(cmd
,"SELECT %d\r\n",config
.dbnum
);
243 anetWrite(fd
,cmd
,sdslen(cmd
));
244 anetRead(fd
,&type
,1);
245 if (type
<= 0 || type
!= '+') return 1;
246 retval
= cliReadSingleLineReply(fd
,1);
253 static int cliSendCommand(int argc
, char **argv
, int repeat
) {
254 char *command
= argv
[0];
255 int fd
, j
, retval
= 0;
258 config
.raw_output
= !strcasecmp(command
,"info");
259 if (!strcasecmp(command
,"shutdown")) config
.shutdown
= 1;
260 if (!strcasecmp(command
,"monitor")) config
.monitor_mode
= 1;
261 if (!strcasecmp(command
,"subscribe") ||
262 !strcasecmp(command
,"psubscribe")) config
.pubsub_mode
= 1;
263 if ((fd
= cliConnect(0)) == -1) return 1;
265 /* Select db number */
266 retval
= selectDb(fd
);
268 fprintf(stderr
,"Error setting DB num\n");
272 /* Build the command to send */
273 cmd
= sdscatprintf(sdsempty(),"*%d\r\n",argc
);
274 for (j
= 0; j
< argc
; j
++) {
275 cmd
= sdscatprintf(cmd
,"$%lu\r\n",
276 (unsigned long)sdslen(argv
[j
]));
277 cmd
= sdscatlen(cmd
,argv
[j
],sdslen(argv
[j
]));
278 cmd
= sdscatlen(cmd
,"\r\n",2);
282 anetWrite(fd
,cmd
,sdslen(cmd
));
283 while (config
.monitor_mode
) {
284 cliReadSingleLineReply(fd
,0);
287 if (config
.pubsub_mode
) {
288 printf("Reading messages... (press Ctrl-c to quit)\n");
295 retval
= cliReadReply(fd
);
299 if (!config
.raw_output
&& config
.tty
) {
306 static int parseOptions(int argc
, char **argv
) {
309 for (i
= 1; i
< argc
; i
++) {
310 int lastarg
= i
==argc
-1;
312 if (!strcmp(argv
[i
],"-h") && !lastarg
) {
313 char *ip
= zmalloc(32);
314 if (anetResolve(NULL
,argv
[i
+1],ip
) == ANET_ERR
) {
315 printf("Can't resolve %s\n", argv
[i
]);
320 } else if (!strcmp(argv
[i
],"-h") && lastarg
) {
322 } else if (!strcmp(argv
[i
],"-p") && !lastarg
) {
323 config
.hostport
= atoi(argv
[i
+1]);
325 } else if (!strcmp(argv
[i
],"-r") && !lastarg
) {
326 config
.repeat
= strtoll(argv
[i
+1],NULL
,10);
328 } else if (!strcmp(argv
[i
],"-n") && !lastarg
) {
329 config
.dbnum
= atoi(argv
[i
+1]);
331 } else if (!strcmp(argv
[i
],"-a") && !lastarg
) {
332 config
.auth
= argv
[i
+1];
334 } else if (!strcmp(argv
[i
],"-i")) {
336 "Starting interactive mode using -i is deprecated. Interactive mode is started\n"
337 "by default when redis-cli is executed without a command to execute.\n"
339 } else if (!strcmp(argv
[i
],"-c")) {
340 config
.argn_from_stdin
= 1;
341 } else if (!strcmp(argv
[i
],"-v")) {
342 printf("redis-cli shipped with Redis verison %s\n", REDIS_VERSION
);
351 static sds
readArgFromStdin(void) {
353 sds arg
= sdsempty();
356 int nread
= read(fileno(stdin
),buf
,1024);
358 if (nread
== 0) break;
359 else if (nread
== -1) {
360 perror("Reading from standard input");
363 arg
= sdscatlen(arg
,buf
,nread
);
368 static void usage() {
369 fprintf(stderr
, "usage: redis-cli [-iv] [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 arg3 ... argN\n");
370 fprintf(stderr
, "usage: echo \"argN\" | redis-cli -c [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] cmd arg1 arg2 ... arg(N-1)\n");
371 fprintf(stderr
, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");
372 fprintf(stderr
, "example: cat /etc/passwd | redis-cli set my_passwd\n");
373 fprintf(stderr
, "example: redis-cli get my_passwd\n");
374 fprintf(stderr
, "example: redis-cli -r 100 lpush mylist x\n");
375 fprintf(stderr
, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
379 /* Turn the plain C strings into Sds strings */
380 static char **convertToSds(int count
, char** args
) {
382 char **sds
= zmalloc(sizeof(char*)*count
);
384 for(j
= 0; j
< count
; j
++)
385 sds
[j
] = sdsnew(args
[j
]);
390 #define LINE_BUFLEN 4096
396 while((line
= linenoise("redis> ")) != NULL
) {
397 if (line
[0] != '\0') {
398 argv
= sdssplitargs(line
,&argc
);
399 linenoiseHistoryAdd(line
);
400 if (config
.historyfile
) linenoiseHistorySave(config
.historyfile
);
402 printf("Invalid argument(s)\n");
404 } else if (argc
> 0) {
405 if (strcasecmp(argv
[0],"quit") == 0 ||
406 strcasecmp(argv
[0],"exit") == 0)
412 if ((err
= cliSendCommand(argc
, argv
, 1)) != 0) {
413 if (err
== ECONNRESET
) {
414 printf("Reconnecting... ");
416 if (cliConnect(1) == -1) exit(1);
418 cliSendCommand(argc
,argv
,1);
423 /* Free the argument vector */
424 for (j
= 0; j
< argc
; j
++)
428 /* linenoise() returns malloc-ed lines like readline() */
434 int main(int argc
, char **argv
) {
438 config
.hostip
= "127.0.0.1";
439 config
.hostport
= 6379;
442 config
.argn_from_stdin
= 0;
444 config
.monitor_mode
= 0;
445 config
.pubsub_mode
= 0;
446 config
.raw_output
= 0;
448 config
.historyfile
= NULL
;
449 config
.tty
= isatty(fileno(stdout
)) || (getenv("FAKETTY") != NULL
);
450 config
.mb_sep
= '\n';
452 if (getenv("HOME") != NULL
) {
453 config
.historyfile
= malloc(256);
454 snprintf(config
.historyfile
,256,"%s/.rediscli_history",getenv("HOME"));
455 linenoiseHistoryLoad(config
.historyfile
);
458 firstarg
= parseOptions(argc
,argv
);
462 if (config
.auth
!= NULL
) {
465 authargv
[0] = "AUTH";
466 authargv
[1] = config
.auth
;
467 cliSendCommand(2, convertToSds(2, authargv
), 1);
470 /* Start interactive mode when no command is provided */
471 if (argc
== 0) repl();
473 argvcopy
= convertToSds(argc
+1, argv
);
474 if (config
.argn_from_stdin
) {
475 sds lastarg
= readArgFromStdin();
476 argvcopy
[argc
] = lastarg
;
479 return cliSendCommand(argc
, argvcopy
, config
.repeat
);