]> git.saurik.com Git - redis.git/blob - redis-cli.c
Merge remote branch 'pietern/zfixes'
[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 /* Build the command to send */
256 cmd = sdscatprintf(sdsempty(),"*%d\r\n",argc);
257 for (j = 0; j < argc; j++) {
258 cmd = sdscatprintf(cmd,"$%lu\r\n",
259 (unsigned long)sdslen(argv[j]));
260 cmd = sdscatlen(cmd,argv[j],sdslen(argv[j]));
261 cmd = sdscatlen(cmd,"\r\n",2);
262 }
263
264 while(repeat--) {
265 anetWrite(fd,cmd,sdslen(cmd));
266 while (config.monitor_mode) {
267 cliReadSingleLineReply(fd,0);
268 }
269
270 if (config.pubsub_mode) {
271 printf("Reading messages... (press Ctrl-c to quit)\n");
272 while (1) {
273 cliReadReply(fd);
274 printf("\n");
275 }
276 }
277
278 retval = cliReadReply(fd);
279 if (retval) {
280 return retval;
281 }
282 }
283 return 0;
284 }
285
286 static int parseOptions(int argc, char **argv) {
287 int i;
288
289 for (i = 1; i < argc; i++) {
290 int lastarg = i==argc-1;
291
292 if (!strcmp(argv[i],"-h") && !lastarg) {
293 char *ip = zmalloc(32);
294 if (anetResolve(NULL,argv[i+1],ip) == ANET_ERR) {
295 printf("Can't resolve %s\n", argv[i]);
296 exit(1);
297 }
298 config.hostip = ip;
299 i++;
300 } else if (!strcmp(argv[i],"-h") && lastarg) {
301 usage();
302 } else if (!strcmp(argv[i],"-p") && !lastarg) {
303 config.hostport = atoi(argv[i+1]);
304 i++;
305 } else if (!strcmp(argv[i],"-r") && !lastarg) {
306 config.repeat = strtoll(argv[i+1],NULL,10);
307 i++;
308 } else if (!strcmp(argv[i],"-n") && !lastarg) {
309 config.dbnum = atoi(argv[i+1]);
310 i++;
311 } else if (!strcmp(argv[i],"-a") && !lastarg) {
312 config.auth = argv[i+1];
313 i++;
314 } else if (!strcmp(argv[i],"-i")) {
315 config.interactive = 1;
316 } else if (!strcmp(argv[i],"-c")) {
317 config.argn_from_stdin = 1;
318 } else {
319 break;
320 }
321 }
322 return i;
323 }
324
325 static sds readArgFromStdin(void) {
326 char buf[1024];
327 sds arg = sdsempty();
328
329 while(1) {
330 int nread = read(fileno(stdin),buf,1024);
331
332 if (nread == 0) break;
333 else if (nread == -1) {
334 perror("Reading from standard input");
335 exit(1);
336 }
337 arg = sdscatlen(arg,buf,nread);
338 }
339 return arg;
340 }
341
342 static void usage() {
343 fprintf(stderr, "usage: redis-cli [-h host] [-p port] [-a authpw] [-r repeat_times] [-n db_num] [-i] cmd arg1 arg2 arg3 ... argN\n");
344 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");
345 fprintf(stderr, "\nIf a pipe from standard input is detected this data is used as last argument.\n\n");
346 fprintf(stderr, "example: cat /etc/passwd | redis-cli set my_passwd\n");
347 fprintf(stderr, "example: redis-cli get my_passwd\n");
348 fprintf(stderr, "example: redis-cli -r 100 lpush mylist x\n");
349 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
350 exit(1);
351 }
352
353 /* Turn the plain C strings into Sds strings */
354 static char **convertToSds(int count, char** args) {
355 int j;
356 char **sds = zmalloc(sizeof(char*)*count);
357
358 for(j = 0; j < count; j++)
359 sds[j] = sdsnew(args[j]);
360
361 return sds;
362 }
363
364 static char **splitArguments(char *line, int *argc) {
365 char *p = line;
366 char *current = NULL;
367 char **vector = NULL;
368
369 *argc = 0;
370 while(1) {
371 /* skip blanks */
372 while(*p && isspace(*p)) p++;
373 if (*p) {
374 /* get a token */
375 int inq=0; /* set to 1 if we are in "quotes" */
376 int done = 0;
377
378 if (current == NULL) current = sdsempty();
379 while(!done) {
380 if (inq) {
381 if (*p == '\\' && *(p+1)) {
382 char c;
383
384 p++;
385 switch(*p) {
386 case 'n': c = '\n'; break;
387 case 'r': c = '\r'; break;
388 case 't': c = '\t'; break;
389 case 'b': c = '\b'; break;
390 case 'a': c = '\a'; break;
391 default: c = *p; break;
392 }
393 current = sdscatlen(current,&c,1);
394 } else if (*p == '"') {
395 done = 1;
396 } else {
397 current = sdscatlen(current,p,1);
398 }
399 } else {
400 switch(*p) {
401 case ' ':
402 case '\n':
403 case '\r':
404 case '\t':
405 case '\0':
406 done=1;
407 break;
408 case '"':
409 inq=1;
410 break;
411 default:
412 current = sdscatlen(current,p,1);
413 break;
414 }
415 }
416 if (*p) p++;
417 }
418 /* add the token to the vector */
419 vector = zrealloc(vector,((*argc)+1)*sizeof(char*));
420 vector[*argc] = current;
421 (*argc)++;
422 current = NULL;
423 } else {
424 return vector;
425 }
426 }
427 }
428
429 #define LINE_BUFLEN 4096
430 static void repl() {
431 int argc, j;
432 char *line, **argv;
433
434 while((line = linenoise("redis> ")) != NULL) {
435 if (line[0] != '\0') {
436 argv = splitArguments(line,&argc);
437 linenoiseHistoryAdd(line);
438 if (argc > 0) {
439 if (strcasecmp(argv[0],"quit") == 0 ||
440 strcasecmp(argv[0],"exit") == 0)
441 exit(0);
442 else
443 cliSendCommand(argc, argv, 1);
444 }
445 /* Free the argument vector */
446 for (j = 0; j < argc; j++)
447 sdsfree(argv[j]);
448 zfree(argv);
449 }
450 /* linenoise() returns malloc-ed lines like readline() */
451 free(line);
452 }
453 exit(0);
454 }
455
456 int main(int argc, char **argv) {
457 int firstarg;
458 char **argvcopy;
459
460 config.hostip = "127.0.0.1";
461 config.hostport = 6379;
462 config.repeat = 1;
463 config.dbnum = 0;
464 config.argn_from_stdin = 0;
465 config.shutdown = 0;
466 config.interactive = 0;
467 config.monitor_mode = 0;
468 config.pubsub_mode = 0;
469 config.raw_output = 0;
470 config.auth = NULL;
471
472 firstarg = parseOptions(argc,argv);
473 argc -= firstarg;
474 argv += firstarg;
475
476 if (config.auth != NULL) {
477 char *authargv[2];
478
479 authargv[0] = "AUTH";
480 authargv[1] = config.auth;
481 cliSendCommand(2, convertToSds(2, authargv), 1);
482 }
483
484 if (argc == 0 || config.interactive == 1) repl();
485
486 argvcopy = convertToSds(argc+1, argv);
487 if (config.argn_from_stdin) {
488 sds lastarg = readArgFromStdin();
489 argvcopy[argc] = lastarg;
490 argc++;
491 }
492 return cliSendCommand(argc, argvcopy, config.repeat);
493 }