2 * Copyright (c) 2008, 2009, 2010 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_command_register(const char *name, unixctl_cb_func *cb, void *aux)
113 struct unixctl_command *command;
115 assert(!shash_find_data(&commands, name)
116 || shash_find_data(&commands, name) == cb);
117 command = xmalloc(sizeof *command);
120 shash_add(&commands, name, command);
124 translate_reply_code(int code)
127 case 200: return "OK";
128 case 201: return "Created";
129 case 202: return "Accepted";
130 case 204: return "No Content";
131 case 211: return "System Status";
132 case 214: return "Help";
133 case 400: return "Bad Request";
134 case 401: return "Unauthorized";
135 case 403: return "Forbidden";
136 case 404: return "Not Found";
137 case 500: return "Internal Server Error";
138 case 501: return "Invalid Argument";
139 case 503: return "Service Unavailable";
140 default: return "Unknown";
145 unixctl_command_reply(struct unixctl_conn *conn,
146 int code, const char *body)
148 struct ds *out = &conn->out;
150 COVERAGE_INC(unixctl_replied);
151 assert(conn->state == S_PROCESS);
152 conn->state = S_SEND;
156 ds_put_format(out, "%03d %s\n", code, translate_reply_code(code));
159 for (p = body; *p != '\0'; ) {
160 size_t n = strcspn(p, "\n");
163 ds_put_char(out, '.');
165 ds_put_buffer(out, p, n);
166 ds_put_char(out, '\n');
173 ds_put_cstr(out, ".\n");
176 /* Creates a unixctl server listening on 'path', which may be:
178 * - NULL, in which case <rundir>/<program>.<pid>.ctl is used.
180 * - "none", in which case the function will return successfully but
181 * no socket will actually be created.
183 * - A name that does not start with '/', in which case it is put in
186 * - An absolute path (starting with '/') that gives the exact name of
187 * the Unix domain socket to listen on.
189 * A program that (optionally) daemonizes itself should call this function
190 * *after* daemonization, so that the socket name contains the pid of the
191 * daemon instead of the pid of the program that exited. (Otherwise,
192 * "ovs-appctl --target=<program>" will fail.)
194 * Returns 0 if successful, otherwise a positive errno value. If successful,
195 * sets '*serverp' to the new unixctl_server (or to NULL if 'path' was "none"),
196 * otherwise to NULL. */
198 unixctl_server_create(const char *path, struct unixctl_server **serverp)
200 struct unixctl_server *server;
203 if (path && !strcmp(path, "none")) {
208 unixctl_command_register("help", unixctl_help, NULL);
210 server = xmalloc(sizeof *server);
211 list_init(&server->conns);
214 server->path = abs_file_name(ovs_rundir(), path);
216 server->path = xasprintf("%s/%s.%ld.ctl", ovs_rundir(),
217 program_name, (long int) getpid());
220 server->fd = make_unix_socket(SOCK_STREAM, true, false, server->path,
222 if (server->fd < 0) {
224 ovs_error(error, "could not initialize control socket %s",
229 if (chmod(server->path, S_IRUSR | S_IWUSR) < 0) {
231 ovs_error(error, "failed to chmod control socket %s", server->path);
235 if (listen(server->fd, 10) < 0) {
237 ovs_error(error, "Failed to listen on control socket %s",
246 if (server->fd >= 0) {
256 new_connection(struct unixctl_server *server, int fd)
258 struct unixctl_conn *conn;
262 conn = xmalloc(sizeof *conn);
263 list_push_back(&server->conns, &conn->node);
265 conn->state = S_RECV;
266 ofpbuf_init(&conn->in, 128);
272 run_connection_output(struct unixctl_conn *conn)
274 while (conn->out_pos < conn->out.length) {
275 size_t bytes_written;
278 error = write_fully(conn->fd, conn->out.string + conn->out_pos,
279 conn->out.length - conn->out_pos, &bytes_written);
280 conn->out_pos += bytes_written;
285 conn->state = S_RECV;
290 process_command(struct unixctl_conn *conn, char *s)
292 struct unixctl_command *command;
296 COVERAGE_INC(unixctl_received);
297 conn->state = S_PROCESS;
300 name_len = strcspn(name, " ");
301 args = name + name_len;
302 args += strspn(args, " ");
303 name[name_len] = '\0';
305 command = shash_find_data(&commands, name);
307 command->cb(conn, args, command->aux);
309 char *msg = xasprintf("\"%s\" is not a valid command", name);
310 unixctl_command_reply(conn, 400, msg);
316 run_connection_input(struct unixctl_conn *conn)
323 newline = memchr(conn->in.data, '\n', conn->in.size);
325 char *command = conn->in.data;
326 size_t n = newline - command + 1;
328 if (n > 0 && newline[-1] == '\r') {
333 process_command(conn, command);
335 ofpbuf_pull(&conn->in, n);
336 if (!conn->in.size) {
337 ofpbuf_clear(&conn->in);
342 ofpbuf_prealloc_tailroom(&conn->in, 128);
343 error = read_fully(conn->fd, ofpbuf_tail(&conn->in),
344 ofpbuf_tailroom(&conn->in), &bytes_read);
345 conn->in.size += bytes_read;
346 if (conn->in.size > 65536) {
347 VLOG_WARN_RL(&rl, "excess command length, killing connection");
351 if (error == EAGAIN || error == EWOULDBLOCK) {
356 if (error != EOF || conn->in.size != 0) {
357 VLOG_WARN_RL(&rl, "read failed: %s",
359 ? "connection dropped mid-command"
369 run_connection(struct unixctl_conn *conn)
375 old_state = conn->state;
376 switch (conn->state) {
378 error = run_connection_input(conn);
386 error = run_connection_output(conn);
395 } while (conn->state != old_state);
400 kill_connection(struct unixctl_conn *conn)
402 list_remove(&conn->node);
403 ofpbuf_uninit(&conn->in);
404 ds_destroy(&conn->out);
410 unixctl_server_run(struct unixctl_server *server)
412 struct unixctl_conn *conn, *next;
419 for (i = 0; i < 10; i++) {
420 int fd = accept(server->fd, NULL, NULL);
422 if (errno != EAGAIN && errno != EWOULDBLOCK) {
423 VLOG_WARN_RL(&rl, "accept failed: %s", strerror(errno));
427 new_connection(server, fd);
430 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
431 int error = run_connection(conn);
432 if (error && error != EAGAIN) {
433 kill_connection(conn);
439 unixctl_server_wait(struct unixctl_server *server)
441 struct unixctl_conn *conn;
447 poll_fd_wait(server->fd, POLLIN);
448 LIST_FOR_EACH (conn, node, &server->conns) {
449 if (conn->state == S_RECV) {
450 poll_fd_wait(conn->fd, POLLIN);
451 } else if (conn->state == S_SEND) {
452 poll_fd_wait(conn->fd, POLLOUT);
457 /* Destroys 'server' and stops listening for connections. */
459 unixctl_server_destroy(struct unixctl_server *server)
462 struct unixctl_conn *conn, *next;
464 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
465 kill_connection(conn);
469 fatal_signal_unlink_file_now(server->path);
475 /* Connects to a Vlog server socket. 'path' should be the name of a Vlog
476 * server socket. If it does not start with '/', it will be prefixed with
477 * the rundir (e.g. /usr/local/var/run/openvswitch).
479 * Returns 0 if successful, otherwise a positive errno value. If successful,
480 * sets '*clientp' to the new unixctl_client, otherwise to NULL. */
482 unixctl_client_create(const char *path, struct unixctl_client **clientp)
485 struct unixctl_client *client;
489 /* Determine location. */
490 client = xmalloc(sizeof *client);
491 client->connect_path = abs_file_name(ovs_rundir(), path);
492 client->bind_path = xasprintf("/tmp/vlog.%ld.%d",
493 (long int) getpid(), counter++);
496 fd = make_unix_socket(SOCK_STREAM, false, false,
497 client->bind_path, client->connect_path);
503 /* Bind socket to stream. */
504 client->stream = fdopen(fd, "r+");
505 if (!client->stream) {
507 VLOG_WARN("%s: fdopen failed (%s)",
508 client->connect_path, strerror(error));
518 free(client->connect_path);
519 free(client->bind_path);
525 /* Destroys 'client'. */
527 unixctl_client_destroy(struct unixctl_client *client)
530 fatal_signal_unlink_file_now(client->bind_path);
531 free(client->bind_path);
532 free(client->connect_path);
533 fclose(client->stream);
538 /* Sends 'request' to the server socket and waits for a reply. Returns 0 if
539 * successful, otherwise to a positive errno value. If successful, sets
540 * '*reply' to the reply, which the caller must free, otherwise to NULL. */
542 unixctl_client_transact(struct unixctl_client *client,
544 int *reply_code, char **reply_body)
546 struct ds line = DS_EMPTY_INITIALIZER;
547 struct ds reply = DS_EMPTY_INITIALIZER;
550 /* Send 'request' to server. Add a new-line if 'request' didn't end in
552 fputs(request, client->stream);
553 if (request[0] == '\0' || request[strlen(request) - 1] != '\n') {
554 putc('\n', client->stream);
556 if (ferror(client->stream)) {
557 VLOG_WARN("error sending request to %s: %s",
558 client->connect_path, strerror(errno));
562 /* Wait for response. */
567 error = ds_get_line(&line, client->stream);
569 VLOG_WARN("error reading reply from %s: %s",
570 client->connect_path,
571 (error == EOF ? "unexpected end of file"
577 if (*reply_code == -1) {
578 if (!isdigit((unsigned char)s[0])
579 || !isdigit((unsigned char)s[1])
580 || !isdigit((unsigned char)s[2])) {
581 VLOG_WARN("reply from %s does not start with 3-digit code",
582 client->connect_path);
586 sscanf(s, "%3d", reply_code);
594 ds_put_cstr(&reply, s);
595 ds_put_char(&reply, '\n');
598 *reply_body = ds_cstr(&reply);
607 return error == EOF ? EPROTO : error;
610 /* Returns the path of the server socket to which 'client' is connected. The
611 * caller must not modify or free the returned string. */
613 unixctl_client_target(const struct unixctl_client *client)
615 return client->connect_path;