]> git.saurik.com Git - redis.git/blob - src/redis-cli.c
Merge master and move argument splitting patch to sds.c
[redis.git] / src / redis-cli.c
1 /* Redis CLI (command line interface)
2 *
3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
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.
17 *
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.
29 */
30
31 #include "fmacros.h"
32 #include "version.h"
33
34 #include <stdio.h>
35 #include <string.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <ctype.h>
39 #include <errno.h>
40
41 #include "anet.h"
42 #include "sds.h"
43 #include "adlist.h"
44 #include "zmalloc.h"
45 #include "linenoise.h"
46
47 #define REDIS_CMD_INLINE 1
48 #define REDIS_CMD_BULK 2
49 #define REDIS_CMD_MULTIBULK 4
50
51 #define REDIS_NOTUSED(V) ((void) V)
52
53 static struct config {
54 char *hostip;
55 int hostport;
56 long repeat;
57 int dbnum;
58 int argn_from_stdin;
59 int shutdown;
60 int monitor_mode;
61 int pubsub_mode;
62 int raw_output; /* output mode per command */
63 int tty; /* flag for default output format */
64 char mb_sep;
65 char *auth;
66 char *historyfile;
67 } config;
68
69 static int cliReadReply(int fd);
70 static void usage();
71
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;
77
78 if (fd == ANET_ERR || force) {
79 if (force) close(fd);
80 fd = anetTcpConnect(err,config.hostip,config.hostport);
81 if (fd == ANET_ERR) {
82 fprintf(stderr, "Could not connect to Redis at %s:%d: %s", config.hostip, config.hostport, err);
83 return -1;
84 }
85 anetTcpNoDelay(NULL,fd);
86 }
87 return fd;
88 }
89
90 static sds cliReadLine(int fd) {
91 sds line = sdsempty();
92
93 while(1) {
94 char c;
95 ssize_t ret;
96
97 ret = read(fd,&c,1);
98 if (ret == -1) {
99 sdsfree(line);
100 return NULL;
101 } else if ((ret == 0) || (c == '\n')) {
102 break;
103 } else {
104 line = sdscatlen(line,&c,1);
105 }
106 }
107 return sdstrim(line,"\r\n");
108 }
109
110 static int cliReadSingleLineReply(int fd, int quiet) {
111 sds reply = cliReadLine(fd);
112
113 if (reply == NULL) return 1;
114 if (!quiet)
115 printf("%s", reply);
116 sdsfree(reply);
117 return 0;
118 }
119
120 static void printStringRepr(char *s, int len) {
121 printf("\"");
122 while(len--) {
123 switch(*s) {
124 case '\\':
125 case '"':
126 printf("\\%c",*s);
127 break;
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;
133 default:
134 if (isprint(*s))
135 printf("%c",*s);
136 else
137 printf("\\x%02x",(unsigned char)*s);
138 break;
139 }
140 s++;
141 }
142 printf("\"");
143 }
144
145 static int cliReadBulkReply(int fd) {
146 sds replylen = cliReadLine(fd);
147 char *reply, crlf[2];
148 int bulklen;
149
150 if (replylen == NULL) return 1;
151 bulklen = atoi(replylen);
152 if (bulklen == -1) {
153 sdsfree(replylen);
154 printf("(nil)\n");
155 return 0;
156 }
157 reply = zmalloc(bulklen);
158 anetRead(fd,reply,bulklen);
159 anetRead(fd,crlf,2);
160 if (config.raw_output || !config.tty) {
161 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
162 zfree(reply);
163 return 1;
164 }
165 } else {
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);
169 }
170 zfree(reply);
171 return 0;
172 }
173
174 static int cliReadMultiBulkReply(int fd) {
175 sds replylen = cliReadLine(fd);
176 int elements, c = 1;
177 int retval = 0;
178
179 if (replylen == NULL) return 1;
180 elements = atoi(replylen);
181 if (elements == -1) {
182 sdsfree(replylen);
183 printf("(nil)\n");
184 return 0;
185 }
186 if (elements == 0) {
187 printf("(empty list or set)\n");
188 }
189 while(elements--) {
190 if (config.tty) printf("%d. ", c);
191 if (cliReadReply(fd)) retval = 1;
192 if (elements) printf("%c",config.mb_sep);
193 c++;
194 }
195 return retval;
196 }
197
198 static int cliReadReply(int fd) {
199 char type;
200 int nread;
201
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)))
206 {
207 return ECONNRESET;
208 } else {
209 printf("I/O error while reading from socket: %s",strerror(errno));
210 exit(1);
211 }
212 }
213 switch(type) {
214 case '-':
215 if (config.tty) printf("(error) ");
216 cliReadSingleLineReply(fd,0);
217 return 1;
218 case '+':
219 return cliReadSingleLineReply(fd,0);
220 case ':':
221 if (config.tty) printf("(integer) ");
222 return cliReadSingleLineReply(fd,0);
223 case '$':
224 return cliReadBulkReply(fd);
225 case '*':
226 return cliReadMultiBulkReply(fd);
227 default:
228 printf("protocol error, got '%c' as reply type byte\n", type);
229 return 1;
230 }
231 }
232
233 static int selectDb(int fd) {
234 int retval;
235 sds cmd;
236 char type;
237
238 if (config.dbnum == 0)
239 return 0;
240
241 cmd = sdsempty();
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);
247 if (retval) {
248 return retval;
249 }
250 return 0;
251 }
252
253 static int cliSendCommand(int argc, char **argv, int repeat) {
254 char *command = argv[0];
255 int fd, j, retval = 0;
256 sds cmd;
257
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;
264
265 /* Select db number */
266 retval = selectDb(fd);
267 if (retval) {
268 fprintf(stderr,"Error setting DB num\n");
269 return 1;
270 }
271
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);
279 }
280
281 while(repeat--) {
282 anetWrite(fd,cmd,sdslen(cmd));
283 while (config.monitor_mode) {
284 cliReadSingleLineReply(fd,0);
285 }
286
287 if (config.pubsub_mode) {
288 printf("Reading messages... (press Ctrl-c to quit)\n");
289 while (1) {
290 cliReadReply(fd);
291 printf("\n\n");
292 }
293 }
294
295 retval = cliReadReply(fd);
296 if (retval) {
297 return retval;
298 }
299 if (!config.raw_output && config.tty) {
300 printf("\n");
301 }
302 }
303 return 0;
304 }
305
306 static int parseOptions(int argc, char **argv) {
307 int i;
308
309 for (i = 1; i < argc; i++) {
310 int lastarg = i==argc-1;
311
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]);
316 exit(1);
317 }
318 config.hostip = ip;
319 i++;
320 } else if (!strcmp(argv[i],"-h") && lastarg) {
321 usage();
322 } else if (!strcmp(argv[i],"-p") && !lastarg) {
323 config.hostport = atoi(argv[i+1]);
324 i++;
325 } else if (!strcmp(argv[i],"-r") && !lastarg) {
326 config.repeat = strtoll(argv[i+1],NULL,10);
327 i++;
328 } else if (!strcmp(argv[i],"-n") && !lastarg) {
329 config.dbnum = atoi(argv[i+1]);
330 i++;
331 } else if (!strcmp(argv[i],"-a") && !lastarg) {
332 config.auth = argv[i+1];
333 i++;
334 } else if (!strcmp(argv[i],"-i")) {
335 fprintf(stderr,
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"
338 );
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);
343 exit(0);
344 } else {
345 break;
346 }
347 }
348 return i;
349 }
350
351 static sds readArgFromStdin(void) {
352 char buf[1024];
353 sds arg = sdsempty();
354
355 while(1) {
356 int nread = read(fileno(stdin),buf,1024);
357
358 if (nread == 0) break;
359 else if (nread == -1) {
360 perror("Reading from standard input");
361 exit(1);
362 }
363 arg = sdscatlen(arg,buf,nread);
364 }
365 return arg;
366 }
367
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");
376 exit(1);
377 }
378
379 /* Turn the plain C strings into Sds strings */
380 static char **convertToSds(int count, char** args) {
381 int j;
382 char **sds = zmalloc(sizeof(char*)*count);
383
384 for(j = 0; j < count; j++)
385 sds[j] = sdsnew(args[j]);
386
387 return sds;
388 }
389
390 #define LINE_BUFLEN 4096
391 static void repl() {
392 int argc, j;
393 char *line;
394 sds *argv;
395
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);
401 if (argv == NULL) {
402 printf("Invalid argument(s)\n");
403 continue;
404 } else if (argc > 0) {
405 if (strcasecmp(argv[0],"quit") == 0 ||
406 strcasecmp(argv[0],"exit") == 0)
407 {
408 exit(0);
409 } else {
410 int err;
411
412 if ((err = cliSendCommand(argc, argv, 1)) != 0) {
413 if (err == ECONNRESET) {
414 printf("Reconnecting... ");
415 fflush(stdout);
416 if (cliConnect(1) == -1) exit(1);
417 printf("OK\n");
418 cliSendCommand(argc,argv,1);
419 }
420 }
421 }
422 }
423 /* Free the argument vector */
424 for (j = 0; j < argc; j++)
425 sdsfree(argv[j]);
426 zfree(argv);
427 }
428 /* linenoise() returns malloc-ed lines like readline() */
429 free(line);
430 }
431 exit(0);
432 }
433
434 int main(int argc, char **argv) {
435 int firstarg;
436 char **argvcopy;
437
438 config.hostip = "127.0.0.1";
439 config.hostport = 6379;
440 config.repeat = 1;
441 config.dbnum = 0;
442 config.argn_from_stdin = 0;
443 config.shutdown = 0;
444 config.monitor_mode = 0;
445 config.pubsub_mode = 0;
446 config.raw_output = 0;
447 config.auth = NULL;
448 config.historyfile = NULL;
449 config.tty = isatty(fileno(stdout)) || (getenv("FAKETTY") != NULL);
450 config.mb_sep = '\n';
451
452 if (getenv("HOME") != NULL) {
453 config.historyfile = malloc(256);
454 snprintf(config.historyfile,256,"%s/.rediscli_history",getenv("HOME"));
455 linenoiseHistoryLoad(config.historyfile);
456 }
457
458 firstarg = parseOptions(argc,argv);
459 argc -= firstarg;
460 argv += firstarg;
461
462 if (config.auth != NULL) {
463 char *authargv[2];
464
465 authargv[0] = "AUTH";
466 authargv[1] = config.auth;
467 cliSendCommand(2, convertToSds(2, authargv), 1);
468 }
469
470 /* Start interactive mode when no command is provided */
471 if (argc == 0) repl();
472
473 argvcopy = convertToSds(argc+1, argv);
474 if (config.argn_from_stdin) {
475 sds lastarg = readArgFromStdin();
476 argvcopy[argc] = lastarg;
477 argc++;
478 }
479 return cliSendCommand(argc, argvcopy, config.repeat);
480 }