PageRenderTime 43ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/src/redis-cli.c

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