2 * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
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:
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
25 #include <sys/socket.h>
30 #include "dynamic-string.h"
31 #include "fatal-signal.h"
34 #include "poll-loop.h"
36 #include "socket-util.h"
41 #ifndef SCM_CREDENTIALS
45 VLOG_DEFINE_THIS_MODULE(unixctl);
47 COVERAGE_DEFINE(unixctl_received);
48 COVERAGE_DEFINE(unixctl_replied);
50 struct unixctl_command {
52 int min_args, max_args;
61 enum { S_RECV, S_PROCESS, S_SEND } state;
67 /* Server for control connection. */
68 struct unixctl_server {
74 /* Client for control connection. */
75 struct unixctl_client {
81 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
83 static struct shash commands = SHASH_INITIALIZER(&commands);
86 unixctl_help(struct unixctl_conn *conn, int argc OVS_UNUSED,
87 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
89 struct ds ds = DS_EMPTY_INITIALIZER;
90 const struct shash_node **nodes = shash_sort(&commands);
93 ds_put_cstr(&ds, "The available commands are:\n");
95 for (i = 0; i < shash_count(&commands); i++) {
96 const struct shash_node *node = nodes[i];
97 const struct unixctl_command *command = node->data;
99 ds_put_format(&ds, " %-23s%s\n", node->name, command->usage);
103 unixctl_command_reply(conn, 214, ds_cstr(&ds));
108 unixctl_version(struct unixctl_conn *conn, int argc OVS_UNUSED,
109 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
111 unixctl_command_reply(conn, 200, get_program_version());
114 /* Registers a unixctl command with the given 'name'. 'usage' describes the
115 * arguments to the command; it is used only for presentation to the user in
118 * 'cb' is called when the command is received. It is passed the actual set of
119 * arguments, as a text string, plus a copy of 'aux'. Normally 'cb' should
120 * call unixctl_command_reply() before it returns, but if the command cannot be
121 * handled immediately then it can defer the reply until later. A given
122 * connection can only process a single request at a time, so
123 * unixctl_command_reply() must be called eventually to avoid blocking that
126 unixctl_command_register(const char *name, const char *usage,
127 int min_args, int max_args,
128 unixctl_cb_func *cb, void *aux)
130 struct unixctl_command *command;
131 struct unixctl_command *lookup = shash_find_data(&commands, name);
133 assert(!lookup || lookup->cb == cb);
139 command = xmalloc(sizeof *command);
140 command->usage = usage;
141 command->min_args = min_args;
142 command->max_args = max_args;
145 shash_add(&commands, name, command);
149 translate_reply_code(int code)
152 case 200: return "OK";
153 case 201: return "Created";
154 case 202: return "Accepted";
155 case 204: return "No Content";
156 case 211: return "System Status";
157 case 214: return "Help";
158 case 400: return "Bad Request";
159 case 401: return "Unauthorized";
160 case 403: return "Forbidden";
161 case 404: return "Not Found";
162 case 500: return "Internal Server Error";
163 case 501: return "Invalid Argument";
164 case 503: return "Service Unavailable";
165 default: return "Unknown";
170 unixctl_command_reply(struct unixctl_conn *conn,
171 int code, const char *body)
173 struct ds *out = &conn->out;
175 COVERAGE_INC(unixctl_replied);
176 assert(conn->state == S_PROCESS);
177 conn->state = S_SEND;
181 ds_put_format(out, "%03d %s\n", code, translate_reply_code(code));
184 for (p = body; *p != '\0'; ) {
185 size_t n = strcspn(p, "\n");
188 ds_put_char(out, '.');
190 ds_put_buffer(out, p, n);
191 ds_put_char(out, '\n');
198 ds_put_cstr(out, ".\n");
201 /* Creates a unixctl server listening on 'path', which may be:
203 * - NULL, in which case <rundir>/<program>.<pid>.ctl is used.
205 * - "none", in which case the function will return successfully but
206 * no socket will actually be created.
208 * - A name that does not start with '/', in which case it is put in
211 * - An absolute path (starting with '/') that gives the exact name of
212 * the Unix domain socket to listen on.
214 * A program that (optionally) daemonizes itself should call this function
215 * *after* daemonization, so that the socket name contains the pid of the
216 * daemon instead of the pid of the program that exited. (Otherwise,
217 * "ovs-appctl --target=<program>" will fail.)
219 * Returns 0 if successful, otherwise a positive errno value. If successful,
220 * sets '*serverp' to the new unixctl_server (or to NULL if 'path' was "none"),
221 * otherwise to NULL. */
223 unixctl_server_create(const char *path, struct unixctl_server **serverp)
225 struct unixctl_server *server;
228 if (path && !strcmp(path, "none")) {
233 unixctl_command_register("help", "", 0, 0, unixctl_help, NULL);
234 unixctl_command_register("version", "", 0, 0, unixctl_version, NULL);
236 server = xmalloc(sizeof *server);
237 list_init(&server->conns);
240 server->path = abs_file_name(ovs_rundir(), path);
242 server->path = xasprintf("%s/%s.%ld.ctl", ovs_rundir(),
243 program_name, (long int) getpid());
246 server->fd = make_unix_socket(SOCK_STREAM, true, false, server->path,
248 if (server->fd < 0) {
250 ovs_error(error, "could not initialize control socket %s",
255 if (chmod(server->path, S_IRUSR | S_IWUSR) < 0) {
257 ovs_error(error, "failed to chmod control socket %s", server->path);
261 if (listen(server->fd, 10) < 0) {
263 ovs_error(error, "Failed to listen on control socket %s",
272 if (server->fd >= 0) {
282 new_connection(struct unixctl_server *server, int fd)
284 struct unixctl_conn *conn;
288 conn = xmalloc(sizeof *conn);
289 list_push_back(&server->conns, &conn->node);
291 conn->state = S_RECV;
292 ofpbuf_init(&conn->in, 128);
298 run_connection_output(struct unixctl_conn *conn)
300 while (conn->out_pos < conn->out.length) {
301 size_t bytes_written;
304 error = write_fully(conn->fd, conn->out.string + conn->out_pos,
305 conn->out.length - conn->out_pos, &bytes_written);
306 conn->out_pos += bytes_written;
311 conn->state = S_RECV;
316 process_command(struct unixctl_conn *conn, char *s)
318 struct unixctl_command *command;
321 COVERAGE_INC(unixctl_received);
322 conn->state = S_PROCESS;
325 svec_parse_words(&argv, s);
326 svec_terminate(&argv);
329 unixctl_command_reply(conn, 400, "missing command name in request");
331 const char *name = argv.names[0];
334 command = shash_find_data(&commands, name);
336 error = xasprintf("\"%s\" is not a valid command", name);
337 } else if (argv.n - 1 < command->min_args) {
338 error = xasprintf("\"%s\" command requires at least %d arguments",
339 name, command->min_args);
340 } else if (argv.n - 1 > command->max_args) {
341 error = xasprintf("\"%s\" command takes at most %d arguments",
342 name, command->max_args);
345 command->cb(conn, argv.n, (const char **) argv.names,
350 unixctl_command_reply(conn, 400, error);
359 run_connection_input(struct unixctl_conn *conn)
366 newline = memchr(conn->in.data, '\n', conn->in.size);
368 char *command = conn->in.data;
369 size_t n = newline - command + 1;
371 if (n > 0 && newline[-1] == '\r') {
376 process_command(conn, command);
378 ofpbuf_pull(&conn->in, n);
379 if (!conn->in.size) {
380 ofpbuf_clear(&conn->in);
385 ofpbuf_prealloc_tailroom(&conn->in, 128);
386 error = read_fully(conn->fd, ofpbuf_tail(&conn->in),
387 ofpbuf_tailroom(&conn->in), &bytes_read);
388 conn->in.size += bytes_read;
389 if (conn->in.size > 65536) {
390 VLOG_WARN_RL(&rl, "excess command length, killing connection");
394 if (error == EAGAIN || error == EWOULDBLOCK) {
399 if (error != EOF || conn->in.size != 0) {
400 VLOG_WARN_RL(&rl, "read failed: %s",
402 ? "connection dropped mid-command"
412 run_connection(struct unixctl_conn *conn)
418 old_state = conn->state;
419 switch (conn->state) {
421 error = run_connection_input(conn);
429 error = run_connection_output(conn);
438 } while (conn->state != old_state);
443 kill_connection(struct unixctl_conn *conn)
445 list_remove(&conn->node);
446 ofpbuf_uninit(&conn->in);
447 ds_destroy(&conn->out);
453 unixctl_server_run(struct unixctl_server *server)
455 struct unixctl_conn *conn, *next;
462 for (i = 0; i < 10; i++) {
463 int fd = accept(server->fd, NULL, NULL);
465 if (errno != EAGAIN && errno != EWOULDBLOCK) {
466 VLOG_WARN_RL(&rl, "accept failed: %s", strerror(errno));
470 new_connection(server, fd);
473 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
474 int error = run_connection(conn);
475 if (error && error != EAGAIN) {
476 kill_connection(conn);
482 unixctl_server_wait(struct unixctl_server *server)
484 struct unixctl_conn *conn;
490 poll_fd_wait(server->fd, POLLIN);
491 LIST_FOR_EACH (conn, node, &server->conns) {
492 if (conn->state == S_RECV) {
493 poll_fd_wait(conn->fd, POLLIN);
494 } else if (conn->state == S_SEND) {
495 poll_fd_wait(conn->fd, POLLOUT);
500 /* Destroys 'server' and stops listening for connections. */
502 unixctl_server_destroy(struct unixctl_server *server)
505 struct unixctl_conn *conn, *next;
507 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
508 kill_connection(conn);
512 fatal_signal_unlink_file_now(server->path);
518 /* Connects to a Vlog server socket. 'path' should be the name of a Vlog
519 * server socket. If it does not start with '/', it will be prefixed with
520 * the rundir (e.g. /usr/local/var/run/openvswitch).
522 * Returns 0 if successful, otherwise a positive errno value. If successful,
523 * sets '*clientp' to the new unixctl_client, otherwise to NULL. */
525 unixctl_client_create(const char *path, struct unixctl_client **clientp)
528 struct unixctl_client *client;
532 /* Determine location. */
533 client = xmalloc(sizeof *client);
534 client->connect_path = abs_file_name(ovs_rundir(), path);
535 client->bind_path = xasprintf("/tmp/vlog.%ld.%d",
536 (long int) getpid(), counter++);
539 fd = make_unix_socket(SOCK_STREAM, false, false,
540 client->bind_path, client->connect_path);
546 /* Bind socket to stream. */
547 client->stream = fdopen(fd, "r+");
548 if (!client->stream) {
550 VLOG_WARN("%s: fdopen failed (%s)",
551 client->connect_path, strerror(error));
561 free(client->connect_path);
562 free(client->bind_path);
568 /* Destroys 'client'. */
570 unixctl_client_destroy(struct unixctl_client *client)
573 fatal_signal_unlink_file_now(client->bind_path);
574 free(client->bind_path);
575 free(client->connect_path);
576 fclose(client->stream);
581 /* Sends 'request' to the server socket and waits for a reply. Returns 0 if
582 * successful, otherwise to a positive errno value. If successful, sets
583 * '*reply' to the reply, which the caller must free, otherwise to NULL. */
585 unixctl_client_transact(struct unixctl_client *client,
587 int *reply_code, char **reply_body)
589 struct ds line = DS_EMPTY_INITIALIZER;
590 struct ds reply = DS_EMPTY_INITIALIZER;
593 /* Send 'request' to server. Add a new-line if 'request' didn't end in
595 fputs(request, client->stream);
596 if (request[0] == '\0' || request[strlen(request) - 1] != '\n') {
597 putc('\n', client->stream);
599 if (ferror(client->stream)) {
600 VLOG_WARN("error sending request to %s: %s",
601 client->connect_path, strerror(errno));
605 /* Wait for response. */
610 error = ds_get_line(&line, client->stream);
612 VLOG_WARN("error reading reply from %s: %s",
613 client->connect_path,
614 ovs_retval_to_string(error));
619 if (*reply_code == -1) {
620 if (!isdigit((unsigned char)s[0])
621 || !isdigit((unsigned char)s[1])
622 || !isdigit((unsigned char)s[2])) {
623 VLOG_WARN("reply from %s does not start with 3-digit code",
624 client->connect_path);
628 sscanf(s, "%3d", reply_code);
636 ds_put_cstr(&reply, s);
637 ds_put_char(&reply, '\n');
640 *reply_body = ds_cstr(&reply);
649 return error == EOF ? EPROTO : error;
652 /* Returns the path of the server socket to which 'client' is connected. The
653 * caller must not modify or free the returned string. */
655 unixctl_client_target(const struct unixctl_client *client)
657 return client->connect_path;