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;
118 struct unixctl_command *lookup = shash_find_data(&commands, name);
120 assert(!lookup || lookup->cb == cb);
126 command = xmalloc(sizeof *command);
127 command->args = args;
130 shash_add(&commands, name, command);
134 translate_reply_code(int code)
137 case 200: return "OK";
138 case 201: return "Created";
139 case 202: return "Accepted";
140 case 204: return "No Content";
141 case 211: return "System Status";
142 case 214: return "Help";
143 case 400: return "Bad Request";
144 case 401: return "Unauthorized";
145 case 403: return "Forbidden";
146 case 404: return "Not Found";
147 case 500: return "Internal Server Error";
148 case 501: return "Invalid Argument";
149 case 503: return "Service Unavailable";
150 default: return "Unknown";
155 unixctl_command_reply(struct unixctl_conn *conn,
156 int code, const char *body)
158 struct ds *out = &conn->out;
160 COVERAGE_INC(unixctl_replied);
161 assert(conn->state == S_PROCESS);
162 conn->state = S_SEND;
166 ds_put_format(out, "%03d %s\n", code, translate_reply_code(code));
169 for (p = body; *p != '\0'; ) {
170 size_t n = strcspn(p, "\n");
173 ds_put_char(out, '.');
175 ds_put_buffer(out, p, n);
176 ds_put_char(out, '\n');
183 ds_put_cstr(out, ".\n");
186 /* Creates a unixctl server listening on 'path', which may be:
188 * - NULL, in which case <rundir>/<program>.<pid>.ctl is used.
190 * - "none", in which case the function will return successfully but
191 * no socket will actually be created.
193 * - A name that does not start with '/', in which case it is put in
196 * - An absolute path (starting with '/') that gives the exact name of
197 * the Unix domain socket to listen on.
199 * A program that (optionally) daemonizes itself should call this function
200 * *after* daemonization, so that the socket name contains the pid of the
201 * daemon instead of the pid of the program that exited. (Otherwise,
202 * "ovs-appctl --target=<program>" will fail.)
204 * Returns 0 if successful, otherwise a positive errno value. If successful,
205 * sets '*serverp' to the new unixctl_server (or to NULL if 'path' was "none"),
206 * otherwise to NULL. */
208 unixctl_server_create(const char *path, struct unixctl_server **serverp)
210 struct unixctl_server *server;
213 if (path && !strcmp(path, "none")) {
218 unixctl_command_register("help", "", unixctl_help, NULL);
219 unixctl_command_register("version", "", unixctl_version, NULL);
221 server = xmalloc(sizeof *server);
222 list_init(&server->conns);
225 server->path = abs_file_name(ovs_rundir(), path);
227 server->path = xasprintf("%s/%s.%ld.ctl", ovs_rundir(),
228 program_name, (long int) getpid());
231 server->fd = make_unix_socket(SOCK_STREAM, true, false, server->path,
233 if (server->fd < 0) {
235 ovs_error(error, "could not initialize control socket %s",
240 if (chmod(server->path, S_IRUSR | S_IWUSR) < 0) {
242 ovs_error(error, "failed to chmod control socket %s", server->path);
246 if (listen(server->fd, 10) < 0) {
248 ovs_error(error, "Failed to listen on control socket %s",
257 if (server->fd >= 0) {
267 new_connection(struct unixctl_server *server, int fd)
269 struct unixctl_conn *conn;
273 conn = xmalloc(sizeof *conn);
274 list_push_back(&server->conns, &conn->node);
276 conn->state = S_RECV;
277 ofpbuf_init(&conn->in, 128);
283 run_connection_output(struct unixctl_conn *conn)
285 while (conn->out_pos < conn->out.length) {
286 size_t bytes_written;
289 error = write_fully(conn->fd, conn->out.string + conn->out_pos,
290 conn->out.length - conn->out_pos, &bytes_written);
291 conn->out_pos += bytes_written;
296 conn->state = S_RECV;
301 process_command(struct unixctl_conn *conn, char *s)
303 struct unixctl_command *command;
307 COVERAGE_INC(unixctl_received);
308 conn->state = S_PROCESS;
311 name_len = strcspn(name, " ");
312 args = name + name_len;
313 args += strspn(args, " ");
314 name[name_len] = '\0';
316 command = shash_find_data(&commands, name);
318 command->cb(conn, args, command->aux);
320 char *msg = xasprintf("\"%s\" is not a valid command", name);
321 unixctl_command_reply(conn, 400, msg);
327 run_connection_input(struct unixctl_conn *conn)
334 newline = memchr(conn->in.data, '\n', conn->in.size);
336 char *command = conn->in.data;
337 size_t n = newline - command + 1;
339 if (n > 0 && newline[-1] == '\r') {
344 process_command(conn, command);
346 ofpbuf_pull(&conn->in, n);
347 if (!conn->in.size) {
348 ofpbuf_clear(&conn->in);
353 ofpbuf_prealloc_tailroom(&conn->in, 128);
354 error = read_fully(conn->fd, ofpbuf_tail(&conn->in),
355 ofpbuf_tailroom(&conn->in), &bytes_read);
356 conn->in.size += bytes_read;
357 if (conn->in.size > 65536) {
358 VLOG_WARN_RL(&rl, "excess command length, killing connection");
362 if (error == EAGAIN || error == EWOULDBLOCK) {
367 if (error != EOF || conn->in.size != 0) {
368 VLOG_WARN_RL(&rl, "read failed: %s",
370 ? "connection dropped mid-command"
380 run_connection(struct unixctl_conn *conn)
386 old_state = conn->state;
387 switch (conn->state) {
389 error = run_connection_input(conn);
397 error = run_connection_output(conn);
406 } while (conn->state != old_state);
411 kill_connection(struct unixctl_conn *conn)
413 list_remove(&conn->node);
414 ofpbuf_uninit(&conn->in);
415 ds_destroy(&conn->out);
421 unixctl_server_run(struct unixctl_server *server)
423 struct unixctl_conn *conn, *next;
430 for (i = 0; i < 10; i++) {
431 int fd = accept(server->fd, NULL, NULL);
433 if (errno != EAGAIN && errno != EWOULDBLOCK) {
434 VLOG_WARN_RL(&rl, "accept failed: %s", strerror(errno));
438 new_connection(server, fd);
441 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
442 int error = run_connection(conn);
443 if (error && error != EAGAIN) {
444 kill_connection(conn);
450 unixctl_server_wait(struct unixctl_server *server)
452 struct unixctl_conn *conn;
458 poll_fd_wait(server->fd, POLLIN);
459 LIST_FOR_EACH (conn, node, &server->conns) {
460 if (conn->state == S_RECV) {
461 poll_fd_wait(conn->fd, POLLIN);
462 } else if (conn->state == S_SEND) {
463 poll_fd_wait(conn->fd, POLLOUT);
468 /* Destroys 'server' and stops listening for connections. */
470 unixctl_server_destroy(struct unixctl_server *server)
473 struct unixctl_conn *conn, *next;
475 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
476 kill_connection(conn);
480 fatal_signal_unlink_file_now(server->path);
486 /* Connects to a Vlog server socket. 'path' should be the name of a Vlog
487 * server socket. If it does not start with '/', it will be prefixed with
488 * the rundir (e.g. /usr/local/var/run/openvswitch).
490 * Returns 0 if successful, otherwise a positive errno value. If successful,
491 * sets '*clientp' to the new unixctl_client, otherwise to NULL. */
493 unixctl_client_create(const char *path, struct unixctl_client **clientp)
496 struct unixctl_client *client;
500 /* Determine location. */
501 client = xmalloc(sizeof *client);
502 client->connect_path = abs_file_name(ovs_rundir(), path);
503 client->bind_path = xasprintf("/tmp/vlog.%ld.%d",
504 (long int) getpid(), counter++);
507 fd = make_unix_socket(SOCK_STREAM, false, false,
508 client->bind_path, client->connect_path);
514 /* Bind socket to stream. */
515 client->stream = fdopen(fd, "r+");
516 if (!client->stream) {
518 VLOG_WARN("%s: fdopen failed (%s)",
519 client->connect_path, strerror(error));
529 free(client->connect_path);
530 free(client->bind_path);
536 /* Destroys 'client'. */
538 unixctl_client_destroy(struct unixctl_client *client)
541 fatal_signal_unlink_file_now(client->bind_path);
542 free(client->bind_path);
543 free(client->connect_path);
544 fclose(client->stream);
549 /* Sends 'request' to the server socket and waits for a reply. Returns 0 if
550 * successful, otherwise to a positive errno value. If successful, sets
551 * '*reply' to the reply, which the caller must free, otherwise to NULL. */
553 unixctl_client_transact(struct unixctl_client *client,
555 int *reply_code, char **reply_body)
557 struct ds line = DS_EMPTY_INITIALIZER;
558 struct ds reply = DS_EMPTY_INITIALIZER;
561 /* Send 'request' to server. Add a new-line if 'request' didn't end in
563 fputs(request, client->stream);
564 if (request[0] == '\0' || request[strlen(request) - 1] != '\n') {
565 putc('\n', client->stream);
567 if (ferror(client->stream)) {
568 VLOG_WARN("error sending request to %s: %s",
569 client->connect_path, strerror(errno));
573 /* Wait for response. */
578 error = ds_get_line(&line, client->stream);
580 VLOG_WARN("error reading reply from %s: %s",
581 client->connect_path,
582 ovs_retval_to_string(error));
587 if (*reply_code == -1) {
588 if (!isdigit((unsigned char)s[0])
589 || !isdigit((unsigned char)s[1])
590 || !isdigit((unsigned char)s[2])) {
591 VLOG_WARN("reply from %s does not start with 3-digit code",
592 client->connect_path);
596 sscanf(s, "%3d", reply_code);
604 ds_put_cstr(&reply, s);
605 ds_put_char(&reply, '\n');
608 *reply_body = ds_cstr(&reply);
617 return error == EOF ? EPROTO : error;
620 /* Returns the path of the server socket to which 'client' is connected. The
621 * caller must not modify or free the returned string. */
623 unixctl_client_target(const struct unixctl_client *client)
625 return client->connect_path;