]> git.proxmox.com Git - ovs.git/blob - lib/unixctl.c
vlog: Make client supply semicolon for VLOG_DEFINE_THIS_MODULE.
[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, node, &server->conns) {
415 int error = run_connection(conn);
416 if (error && error != EAGAIN) {
417 kill_connection(conn);
418 }
419 }
420 }
421
422 void
423 unixctl_server_wait(struct unixctl_server *server)
424 {
425 struct unixctl_conn *conn;
426
427 poll_fd_wait(server->fd, POLLIN);
428 LIST_FOR_EACH (conn, node, &server->conns) {
429 if (conn->state == S_RECV) {
430 poll_fd_wait(conn->fd, POLLIN);
431 } else if (conn->state == S_SEND) {
432 poll_fd_wait(conn->fd, POLLOUT);
433 }
434 }
435 }
436
437 /* Destroys 'server' and stops listening for connections. */
438 void
439 unixctl_server_destroy(struct unixctl_server *server)
440 {
441 if (server) {
442 struct unixctl_conn *conn, *next;
443
444 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
445 kill_connection(conn);
446 }
447
448 close(server->fd);
449 fatal_signal_unlink_file_now(server->path);
450 free(server->path);
451 free(server);
452 }
453 }
454 \f
455 /* Connects to a Vlog server socket. 'path' should be the name of a Vlog
456 * server socket. If it does not start with '/', it will be prefixed with
457 * ovs_rundir (e.g. /var/run/openvswitch).
458 *
459 * Returns 0 if successful, otherwise a positive errno value. If successful,
460 * sets '*clientp' to the new unixctl_client, otherwise to NULL. */
461 int
462 unixctl_client_create(const char *path, struct unixctl_client **clientp)
463 {
464 static int counter;
465 struct unixctl_client *client;
466 int error;
467 int fd = -1;
468
469 /* Determine location. */
470 client = xmalloc(sizeof *client);
471 client->connect_path = abs_file_name(ovs_rundir, path);
472 client->bind_path = xasprintf("/tmp/vlog.%ld.%d",
473 (long int) getpid(), counter++);
474
475 /* Open socket. */
476 fd = make_unix_socket(SOCK_STREAM, false, false,
477 client->bind_path, client->connect_path);
478 if (fd < 0) {
479 error = -fd;
480 goto error;
481 }
482
483 /* Bind socket to stream. */
484 client->stream = fdopen(fd, "r+");
485 if (!client->stream) {
486 error = errno;
487 VLOG_WARN("%s: fdopen failed (%s)",
488 client->connect_path, strerror(error));
489 goto error;
490 }
491 *clientp = client;
492 return 0;
493
494 error:
495 if (fd >= 0) {
496 close(fd);
497 }
498 free(client->connect_path);
499 free(client->bind_path);
500 free(client);
501 *clientp = NULL;
502 return error;
503 }
504
505 /* Destroys 'client'. */
506 void
507 unixctl_client_destroy(struct unixctl_client *client)
508 {
509 if (client) {
510 fatal_signal_unlink_file_now(client->bind_path);
511 free(client->bind_path);
512 free(client->connect_path);
513 fclose(client->stream);
514 free(client);
515 }
516 }
517
518 /* Sends 'request' to the server socket and waits for a reply. Returns 0 if
519 * successful, otherwise to a positive errno value. If successful, sets
520 * '*reply' to the reply, which the caller must free, otherwise to NULL. */
521 int
522 unixctl_client_transact(struct unixctl_client *client,
523 const char *request,
524 int *reply_code, char **reply_body)
525 {
526 struct ds line = DS_EMPTY_INITIALIZER;
527 struct ds reply = DS_EMPTY_INITIALIZER;
528 int error;
529
530 /* Send 'request' to server. Add a new-line if 'request' didn't end in
531 * one. */
532 fputs(request, client->stream);
533 if (request[0] == '\0' || request[strlen(request) - 1] != '\n') {
534 putc('\n', client->stream);
535 }
536 if (ferror(client->stream)) {
537 VLOG_WARN("error sending request to %s: %s",
538 client->connect_path, strerror(errno));
539 return errno;
540 }
541
542 /* Wait for response. */
543 *reply_code = -1;
544 for (;;) {
545 const char *s;
546
547 error = ds_get_line(&line, client->stream);
548 if (error) {
549 VLOG_WARN("error reading reply from %s: %s",
550 client->connect_path,
551 (error == EOF ? "unexpected end of file"
552 : strerror(error)));
553 goto error;
554 }
555
556 s = ds_cstr(&line);
557 if (*reply_code == -1) {
558 if (!isdigit((unsigned char)s[0])
559 || !isdigit((unsigned char)s[1])
560 || !isdigit((unsigned char)s[2])) {
561 VLOG_WARN("reply from %s does not start with 3-digit code",
562 client->connect_path);
563 error = EPROTO;
564 goto error;
565 }
566 sscanf(s, "%3d", reply_code);
567 } else {
568 if (s[0] == '.') {
569 if (s[1] == '\0') {
570 break;
571 }
572 s++;
573 }
574 ds_put_cstr(&reply, s);
575 ds_put_char(&reply, '\n');
576 }
577 }
578 *reply_body = ds_cstr(&reply);
579 ds_destroy(&line);
580 return 0;
581
582 error:
583 ds_destroy(&line);
584 ds_destroy(&reply);
585 *reply_code = 0;
586 *reply_body = NULL;
587 return error == EOF ? EPROTO : error;
588 }
589
590 /* Returns the path of the server socket to which 'client' is connected. The
591 * caller must not modify or free the returned string. */
592 const char *
593 unixctl_client_target(const struct unixctl_client *client)
594 {
595 return client->connect_path;
596 }