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