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