]> git.saurik.com Git - redis.git/blob - redis-cli.c
08c8e2d572230d5619e1a9fae1e4796b03d252c8
[redis.git] / 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
33 #include <stdio.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <ctype.h>
38
39 #include "anet.h"
40 #include "sds.h"
41 #include "adlist.h"
42 #include "zmalloc.h"
43 #include "linenoise.h"
44
45 #define REDIS_CMD_INLINE 1
46 #define REDIS_CMD_BULK 2
47 #define REDIS_CMD_MULTIBULK 4
48
49 #define REDIS_NOTUSED(V) ((void) V)
50
51 static struct config {
52 char *hostip;
53 int hostport;
54 long repeat;
55 int dbnum;
56 int argn_from_stdin;
57 int interactive;
58 int shutdown;
59 int monitor_mode;
60 int pubsub_mode;
61 int raw_output;
62 char *auth;
63 } config;
64
65 static int cliReadReply(int fd);
66 static void usage();
67
68 static int cliConnect(void) {
69 char err[ANET_ERR_LEN];
70 static int fd = ANET_ERR;
71
72 if (fd == ANET_ERR) {
73 fd = anetTcpConnect(err,config.hostip,config.hostport);
74 if (fd == ANET_ERR) {
75 fprintf(stderr, "Could not connect to Redis at %s:%d: %s", config.hostip, config.hostport, err);
76 return -1;
77 }
78 anetTcpNoDelay(NULL,fd);
79 }
80 return fd;
81 }
82
83 static sds cliReadLine(int fd) {
84 sds line = sdsempty();
85
86 while(1) {
87 char c;
88 ssize_t ret;
89
90 ret = read(fd,&c,1);
91 if (ret == -1) {
92 sdsfree(line);
93 return NULL;
94 } else if ((ret == 0) || (c == '\n')) {
95 break;
96 } else {
97 line = sdscatlen(line,&c,1);
98 }
99 }
100 return sdstrim(line,"\r\n");
101 }
102
103 static int cliReadSingleLineReply(int fd, int quiet) {
104 sds reply = cliReadLine(fd);
105
106 if (reply == NULL) return 1;
107 if (!quiet)
108 printf("%s\n", reply);
109 sdsfree(reply);
110 return 0;
111 }
112
113 static void printStringRepr(char *s, int len) {
114 printf("\"");
115 while(len--) {
116 switch(*s) {
117 case '\\':
118 case '"':
119 printf("\\%c",*s);
120 break;
121 case '\n': printf("\\n"); break;
122 case '\r': printf("\\r"); break;
123 case '\t': printf("\\t"); break;
124 case '\a': printf("\\a"); break;
125 case '\b': printf("\\b"); break;
126 default:
127 if (isprint(*s))
128 printf("%c",*s);
129 else
130 printf("\\x%02x",(unsigned char)*s);
131 break;
132 }
133 s++;
134 }
135 printf("\"\n");
136 }
137
138 static int cliReadBulkReply(int fd) {
139 sds replylen = cliReadLine(fd);
140 char *reply, crlf[2];
141 int bulklen;
142
143 if (replylen == NULL) return 1;
144 bulklen = atoi(replylen);
145 if (bulklen == -1) {
146 sdsfree(replylen);
147 printf("(nil)\n");
148 return 0;
149 }
150 reply = zmalloc(bulklen);
151 anetRead(fd,reply,bulklen);
152 anetRead(fd,crlf,2);
153 if (config.raw_output || !isatty(fileno(stdout))) {
154 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
155 zfree(reply);
156 return 1;
157 }
158 } else {
159 /* If you are producing output for the standard output we want
160 * a more interesting output with quoted characters and so forth */
161 printStringRepr(reply,bulklen);
162 }
163 zfree(reply);
164 return 0;
165 }
166
167 static int cliReadMultiBulkReply(int fd) {
168 sds replylen = cliReadLine(fd);
169 int elements, c = 1;
170
171 if (replylen == NULL) return 1;
172 elements = atoi(replylen);
173 if (elements == -1) {
174 sdsfree(replylen);
175 printf("(nil)\n");
176 return 0;
177 }
178 if (elements == 0) {
179 printf("(empty list or set)\n");
180 }
181 while(elements--) {
182 printf("%d. ", c);
183 if (cliReadReply(fd)) return 1;
184 c++;
185 }
186 return 0;
187 }
188
189 static int cliReadReply(int fd) {
190 char type;
191
192 if (anetRead(fd,&type,1) <= 0) {
193 if (config.shutdown) return 0;
194 exit(1);
195 }
196 switch(type) {
197 case '-':
198 printf("(error) ");
199 cliReadSingleLineReply(fd,0);
200 return 1;
201 case '+':
202 return cliReadSingleLineReply(fd,0);
203 case ':':
204 printf("(integer) ");
205 return cliReadSingleLineReply(fd,0);
206 case '$':
207 return cliReadBulkReply(fd);
208 case '*':
209 return cliReadMultiBulkReply(fd);
210 default:
211 printf("protocol error, got '%c' as reply type byte\n", type);
212 return 1;
213 }
214 }
215
216 static int selectDb(int fd) {
217 int retval;
218 sds cmd;
219 char type;
220
221 if (config.dbnum == 0)
222 return 0;
223
224 cmd = sdsempty();
225 cmd = sdscatprintf(cmd,"SELECT %d\r\n",config.dbnum);
226 anetWrite(fd,cmd,sdslen(cmd));
227 anetRead(fd,&type,1);
228 if (type <= 0 || type != '+') return 1;
229 retval = cliReadSingleLineReply(fd,1);
230 if (retval) {
231 return retval;
232 }
233 return 0;
234 }
235
236 static int cliSendCommand(int argc, char **argv, int repeat) {
237 char *command = argv[0];
238 int fd, j, retval = 0;
239 sds cmd;
240
241 config.raw_output = !strcasecmp(command,"info");
242 if (!strcasecmp(command,"shutdown")) config.shutdown = 1;
243 if (!strcasecmp(command,"monitor")) config.monitor_mode = 1;
244 if (!strcasecmp(command,"subscribe") ||
245 !strcasecmp(command,"psubscribe")) config.pubsub_mode = 1;
246 if ((fd = cliConnect()) == -1) return 1;
247
248 /* Select db number */
249 retval = selectDb(fd);
250 if (retval) {
251 fprintf(stderr,"Error setting DB num\n");
252 return 1;
253 }
254
255 while(repeat--) {
256 /* Build the command to send */
257 cmd = sdscatprintf(sdsempty(),"*%d\r\n",argc);
258 for (j = 0; j < argc; j++) {
259 cmd = sdscatprintf(cmd,"$%lu\r\n",
260 (unsigned long)sdslen(argv[j]));
261 cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));
262 cmd = sdscatlen(cmd,"\r\n",2);
263 }
264 anetWrite(fd,cmd,sdslen(cmd));
265 sdsfree(cmd);
266
267 while (config.monitor_mode) {
268 cliReadSingleLineReply(fd,0);
269 }
270
271 if (config.pubsub_mode) {
272 printf("Reading messages... (press Ctrl-c to quit)\n");
273 while (1) {
274 cliReadReply(fd);
275 printf("\n");
276 }
277 }
278
279 retval = cliReadReply(fd);
280
281 if (retval) {
282 return retval;
283 }
284 }
285 return 0;
286 }
287
288 static int parseOptions(int argc, char **argv) {
289 int i;
290
291 for (i = 1; i < argc; i++) {
292 int lastarg = i==argc-1;
293
294 if (!strcmp(argv[i],"-h") && !lastarg) {
295 char *ip = zmalloc(32);
296 if (anetResolve(NULL,argv[i+1],ip) == ANET_ERR) {
297 printf("Can't resolve %s\n", argv[i]);
298 exit(1);
299 }
300 config.hostip = ip;
301 i++;
302 } else if (!strcmp(argv[i],"-h") && lastarg) {
303 usage();
304 } else if (!strcmp(argv[i],"-p") && !lastarg) {
305 config.hostport = atoi(argv[i+1]);
306 i++;
307 } else if (!strcmp(argv[i],"-r") && !lastarg) {
308 config.repeat = strtoll(argv[i+1],NULL,10);
309 i++;
310 } else if (!strcmp(argv[i],"-n") && !lastarg) {
311 config.dbnum = atoi(argv[i+1]);
312 i++;
313 } else if (!strcmp(argv[i],"-a") && !lastarg) {
314 config.auth = argv[i+1];
315 i++;
316 } else if (!strcmp(argv[i],"-i")) {
317 config.interactive = 1;
318 } else if (!strcmp(argv[i],"-c")) {
319 config.argn_from_stdin = 1;
320 } else {
321 break;
322 }
323 }
324 return i;
325 }
326
327 static sds readArgFromStdin(void) {
328 char buf[1024];
329 sds arg = sdsempty();
330
331 while(1) {
332 int nread = read(fileno(stdin),buf,1024);
333
334 if (nread == 0) break;
335 else if (nread == -1) {
336 perror("Reading from standard input");
337 exit(1);
338 }
339 arg = sdscatlen(arg,buf,nread);
340 }
341 return arg;
342 }
343
344 static void usage() {
345 fprintf(stderr, "usage: redis-cli [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] [-i] cmd arg1 arg2 arg3 ... argN\n");
346 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");
347 fprintf(stderr, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");
348 fprintf(stderr, "example: cat /etc/passwd | redis-cli set my_passwd\n");
349 fprintf(stderr, "example: redis-cli get my_passwd\n");
350 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
351 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
352 exit(1);
353 }
354
355 /* Turn the plain C strings into Sds strings */
356 static char **convertToSds(int count, char** args) {
357 int j;
358 char **sds = zmalloc(sizeof(char*)*count);
359
360 for(j = 0; j < count; j++)
361 sds[j] = sdsnew(args[j]);
362
363 return sds;
364 }
365
366 static char **splitArguments(char *line, int *argc) {
367 char *p = line;
368 char *current = NULL;
369 char **vector = NULL;
370
371 *argc = 0;
372 while(1) {
373 /* skip blanks */
374 while(*p && isspace(*p)) p++;
375 if (*p) {
376 /* get a token */
377 int inq=0; /* set to 1 if we are in "quotes" */
378 int done = 0;
379
380 if (current == NULL) current = sdsempty();
381 while(!done) {
382 if (inq) {
383 if (*p == '\\' && *(p+1)) {
384 char c;
385
386 p++;
387 switch(*p) {
388 case 'n': c = '\n'; break;
389 case 'r': c = '\r'; break;
390 case 't': c = '\t'; break;
391 case 'b': c = '\b'; break;
392 case 'a': c = '\a'; break;
393 default: c = *p; break;
394 }
395 current = sdscatlen(current,&c,1);
396 } else if (*p == '"') {
397 done = 1;
398 } else {
399 current = sdscatlen(current,p,1);
400 }
401 } else {
402 switch(*p) {
403 case ' ':
404 case '\n':
405 case '\r':
406 case '\t':
407 case '\0':
408 done=1;
409 break;
410 case '"':
411 inq=1;
412 break;
413 default:
414 current = sdscatlen(current,p,1);
415 break;
416 }
417 }
418 if (*p) p++;
419 }
420 /* add the token to the vector */
421 vector = zrealloc(vector,((*argc)+1)*sizeof(char*));
422 vector[*argc] = current;
423 (*argc)++;
424 current = NULL;
425 } else {
426 return vector;
427 }
428 }
429 }
430
431 #define LINE_BUFLEN 4096
432 static void repl() {
433 int argc, j;
434 char *line, **argv;
435
436 while((line = linenoise("redis> ")) != NULL) {
437 if (line[0] != '\0') {
438 argv = splitArguments(line,&argc);
439 linenoiseHistoryAdd(line);
440 if (argc > 0) {
441 if (strcasecmp(argv[0],"quit") == 0 ||
442 strcasecmp(argv[0],"exit") == 0)
443 exit(0);
444 else
445 cliSendCommand(argc, argv, 1);
446 }
447 /* Free the argument vector */
448 for (j = 0; j < argc; j++)
449 sdsfree(argv[j]);
450 zfree(argv);
451 }
452 /* linenoise() returns malloc-ed lines like readline() */
453 free(line);
454 }
455 exit(0);
456 }
457
458 int main(int argc, char **argv) {
459 int firstarg;
460 char **argvcopy;
461
462 config.hostip = "127.0.0.1";
463 config.hostport = 6379;
464 config.repeat = 1;
465 config.dbnum = 0;
466 config.argn_from_stdin = 0;
467 config.shutdown = 0;
468 config.interactive = 0;
469 config.monitor_mode = 0;
470 config.pubsub_mode = 0;
471 config.raw_output = 0;
472 config.auth = NULL;
473
474 firstarg = parseOptions(argc,argv);
475 argc -= firstarg;
476 argv += firstarg;
477
478 if (config.auth != NULL) {
479 char *authargv[2];
480
481 authargv[0] = "AUTH";
482 authargv[1] = config.auth;
483 cliSendCommand(2, convertToSds(2, authargv), 1);
484 }
485
486 if (argc == 0 || config.interactive == 1) repl();
487
488 argvcopy = convertToSds(argc+1, argv);
489 if (config.argn_from_stdin) {
490 sds lastarg = readArgFromStdin();
491 argvcopy[argc] = lastarg;
492 argc++;
493 }
494 return cliSendCommand(argc, argvcopy, config.repeat);
495 }