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