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