unixctl: Improve readability of "help" output for long command names.
[cascardo/ovs.git] / lib / unixctl.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "unixctl.h"
19 #include <assert.h>
20 #include <ctype.h>
21 #include <errno.h>
22 #include <poll.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/socket.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 #include "coverage.h"
29 #include "dirs.h"
30 #include "dynamic-string.h"
31 #include "fatal-signal.h"
32 #include "list.h"
33 #include "ofpbuf.h"
34 #include "poll-loop.h"
35 #include "shash.h"
36 #include "socket-util.h"
37 #include "svec.h"
38 #include "util.h"
39 #include "vlog.h"
40
41 #ifndef SCM_CREDENTIALS
42 #include <time.h>
43 #endif
44
45 VLOG_DEFINE_THIS_MODULE(unixctl);
46
47 COVERAGE_DEFINE(unixctl_received);
48 COVERAGE_DEFINE(unixctl_replied);
49 \f
50 struct unixctl_command {
51     const char *usage;
52     int min_args, max_args;
53     unixctl_cb_func *cb;
54     void *aux;
55 };
56
57 struct unixctl_conn {
58     struct list node;
59     int fd;
60
61     enum { S_RECV, S_PROCESS, S_SEND } state;
62     struct ofpbuf in;
63     struct ds out;
64     size_t out_pos;
65 };
66
67 /* Server for control connection. */
68 struct unixctl_server {
69     char *path;
70     int fd;
71     struct list conns;
72 };
73
74 /* Client for control connection. */
75 struct unixctl_client {
76     char *connect_path;
77     char *bind_path;
78     FILE *stream;
79 };
80
81 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
82
83 static struct shash commands = SHASH_INITIALIZER(&commands);
84
85 static void
86 unixctl_help(struct unixctl_conn *conn, int argc OVS_UNUSED,
87              const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
88 {
89     struct ds ds = DS_EMPTY_INITIALIZER;
90     const struct shash_node **nodes = shash_sort(&commands);
91     size_t i;
92
93     ds_put_cstr(&ds, "The available commands are:\n");
94
95     for (i = 0; i < shash_count(&commands); i++) {
96         const struct shash_node *node = nodes[i];
97         const struct unixctl_command *command = node->data;
98         
99         ds_put_format(&ds, "  %-23s %s\n", node->name, command->usage);
100     }
101     free(nodes);
102
103     unixctl_command_reply(conn, 214, ds_cstr(&ds));
104     ds_destroy(&ds);
105 }
106
107 static void
108 unixctl_version(struct unixctl_conn *conn, int argc OVS_UNUSED,
109                 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
110 {
111     unixctl_command_reply(conn, 200, get_program_version());
112 }
113
114 /* Registers a unixctl command with the given 'name'.  'usage' describes the
115  * arguments to the command; it is used only for presentation to the user in
116  * "help" output.
117  *
118  * 'cb' is called when the command is received.  It is passed the actual set of
119  * arguments, as a text string, plus a copy of 'aux'.  Normally 'cb' should
120  * call unixctl_command_reply() before it returns, but if the command cannot be
121  * handled immediately then it can defer the reply until later.  A given
122  * connection can only process a single request at a time, so
123  * unixctl_command_reply() must be called eventually to avoid blocking that
124  * connection. */
125 void
126 unixctl_command_register(const char *name, const char *usage,
127                          int min_args, int max_args,
128                          unixctl_cb_func *cb, void *aux)
129 {
130     struct unixctl_command *command;
131     struct unixctl_command *lookup = shash_find_data(&commands, name);
132
133     assert(!lookup || lookup->cb == cb);
134
135     if (lookup) {
136         return;
137     }
138
139     command = xmalloc(sizeof *command);
140     command->usage = usage;
141     command->min_args = min_args;
142     command->max_args = max_args;
143     command->cb = cb;
144     command->aux = aux;
145     shash_add(&commands, name, command);
146 }
147
148 static const char *
149 translate_reply_code(int code)
150 {
151     switch (code) {
152     case 200: return "OK";
153     case 201: return "Created";
154     case 202: return "Accepted";
155     case 204: return "No Content";
156     case 211: return "System Status";
157     case 214: return "Help";
158     case 400: return "Bad Request";
159     case 401: return "Unauthorized";
160     case 403: return "Forbidden";
161     case 404: return "Not Found";
162     case 500: return "Internal Server Error";
163     case 501: return "Invalid Argument";
164     case 503: return "Service Unavailable";
165     default: return "Unknown";
166     }
167 }
168
169 void
170 unixctl_command_reply(struct unixctl_conn *conn,
171                       int code, const char *body)
172 {
173     struct ds *out = &conn->out;
174
175     COVERAGE_INC(unixctl_replied);
176     assert(conn->state == S_PROCESS);
177     conn->state = S_SEND;
178     conn->out_pos = 0;
179
180     ds_clear(out);
181     ds_put_format(out, "%03d %s\n", code, translate_reply_code(code));
182     if (body) {
183         const char *p;
184         for (p = body; *p != '\0'; ) {
185             size_t n = strcspn(p, "\n");
186
187             if (*p == '.') {
188                 ds_put_char(out, '.');
189             }
190             ds_put_buffer(out, p, n);
191             ds_put_char(out, '\n');
192             p += n;
193             if (*p == '\n') {
194                 p++;
195             }
196         }
197     }
198     ds_put_cstr(out, ".\n");
199 }
200
201 /* Creates a unixctl server listening on 'path', which may be:
202  *
203  *      - NULL, in which case <rundir>/<program>.<pid>.ctl is used.
204  *
205  *      - "none", in which case the function will return successfully but
206  *        no socket will actually be created.
207  *
208  *      - A name that does not start with '/', in which case it is put in
209  *        <rundir>.
210  *
211  *      - An absolute path (starting with '/') that gives the exact name of
212  *        the Unix domain socket to listen on.
213  *
214  * A program that (optionally) daemonizes itself should call this function
215  * *after* daemonization, so that the socket name contains the pid of the
216  * daemon instead of the pid of the program that exited.  (Otherwise,
217  * "ovs-appctl --target=<program>" will fail.)
218  *
219  * Returns 0 if successful, otherwise a positive errno value.  If successful,
220  * sets '*serverp' to the new unixctl_server (or to NULL if 'path' was "none"),
221  * otherwise to NULL. */
222 int
223 unixctl_server_create(const char *path, struct unixctl_server **serverp)
224 {
225     struct unixctl_server *server;
226     int error;
227
228     if (path && !strcmp(path, "none")) {
229         *serverp = NULL;
230         return 0;
231     }
232
233     unixctl_command_register("help", "", 0, 0, unixctl_help, NULL);
234     unixctl_command_register("version", "", 0, 0, unixctl_version, NULL);
235
236     server = xmalloc(sizeof *server);
237     list_init(&server->conns);
238
239     if (path) {
240         server->path = abs_file_name(ovs_rundir(), path);
241     } else {
242         server->path = xasprintf("%s/%s.%ld.ctl", ovs_rundir(),
243                                  program_name, (long int) getpid());
244     }
245
246     server->fd = make_unix_socket(SOCK_STREAM, true, false, server->path,
247                                   NULL);
248     if (server->fd < 0) {
249         error = -server->fd;
250         ovs_error(error, "could not initialize control socket %s",
251                   server->path);
252         goto error;
253     }
254
255     if (chmod(server->path, S_IRUSR | S_IWUSR) < 0) {
256         error = errno;
257         ovs_error(error, "failed to chmod control socket %s", server->path);
258         goto error;
259     }
260
261     if (listen(server->fd, 10) < 0) {
262         error = errno;
263         ovs_error(error, "Failed to listen on control socket %s",
264                   server->path);
265         goto error;
266     }
267
268     *serverp = server;
269     return 0;
270
271 error:
272     if (server->fd >= 0) {
273         close(server->fd);
274     }
275     free(server->path);
276     free(server);
277     *serverp = NULL;
278     return error;
279 }
280
281 static void
282 new_connection(struct unixctl_server *server, int fd)
283 {
284     struct unixctl_conn *conn;
285
286     set_nonblocking(fd);
287
288     conn = xmalloc(sizeof *conn);
289     list_push_back(&server->conns, &conn->node);
290     conn->fd = fd;
291     conn->state = S_RECV;
292     ofpbuf_init(&conn->in, 128);
293     ds_init(&conn->out);
294     conn->out_pos = 0;
295 }
296
297 static int
298 run_connection_output(struct unixctl_conn *conn)
299 {
300     while (conn->out_pos < conn->out.length) {
301         size_t bytes_written;
302         int error;
303
304         error = write_fully(conn->fd, conn->out.string + conn->out_pos,
305                             conn->out.length - conn->out_pos, &bytes_written);
306         conn->out_pos += bytes_written;
307         if (error) {
308             return error;
309         }
310     }
311     conn->state = S_RECV;
312     return 0;
313 }
314
315 static void
316 process_command(struct unixctl_conn *conn, char *s)
317 {
318     struct unixctl_command *command;
319     struct svec argv;
320
321     COVERAGE_INC(unixctl_received);
322     conn->state = S_PROCESS;
323
324     svec_init(&argv);
325     svec_parse_words(&argv, s);
326     svec_terminate(&argv);
327
328     if (argv.n == 0) {
329         unixctl_command_reply(conn, 400, "missing command name in request");
330     } else {
331         const char *name = argv.names[0];
332         char *error;
333
334         command = shash_find_data(&commands, name);
335         if (!command) {
336             error = xasprintf("\"%s\" is not a valid command", name);
337         } else if (argv.n - 1 < command->min_args) {
338             error = xasprintf("\"%s\" command requires at least %d arguments",
339                               name, command->min_args);
340         } else if (argv.n - 1 > command->max_args) {
341             error = xasprintf("\"%s\" command takes at most %d arguments",
342                               name, command->max_args);
343         } else {
344             error = NULL;
345             command->cb(conn, argv.n, (const char **) argv.names,
346                         command->aux);
347         }
348
349         if (error) {
350             unixctl_command_reply(conn, 400, error);
351             free(error);
352         }
353     }
354
355     svec_destroy(&argv);
356 }
357
358 static int
359 run_connection_input(struct unixctl_conn *conn)
360 {
361     for (;;) {
362         size_t bytes_read;
363         char *newline;
364         int error;
365
366         newline = memchr(conn->in.data, '\n', conn->in.size);
367         if (newline) {
368             char *command = conn->in.data;
369             size_t n = newline - command + 1;
370
371             if (n > 0 && newline[-1] == '\r') {
372                 newline--;
373             }
374             *newline = '\0';
375
376             process_command(conn, command);
377
378             ofpbuf_pull(&conn->in, n);
379             if (!conn->in.size) {
380                 ofpbuf_clear(&conn->in);
381             }
382             return 0;
383         }
384
385         ofpbuf_prealloc_tailroom(&conn->in, 128);
386         error = read_fully(conn->fd, ofpbuf_tail(&conn->in),
387                            ofpbuf_tailroom(&conn->in), &bytes_read);
388         conn->in.size += bytes_read;
389         if (conn->in.size > 65536) {
390             VLOG_WARN_RL(&rl, "excess command length, killing connection");
391             return EPROTO;
392         }
393         if (error) {
394             if (error == EAGAIN || error == EWOULDBLOCK) {
395                 if (!bytes_read) {
396                     return EAGAIN;
397                 }
398             } else {
399                 if (error != EOF || conn->in.size != 0) {
400                     VLOG_WARN_RL(&rl, "read failed: %s",
401                                  (error == EOF
402                                   ? "connection dropped mid-command"
403                                   : strerror(error)));
404                 }
405                 return error;
406             }
407         }
408     }
409 }
410
411 static int
412 run_connection(struct unixctl_conn *conn)
413 {
414     int old_state;
415     do {
416         int error;
417
418         old_state = conn->state;
419         switch (conn->state) {
420         case S_RECV:
421             error = run_connection_input(conn);
422             break;
423
424         case S_PROCESS:
425             error = 0;
426             break;
427
428         case S_SEND:
429             error = run_connection_output(conn);
430             break;
431
432         default:
433             NOT_REACHED();
434         }
435         if (error) {
436             return error;
437         }
438     } while (conn->state != old_state);
439     return 0;
440 }
441
442 static void
443 kill_connection(struct unixctl_conn *conn)
444 {
445     list_remove(&conn->node);
446     ofpbuf_uninit(&conn->in);
447     ds_destroy(&conn->out);
448     close(conn->fd);
449     free(conn);
450 }
451
452 void
453 unixctl_server_run(struct unixctl_server *server)
454 {
455     struct unixctl_conn *conn, *next;
456     int i;
457
458     if (!server) {
459         return;
460     }
461
462     for (i = 0; i < 10; i++) {
463         int fd = accept(server->fd, NULL, NULL);
464         if (fd < 0) {
465             if (errno != EAGAIN && errno != EWOULDBLOCK) {
466                 VLOG_WARN_RL(&rl, "accept failed: %s", strerror(errno));
467             }
468             break;
469         }
470         new_connection(server, fd);
471     }
472
473     LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
474         int error = run_connection(conn);
475         if (error && error != EAGAIN) {
476             kill_connection(conn);
477         }
478     }
479 }
480
481 void
482 unixctl_server_wait(struct unixctl_server *server)
483 {
484     struct unixctl_conn *conn;
485
486     if (!server) {
487         return;
488     }
489
490     poll_fd_wait(server->fd, POLLIN);
491     LIST_FOR_EACH (conn, node, &server->conns) {
492         if (conn->state == S_RECV) {
493             poll_fd_wait(conn->fd, POLLIN);
494         } else if (conn->state == S_SEND) {
495             poll_fd_wait(conn->fd, POLLOUT);
496         }
497     }
498 }
499
500 /* Destroys 'server' and stops listening for connections. */
501 void
502 unixctl_server_destroy(struct unixctl_server *server)
503 {
504     if (server) {
505         struct unixctl_conn *conn, *next;
506
507         LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
508             kill_connection(conn);
509         }
510
511         close(server->fd);
512         fatal_signal_unlink_file_now(server->path);
513         free(server->path);
514         free(server);
515     }
516 }
517 \f
518 /* Connects to a Vlog server socket.  'path' should be the name of a Vlog
519  * server socket.  If it does not start with '/', it will be prefixed with
520  * the rundir (e.g. /usr/local/var/run/openvswitch).
521  *
522  * Returns 0 if successful, otherwise a positive errno value.  If successful,
523  * sets '*clientp' to the new unixctl_client, otherwise to NULL. */
524 int
525 unixctl_client_create(const char *path, struct unixctl_client **clientp)
526 {
527     static int counter;
528     struct unixctl_client *client;
529     int error;
530     int fd = -1;
531
532     /* Determine location. */
533     client = xmalloc(sizeof *client);
534     client->connect_path = abs_file_name(ovs_rundir(), path);
535     client->bind_path = xasprintf("/tmp/vlog.%ld.%d",
536                                   (long int) getpid(), counter++);
537
538     /* Open socket. */
539     fd = make_unix_socket(SOCK_STREAM, false, false,
540                           client->bind_path, client->connect_path);
541     if (fd < 0) {
542         error = -fd;
543         goto error;
544     }
545
546     /* Bind socket to stream. */
547     client->stream = fdopen(fd, "r+");
548     if (!client->stream) {
549         error = errno;
550         VLOG_WARN("%s: fdopen failed (%s)",
551                   client->connect_path, strerror(error));
552         goto error;
553     }
554     *clientp = client;
555     return 0;
556
557 error:
558     if (fd >= 0) {
559         close(fd);
560     }
561     free(client->connect_path);
562     free(client->bind_path);
563     free(client);
564     *clientp = NULL;
565     return error;
566 }
567
568 /* Destroys 'client'. */
569 void
570 unixctl_client_destroy(struct unixctl_client *client)
571 {
572     if (client) {
573         fatal_signal_unlink_file_now(client->bind_path);
574         free(client->bind_path);
575         free(client->connect_path);
576         fclose(client->stream);
577         free(client);
578     }
579 }
580
581 /* Sends 'request' to the server socket and waits for a reply.  Returns 0 if
582  * successful, otherwise to a positive errno value.  If successful, sets
583  * '*reply' to the reply, which the caller must free, otherwise to NULL. */
584 int
585 unixctl_client_transact(struct unixctl_client *client,
586                         const char *request,
587                         int *reply_code, char **reply_body)
588 {
589     struct ds line = DS_EMPTY_INITIALIZER;
590     struct ds reply = DS_EMPTY_INITIALIZER;
591     int error;
592
593     /* Send 'request' to server.  Add a new-line if 'request' didn't end in
594      * one. */
595     fputs(request, client->stream);
596     if (request[0] == '\0' || request[strlen(request) - 1] != '\n') {
597         putc('\n', client->stream);
598     }
599     if (ferror(client->stream)) {
600         VLOG_WARN("error sending request to %s: %s",
601                   client->connect_path, strerror(errno));
602         return errno;
603     }
604
605     /* Wait for response. */
606     *reply_code = -1;
607     for (;;) {
608         const char *s;
609
610         error = ds_get_line(&line, client->stream);
611         if (error) {
612             VLOG_WARN("error reading reply from %s: %s",
613                       client->connect_path,
614                       ovs_retval_to_string(error));
615             goto error;
616         }
617
618         s = ds_cstr(&line);
619         if (*reply_code == -1) {
620             if (!isdigit((unsigned char)s[0])
621                     || !isdigit((unsigned char)s[1])
622                     || !isdigit((unsigned char)s[2])) {
623                 VLOG_WARN("reply from %s does not start with 3-digit code",
624                           client->connect_path);
625                 error = EPROTO;
626                 goto error;
627             }
628             sscanf(s, "%3d", reply_code);
629         } else {
630             if (s[0] == '.') {
631                 if (s[1] == '\0') {
632                     break;
633                 }
634                 s++;
635             }
636             ds_put_cstr(&reply, s);
637             ds_put_char(&reply, '\n');
638         }
639     }
640     *reply_body = ds_cstr(&reply);
641     ds_destroy(&line);
642     return 0;
643
644 error:
645     ds_destroy(&line);
646     ds_destroy(&reply);
647     *reply_code = 0;
648     *reply_body = NULL;
649     return error == EOF ? EPROTO : error;
650 }
651
652 /* Returns the path of the server socket to which 'client' is connected.  The
653  * caller must not modify or free the returned string. */
654 const char *
655 unixctl_client_target(const struct unixctl_client *client)
656 {
657     return client->connect_path;
658 }