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