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 {
59 enum { S_RECV, S_PROCESS, S_SEND } state;
65 /* Server for control connection. */
66 struct unixctl_server {
72 /* Client for control connection. */
73 struct unixctl_client {
79 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
81 static struct shash commands = SHASH_INITIALIZER(&commands);
84 unixctl_help(struct unixctl_conn *conn, const char *args OVS_UNUSED,
87 struct ds ds = DS_EMPTY_INITIALIZER;
88 struct shash_node *node;
93 ds_put_cstr(&ds, "The available commands are:\n");
96 SHASH_FOR_EACH (node, &commands) {
97 svec_add(&names, node->name);
101 SVEC_FOR_EACH (i, name, &names) {
102 ds_put_format(&ds, "\t%s\n", name);
104 svec_destroy(&names);
106 unixctl_command_reply(conn, 214, ds_cstr(&ds));
111 unixctl_version(struct unixctl_conn *conn, const char *args OVS_UNUSED,
112 void *aux OVS_UNUSED)
114 unixctl_command_reply(conn, 200, get_program_version());
118 unixctl_command_register(const char *name, unixctl_cb_func *cb, void *aux)
120 struct unixctl_command *command;
122 assert(!shash_find_data(&commands, name)
123 || shash_find_data(&commands, name) == cb);
124 command = xmalloc(sizeof *command);
127 shash_add(&commands, name, command);
131 translate_reply_code(int code)
134 case 200: return "OK";
135 case 201: return "Created";
136 case 202: return "Accepted";
137 case 204: return "No Content";
138 case 211: return "System Status";
139 case 214: return "Help";
140 case 400: return "Bad Request";
141 case 401: return "Unauthorized";
142 case 403: return "Forbidden";
143 case 404: return "Not Found";
144 case 500: return "Internal Server Error";
145 case 501: return "Invalid Argument";
146 case 503: return "Service Unavailable";
147 default: return "Unknown";
152 unixctl_command_reply(struct unixctl_conn *conn,
153 int code, const char *body)
155 struct ds *out = &conn->out;
157 COVERAGE_INC(unixctl_replied);
158 assert(conn->state == S_PROCESS);
159 conn->state = S_SEND;
163 ds_put_format(out, "%03d %s\n", code, translate_reply_code(code));
166 for (p = body; *p != '\0'; ) {
167 size_t n = strcspn(p, "\n");
170 ds_put_char(out, '.');
172 ds_put_buffer(out, p, n);
173 ds_put_char(out, '\n');
180 ds_put_cstr(out, ".\n");
183 /* Creates a unixctl server listening on 'path', which may be:
185 * - NULL, in which case <rundir>/<program>.<pid>.ctl is used.
187 * - "none", in which case the function will return successfully but
188 * no socket will actually be created.
190 * - A name that does not start with '/', in which case it is put in
193 * - An absolute path (starting with '/') that gives the exact name of
194 * the Unix domain socket to listen on.
196 * A program that (optionally) daemonizes itself should call this function
197 * *after* daemonization, so that the socket name contains the pid of the
198 * daemon instead of the pid of the program that exited. (Otherwise,
199 * "ovs-appctl --target=<program>" will fail.)
201 * Returns 0 if successful, otherwise a positive errno value. If successful,
202 * sets '*serverp' to the new unixctl_server (or to NULL if 'path' was "none"),
203 * otherwise to NULL. */
205 unixctl_server_create(const char *path, struct unixctl_server **serverp)
207 struct unixctl_server *server;
210 if (path && !strcmp(path, "none")) {
215 unixctl_command_register("help", unixctl_help, NULL);
216 unixctl_command_register("version", unixctl_version, NULL);
218 server = xmalloc(sizeof *server);
219 list_init(&server->conns);
222 server->path = abs_file_name(ovs_rundir(), path);
224 server->path = xasprintf("%s/%s.%ld.ctl", ovs_rundir(),
225 program_name, (long int) getpid());
228 server->fd = make_unix_socket(SOCK_STREAM, true, false, server->path,
230 if (server->fd < 0) {
232 ovs_error(error, "could not initialize control socket %s",
237 if (chmod(server->path, S_IRUSR | S_IWUSR) < 0) {
239 ovs_error(error, "failed to chmod control socket %s", server->path);
243 if (listen(server->fd, 10) < 0) {
245 ovs_error(error, "Failed to listen on control socket %s",
254 if (server->fd >= 0) {
264 new_connection(struct unixctl_server *server, int fd)
266 struct unixctl_conn *conn;
270 conn = xmalloc(sizeof *conn);
271 list_push_back(&server->conns, &conn->node);
273 conn->state = S_RECV;
274 ofpbuf_init(&conn->in, 128);
280 run_connection_output(struct unixctl_conn *conn)
282 while (conn->out_pos < conn->out.length) {
283 size_t bytes_written;
286 error = write_fully(conn->fd, conn->out.string + conn->out_pos,
287 conn->out.length - conn->out_pos, &bytes_written);
288 conn->out_pos += bytes_written;
293 conn->state = S_RECV;
298 process_command(struct unixctl_conn *conn, char *s)
300 struct unixctl_command *command;
304 COVERAGE_INC(unixctl_received);
305 conn->state = S_PROCESS;
308 name_len = strcspn(name, " ");
309 args = name + name_len;
310 args += strspn(args, " ");
311 name[name_len] = '\0';
313 command = shash_find_data(&commands, name);
315 command->cb(conn, args, command->aux);
317 char *msg = xasprintf("\"%s\" is not a valid command", name);
318 unixctl_command_reply(conn, 400, msg);
324 run_connection_input(struct unixctl_conn *conn)
331 newline = memchr(conn->in.data, '\n', conn->in.size);
333 char *command = conn->in.data;
334 size_t n = newline - command + 1;
336 if (n > 0 && newline[-1] == '\r') {
341 process_command(conn, command);
343 ofpbuf_pull(&conn->in, n);
344 if (!conn->in.size) {
345 ofpbuf_clear(&conn->in);
350 ofpbuf_prealloc_tailroom(&conn->in, 128);
351 error = read_fully(conn->fd, ofpbuf_tail(&conn->in),
352 ofpbuf_tailroom(&conn->in), &bytes_read);
353 conn->in.size += bytes_read;
354 if (conn->in.size > 65536) {
355 VLOG_WARN_RL(&rl, "excess command length, killing connection");
359 if (error == EAGAIN || error == EWOULDBLOCK) {
364 if (error != EOF || conn->in.size != 0) {
365 VLOG_WARN_RL(&rl, "read failed: %s",
367 ? "connection dropped mid-command"
377 run_connection(struct unixctl_conn *conn)
383 old_state = conn->state;
384 switch (conn->state) {
386 error = run_connection_input(conn);
394 error = run_connection_output(conn);
403 } while (conn->state != old_state);
408 kill_connection(struct unixctl_conn *conn)
410 list_remove(&conn->node);
411 ofpbuf_uninit(&conn->in);
412 ds_destroy(&conn->out);
418 unixctl_server_run(struct unixctl_server *server)
420 struct unixctl_conn *conn, *next;
427 for (i = 0; i < 10; i++) {
428 int fd = accept(server->fd, NULL, NULL);
430 if (errno != EAGAIN && errno != EWOULDBLOCK) {
431 VLOG_WARN_RL(&rl, "accept failed: %s", strerror(errno));
435 new_connection(server, fd);
438 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
439 int error = run_connection(conn);
440 if (error && error != EAGAIN) {
441 kill_connection(conn);
447 unixctl_server_wait(struct unixctl_server *server)
449 struct unixctl_conn *conn;
455 poll_fd_wait(server->fd, POLLIN);
456 LIST_FOR_EACH (conn, node, &server->conns) {
457 if (conn->state == S_RECV) {
458 poll_fd_wait(conn->fd, POLLIN);
459 } else if (conn->state == S_SEND) {
460 poll_fd_wait(conn->fd, POLLOUT);
465 /* Destroys 'server' and stops listening for connections. */
467 unixctl_server_destroy(struct unixctl_server *server)
470 struct unixctl_conn *conn, *next;
472 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
473 kill_connection(conn);
477 fatal_signal_unlink_file_now(server->path);
483 /* Connects to a Vlog server socket. 'path' should be the name of a Vlog
484 * server socket. If it does not start with '/', it will be prefixed with
485 * the rundir (e.g. /usr/local/var/run/openvswitch).
487 * Returns 0 if successful, otherwise a positive errno value. If successful,
488 * sets '*clientp' to the new unixctl_client, otherwise to NULL. */
490 unixctl_client_create(const char *path, struct unixctl_client **clientp)
493 struct unixctl_client *client;
497 /* Determine location. */
498 client = xmalloc(sizeof *client);
499 client->connect_path = abs_file_name(ovs_rundir(), path);
500 client->bind_path = xasprintf("/tmp/vlog.%ld.%d",
501 (long int) getpid(), counter++);
504 fd = make_unix_socket(SOCK_STREAM, false, false,
505 client->bind_path, client->connect_path);
511 /* Bind socket to stream. */
512 client->stream = fdopen(fd, "r+");
513 if (!client->stream) {
515 VLOG_WARN("%s: fdopen failed (%s)",
516 client->connect_path, strerror(error));
526 free(client->connect_path);
527 free(client->bind_path);
533 /* Destroys 'client'. */
535 unixctl_client_destroy(struct unixctl_client *client)
538 fatal_signal_unlink_file_now(client->bind_path);
539 free(client->bind_path);
540 free(client->connect_path);
541 fclose(client->stream);
546 /* Sends 'request' to the server socket and waits for a reply. Returns 0 if
547 * successful, otherwise to a positive errno value. If successful, sets
548 * '*reply' to the reply, which the caller must free, otherwise to NULL. */
550 unixctl_client_transact(struct unixctl_client *client,
552 int *reply_code, char **reply_body)
554 struct ds line = DS_EMPTY_INITIALIZER;
555 struct ds reply = DS_EMPTY_INITIALIZER;
558 /* Send 'request' to server. Add a new-line if 'request' didn't end in
560 fputs(request, client->stream);
561 if (request[0] == '\0' || request[strlen(request) - 1] != '\n') {
562 putc('\n', client->stream);
564 if (ferror(client->stream)) {
565 VLOG_WARN("error sending request to %s: %s",
566 client->connect_path, strerror(errno));
570 /* Wait for response. */
575 error = ds_get_line(&line, client->stream);
577 VLOG_WARN("error reading reply from %s: %s",
578 client->connect_path,
579 ovs_retval_to_string(error));
584 if (*reply_code == -1) {
585 if (!isdigit((unsigned char)s[0])
586 || !isdigit((unsigned char)s[1])
587 || !isdigit((unsigned char)s[2])) {
588 VLOG_WARN("reply from %s does not start with 3-digit code",
589 client->connect_path);
593 sscanf(s, "%3d", reply_code);
601 ds_put_cstr(&reply, s);
602 ds_put_char(&reply, '\n');
605 *reply_body = ds_cstr(&reply);
614 return error == EOF ? EPROTO : error;
617 /* Returns the path of the server socket to which 'client' is connected. The
618 * caller must not modify or free the returned string. */
620 unixctl_client_target(const struct unixctl_client *client)
622 return client->connect_path;