]> git.saurik.com Git - redis.git/blame - src/redis-cli.c
Fixed a crash loading the AOF file containing MULTI/EXEC, a result of WATCH implement...
[redis.git] / src / redis-cli.c
CommitLineData
ed9b544e 1/* Redis CLI (command line interface)
2 *
12d090d2 3 * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com>
ed9b544e 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
23d4709d 31#include "fmacros.h"
32
ed9b544e 33#include <stdio.h>
34#include <string.h>
35#include <stdlib.h>
36#include <unistd.h>
a88a2af6 37#include <ctype.h>
ed9b544e 38
39#include "anet.h"
40#include "sds.h"
41#include "adlist.h"
42#include "zmalloc.h"
cf87ebf2 43#include "linenoise.h"
ed9b544e 44
45#define REDIS_CMD_INLINE 1
46#define REDIS_CMD_BULK 2
e17e0b05 47#define REDIS_CMD_MULTIBULK 4
ed9b544e 48
49#define REDIS_NOTUSED(V) ((void) V)
50
51static struct config {
52 char *hostip;
53 int hostport;
5762b7f0 54 long repeat;
62e920df 55 int dbnum;
37dc9e5a 56 int argn_from_stdin;
6cf5882c 57 int interactive;
36e5db6d 58 int shutdown;
249c3a7d 59 int monitor_mode;
60 int pubsub_mode;
f40b035d 61 int raw_output;
288799e0 62 char *auth;
ed9b544e 63} config;
64
c937aa89 65static int cliReadReply(int fd);
a9158272 66static void usage();
c937aa89 67
ed9b544e 68static int cliConnect(void) {
69 char err[ANET_ERR_LEN];
6fa24622 70 static int fd = ANET_ERR;
ed9b544e 71
ed9b544e 72 if (fd == ANET_ERR) {
6fa24622
DJMM
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);
ed9b544e 79 }
ed9b544e 80 return fd;
81}
82
83static sds cliReadLine(int fd) {
84 sds line = sdsempty();
85
86 while(1) {
87 char c;
b91f03a4 88 ssize_t ret;
ed9b544e 89
b91f03a4
LH
90 ret = read(fd,&c,1);
91 if (ret == -1) {
ed9b544e 92 sdsfree(line);
93 return NULL;
b91f03a4 94 } else if ((ret == 0) || (c == '\n')) {
ed9b544e 95 break;
96 } else {
97 line = sdscatlen(line,&c,1);
98 }
99 }
100 return sdstrim(line,"\r\n");
101}
102
62e920df 103static int cliReadSingleLineReply(int fd, int quiet) {
ed9b544e 104 sds reply = cliReadLine(fd);
105
106 if (reply == NULL) return 1;
62e920df 107 if (!quiet)
108 printf("%s\n", reply);
621d5c19 109 sdsfree(reply);
ed9b544e 110 return 0;
111}
112
21cdc9f0 113static 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
c937aa89 138static int cliReadBulkReply(int fd) {
ed9b544e 139 sds replylen = cliReadLine(fd);
140 char *reply, crlf[2];
c937aa89 141 int bulklen;
ed9b544e 142
143 if (replylen == NULL) return 1;
ed9b544e 144 bulklen = atoi(replylen);
c937aa89 145 if (bulklen == -1) {
ed9b544e 146 sdsfree(replylen);
060f6be6 147 printf("(nil)\n");
ed9b544e 148 return 0;
149 }
ed9b544e 150 reply = zmalloc(bulklen);
151 anetRead(fd,reply,bulklen);
152 anetRead(fd,crlf,2);
f40b035d 153 if (config.raw_output || !isatty(fileno(stdout))) {
21cdc9f0 154 if (bulklen && fwrite(reply,bulklen,1,stdout) == 0) {
155 zfree(reply);
156 return 1;
157 }
21cdc9f0 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);
ed9b544e 162 }
ed9b544e 163 zfree(reply);
c937aa89 164 return 0;
ed9b544e 165}
166
167static int cliReadMultiBulkReply(int fd) {
168 sds replylen = cliReadLine(fd);
169 int elements, c = 1;
170
171 if (replylen == NULL) return 1;
c937aa89 172 elements = atoi(replylen);
173 if (elements == -1) {
ed9b544e 174 sdsfree(replylen);
175 printf("(nil)\n");
176 return 0;
177 }
c937aa89 178 if (elements == 0) {
179 printf("(empty list or set)\n");
180 }
ed9b544e 181 while(elements--) {
182 printf("%d. ", c);
c937aa89 183 if (cliReadReply(fd)) return 1;
ed9b544e 184 c++;
185 }
186 return 0;
187}
188
c937aa89 189static int cliReadReply(int fd) {
190 char type;
191
36e5db6d
BD
192 if (anetRead(fd,&type,1) <= 0) {
193 if (config.shutdown) return 0;
194 exit(1);
195 }
c937aa89 196 switch(type) {
197 case '-':
198 printf("(error) ");
62e920df 199 cliReadSingleLineReply(fd,0);
c937aa89 200 return 1;
201 case '+':
62e920df 202 return cliReadSingleLineReply(fd,0);
c937aa89 203 case ':':
443c6409 204 printf("(integer) ");
62e920df 205 return cliReadSingleLineReply(fd,0);
c937aa89 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
6cf5882c 216static int selectDb(int fd) {
62e920df 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) {
6cf5882c 231 return retval;
62e920df 232 }
233 return 0;
234}
235
aab055ae 236static int cliSendCommand(int argc, char **argv, int repeat) {
37dc9e5a 237 char *command = argv[0];
ed9b544e 238 int fd, j, retval = 0;
5762b7f0 239 sds cmd;
ed9b544e 240
37dc9e5a
PN
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;
ed9b544e 246 if ((fd = cliConnect()) == -1) return 1;
247
62e920df 248 /* Select db number */
249 retval = selectDb(fd);
250 if (retval) {
251 fprintf(stderr,"Error setting DB num\n");
252 return 1;
253 }
6cf5882c 254
a2f4f871
PN
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
aab055ae 264 while(repeat--) {
5762b7f0 265 anetWrite(fd,cmd,sdslen(cmd));
249c3a7d 266 while (config.monitor_mode) {
621d5c19 267 cliReadSingleLineReply(fd,0);
268 }
269
249c3a7d 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
5762b7f0 278 retval = cliReadReply(fd);
279 if (retval) {
36e5db6d 280 return retval;
8165a5f2 281 }
ed9b544e 282 }
ed9b544e 283 return 0;
284}
285
286static int parseOptions(int argc, char **argv) {
287 int i;
288
289 for (i = 1; i < argc; i++) {
290 int lastarg = i==argc-1;
6cf5882c 291
ed9b544e 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++;
a9158272 300 } else if (!strcmp(argv[i],"-h") && lastarg) {
301 usage();
ed9b544e 302 } else if (!strcmp(argv[i],"-p") && !lastarg) {
303 config.hostport = atoi(argv[i+1]);
304 i++;
5762b7f0 305 } else if (!strcmp(argv[i],"-r") && !lastarg) {
306 config.repeat = strtoll(argv[i+1],NULL,10);
307 i++;
62e920df 308 } else if (!strcmp(argv[i],"-n") && !lastarg) {
309 config.dbnum = atoi(argv[i+1]);
310 i++;
fdfdae0f 311 } else if (!strcmp(argv[i],"-a") && !lastarg) {
288799e0 312 config.auth = argv[i+1];
fdfdae0f 313 i++;
6cf5882c
MMDJ
314 } else if (!strcmp(argv[i],"-i")) {
315 config.interactive = 1;
37dc9e5a
PN
316 } else if (!strcmp(argv[i],"-c")) {
317 config.argn_from_stdin = 1;
ed9b544e 318 } else {
319 break;
320 }
321 }
322 return i;
323}
324
325static 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
a9158272 342static void usage() {
fdfdae0f 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");
37dc9e5a 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");
a9158272 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");
d239ec59 349 fprintf(stderr, "\nRun in interactive mode: redis-cli -i or just don't pass any command\n");
a9158272 350 exit(1);
351}
352
6cf5882c
MMDJ
353/* Turn the plain C strings into Sds strings */
354static char **convertToSds(int count, char** args) {
355 int j;
37dc9e5a 356 char **sds = zmalloc(sizeof(char*)*count);
6cf5882c
MMDJ
357
358 for(j = 0; j < count; j++)
359 sds[j] = sdsnew(args[j]);
360
361 return sds;
362}
363
a88a2af6 364static 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
6cf5882c 430static void repl() {
a88a2af6 431 int argc, j;
432 char *line, **argv;
6cf5882c 433
bc86d88e 434 while((line = linenoise("redis> ")) != NULL) {
cf87ebf2 435 if (line[0] != '\0') {
a88a2af6 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]);
8ff6a48b 448 zfree(argv);
6cf5882c 449 }
a88a2af6 450 /* linenoise() returns malloc-ed lines like readline() */
cf87ebf2 451 free(line);
6cf5882c 452 }
6cf5882c
MMDJ
453 exit(0);
454}
455
ed9b544e 456int main(int argc, char **argv) {
6cf5882c 457 int firstarg;
ed9b544e 458 char **argvcopy;
459
460 config.hostip = "127.0.0.1";
461 config.hostport = 6379;
5762b7f0 462 config.repeat = 1;
62e920df 463 config.dbnum = 0;
37dc9e5a 464 config.argn_from_stdin = 0;
36e5db6d 465 config.shutdown = 0;
6cf5882c 466 config.interactive = 0;
249c3a7d 467 config.monitor_mode = 0;
468 config.pubsub_mode = 0;
f40b035d 469 config.raw_output = 0;
288799e0 470 config.auth = NULL;
ed9b544e 471
472 firstarg = parseOptions(argc,argv);
473 argc -= firstarg;
474 argv += firstarg;
ed9b544e 475
aab055ae
MMDJ
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
d239ec59 484 if (argc == 0 || config.interactive == 1) repl();
ed9b544e 485
37dc9e5a
PN
486 argvcopy = convertToSds(argc+1, argv);
487 if (config.argn_from_stdin) {
6cf5882c
MMDJ
488 sds lastarg = readArgFromStdin();
489 argvcopy[argc] = lastarg;
490 argc++;
2073a849 491 }
aab055ae 492 return cliSendCommand(argc, argvcopy, config.repeat);
ed9b544e 493}