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