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 {
60 enum { S_RECV, S_PROCESS, S_SEND } state;
66 /* Server for control connection. */
67 struct unixctl_server {
73 /* Client for control connection. */
74 struct unixctl_client {
80 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
82 static struct shash commands = SHASH_INITIALIZER(&commands);
85 unixctl_help(struct unixctl_conn *conn, const char *args OVS_UNUSED,
88 struct ds ds = DS_EMPTY_INITIALIZER;
89 const struct shash_node **nodes = shash_sort(&commands);
92 ds_put_cstr(&ds, "The available commands are:\n");
94 for (i = 0; i < shash_count(&commands); i++) {
95 const struct shash_node *node = nodes[i];
96 const struct unixctl_command *command = node->data;
98 ds_put_format(&ds, " %-23s%s\n", node->name, command->args);
102 unixctl_command_reply(conn, 214, ds_cstr(&ds));
107 unixctl_version(struct unixctl_conn *conn, const char *args OVS_UNUSED,
108 void *aux OVS_UNUSED)
110 unixctl_command_reply(conn, 200, get_program_version());
114 unixctl_command_register(const char *name, const char *args,
115 unixctl_cb_func *cb, void *aux)
117 struct unixctl_command *command;
119 assert(!shash_find_data(&commands, name)
120 || shash_find_data(&commands, name) == cb);
121 command = xmalloc(sizeof *command);
122 command->args = args;
125 shash_add(&commands, name, command);
129 translate_reply_code(int code)
132 case 200: return "OK";
133 case 201: return "Created";
134 case 202: return "Accepted";
135 case 204: return "No Content";
136 case 211: return "System Status";
137 case 214: return "Help";
138 case 400: return "Bad Request";
139 case 401: return "Unauthorized";
140 case 403: return "Forbidden";
141 case 404: return "Not Found";
142 case 500: return "Internal Server Error";
143 case 501: return "Invalid Argument";
144 case 503: return "Service Unavailable";
145 default: return "Unknown";
150 unixctl_command_reply(struct unixctl_conn *conn,
151 int code, const char *body)
153 struct ds *out = &conn->out;
155 COVERAGE_INC(unixctl_replied);
156 assert(conn->state == S_PROCESS);
157 conn->state = S_SEND;
161 ds_put_format(out, "%03d %s\n", code, translate_reply_code(code));
164 for (p = body; *p != '\0'; ) {
165 size_t n = strcspn(p, "\n");
168 ds_put_char(out, '.');
170 ds_put_buffer(out, p, n);
171 ds_put_char(out, '\n');
178 ds_put_cstr(out, ".\n");
181 /* Creates a unixctl server listening on 'path', which may be:
183 * - NULL, in which case <rundir>/<program>.<pid>.ctl is used.
185 * - "none", in which case the function will return successfully but
186 * no socket will actually be created.
188 * - A name that does not start with '/', in which case it is put in
191 * - An absolute path (starting with '/') that gives the exact name of
192 * the Unix domain socket to listen on.
194 * A program that (optionally) daemonizes itself should call this function
195 * *after* daemonization, so that the socket name contains the pid of the
196 * daemon instead of the pid of the program that exited. (Otherwise,
197 * "ovs-appctl --target=<program>" will fail.)
199 * Returns 0 if successful, otherwise a positive errno value. If successful,
200 * sets '*serverp' to the new unixctl_server (or to NULL if 'path' was "none"),
201 * otherwise to NULL. */
203 unixctl_server_create(const char *path, struct unixctl_server **serverp)
205 struct unixctl_server *server;
208 if (path && !strcmp(path, "none")) {
213 unixctl_command_register("help", "", unixctl_help, NULL);
214 unixctl_command_register("version", "", unixctl_version, NULL);
216 server = xmalloc(sizeof *server);
217 list_init(&server->conns);
220 server->path = abs_file_name(ovs_rundir(), path);
222 server->path = xasprintf("%s/%s.%ld.ctl", ovs_rundir(),
223 program_name, (long int) getpid());
226 server->fd = make_unix_socket(SOCK_STREAM, true, false, server->path,
228 if (server->fd < 0) {
230 ovs_error(error, "could not initialize control socket %s",
235 if (chmod(server->path, S_IRUSR | S_IWUSR) < 0) {
237 ovs_error(error, "failed to chmod control socket %s", server->path);
241 if (listen(server->fd, 10) < 0) {
243 ovs_error(error, "Failed to listen on control socket %s",
252 if (server->fd >= 0) {
262 new_connection(struct unixctl_server *server, int fd)
264 struct unixctl_conn *conn;
268 conn = xmalloc(sizeof *conn);
269 list_push_back(&server->conns, &conn->node);
271 conn->state = S_RECV;
272 ofpbuf_init(&conn->in, 128);
278 run_connection_output(struct unixctl_conn *conn)
280 while (conn->out_pos < conn->out.length) {
281 size_t bytes_written;
284 error = write_fully(conn->fd, conn->out.string + conn->out_pos,
285 conn->out.length - conn->out_pos, &bytes_written);
286 conn->out_pos += bytes_written;
291 conn->state = S_RECV;
296 process_command(struct unixctl_conn *conn, char *s)
298 struct unixctl_command *command;
302 COVERAGE_INC(unixctl_received);
303 conn->state = S_PROCESS;
306 name_len = strcspn(name, " ");
307 args = name + name_len;
308 args += strspn(args, " ");
309 name[name_len] = '\0';
311 command = shash_find_data(&commands, name);
313 command->cb(conn, args, command->aux);
315 char *msg = xasprintf("\"%s\" is not a valid command", name);
316 unixctl_command_reply(conn, 400, msg);
322 run_connection_input(struct unixctl_conn *conn)
329 newline = memchr(conn->in.data, '\n', conn->in.size);
331 char *command = conn->in.data;
332 size_t n = newline - command + 1;
334 if (n > 0 && newline[-1] == '\r') {
339 process_command(conn, command);
341 ofpbuf_pull(&conn->in, n);
342 if (!conn->in.size) {
343 ofpbuf_clear(&conn->in);
348 ofpbuf_prealloc_tailroom(&conn->in, 128);
349 error = read_fully(conn->fd, ofpbuf_tail(&conn->in),
350 ofpbuf_tailroom(&conn->in), &bytes_read);
351 conn->in.size += bytes_read;
352 if (conn->in.size > 65536) {
353 VLOG_WARN_RL(&rl, "excess command length, killing connection");
357 if (error == EAGAIN || error == EWOULDBLOCK) {
362 if (error != EOF || conn->in.size != 0) {
363 VLOG_WARN_RL(&rl, "read failed: %s",
365 ? "connection dropped mid-command"
375 run_connection(struct unixctl_conn *conn)
381 old_state = conn->state;
382 switch (conn->state) {
384 error = run_connection_input(conn);
392 error = run_connection_output(conn);
401 } while (conn->state != old_state);
406 kill_connection(struct unixctl_conn *conn)
408 list_remove(&conn->node);
409 ofpbuf_uninit(&conn->in);
410 ds_destroy(&conn->out);
416 unixctl_server_run(struct unixctl_server *server)
418 struct unixctl_conn *conn, *next;
425 for (i = 0; i < 10; i++) {
426 int fd = accept(server->fd, NULL, NULL);
428 if (errno != EAGAIN && errno != EWOULDBLOCK) {
429 VLOG_WARN_RL(&rl, "accept failed: %s", strerror(errno));
433 new_connection(server, fd);
436 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
437 int error = run_connection(conn);
438 if (error && error != EAGAIN) {
439 kill_connection(conn);
445 unixctl_server_wait(struct unixctl_server *server)
447 struct unixctl_conn *conn;
453 poll_fd_wait(server->fd, POLLIN);
454 LIST_FOR_EACH (conn, node, &server->conns) {
455 if (conn->state == S_RECV) {
456 poll_fd_wait(conn->fd, POLLIN);
457 } else if (conn->state == S_SEND) {
458 poll_fd_wait(conn->fd, POLLOUT);
463 /* Destroys 'server' and stops listening for connections. */
465 unixctl_server_destroy(struct unixctl_server *server)
468 struct unixctl_conn *conn, *next;
470 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
471 kill_connection(conn);
475 fatal_signal_unlink_file_now(server->path);
481 /* Connects to a Vlog server socket. 'path' should be the name of a Vlog
482 * server socket. If it does not start with '/', it will be prefixed with
483 * the rundir (e.g. /usr/local/var/run/openvswitch).
485 * Returns 0 if successful, otherwise a positive errno value. If successful,
486 * sets '*clientp' to the new unixctl_client, otherwise to NULL. */
488 unixctl_client_create(const char *path, struct unixctl_client **clientp)
491 struct unixctl_client *client;
495 /* Determine location. */
496 client = xmalloc(sizeof *client);
497 client->connect_path = abs_file_name(ovs_rundir(), path);
498 client->bind_path = xasprintf("/tmp/vlog.%ld.%d",
499 (long int) getpid(), counter++);
502 fd = make_unix_socket(SOCK_STREAM, false, false,
503 client->bind_path, client->connect_path);
509 /* Bind socket to stream. */
510 client->stream = fdopen(fd, "r+");
511 if (!client->stream) {
513 VLOG_WARN("%s: fdopen failed (%s)",
514 client->connect_path, strerror(error));
524 free(client->connect_path);
525 free(client->bind_path);
531 /* Destroys 'client'. */
533 unixctl_client_destroy(struct unixctl_client *client)
536 fatal_signal_unlink_file_now(client->bind_path);
537 free(client->bind_path);
538 free(client->connect_path);
539 fclose(client->stream);
544 /* Sends 'request' to the server socket and waits for a reply. Returns 0 if
545 * successful, otherwise to a positive errno value. If successful, sets
546 * '*reply' to the reply, which the caller must free, otherwise to NULL. */
548 unixctl_client_transact(struct unixctl_client *client,
550 int *reply_code, char **reply_body)
552 struct ds line = DS_EMPTY_INITIALIZER;
553 struct ds reply = DS_EMPTY_INITIALIZER;
556 /* Send 'request' to server. Add a new-line if 'request' didn't end in
558 fputs(request, client->stream);
559 if (request[0] == '\0' || request[strlen(request) - 1] != '\n') {
560 putc('\n', client->stream);
562 if (ferror(client->stream)) {
563 VLOG_WARN("error sending request to %s: %s",
564 client->connect_path, strerror(errno));
568 /* Wait for response. */
573 error = ds_get_line(&line, client->stream);
575 VLOG_WARN("error reading reply from %s: %s",
576 client->connect_path,
577 ovs_retval_to_string(error));
582 if (*reply_code == -1) {
583 if (!isdigit((unsigned char)s[0])
584 || !isdigit((unsigned char)s[1])
585 || !isdigit((unsigned char)s[2])) {
586 VLOG_WARN("reply from %s does not start with 3-digit code",
587 client->connect_path);
591 sscanf(s, "%3d", reply_code);
599 ds_put_cstr(&reply, s);
600 ds_put_char(&reply, '\n');
603 *reply_body = ds_cstr(&reply);
612 return error == EOF ? EPROTO : error;
615 /* Returns the path of the server socket to which 'client' is connected. The
616 * caller must not modify or free the returned string. */
618 unixctl_client_target(const struct unixctl_client *client)
620 return client->connect_path;