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