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