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 struct unixctl_command {
56 enum { S_RECV, S_PROCESS, S_SEND } state;
62 /* Server for control connection. */
63 struct unixctl_server {
69 /* Client for control connection. */
70 struct unixctl_client {
76 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
78 static struct shash commands = SHASH_INITIALIZER(&commands);
81 unixctl_help(struct unixctl_conn *conn, const char *args OVS_UNUSED,
84 struct ds ds = DS_EMPTY_INITIALIZER;
85 struct shash_node *node;
90 ds_put_cstr(&ds, "The available commands are:\n");
93 SHASH_FOR_EACH (node, &commands) {
94 svec_add(&names, node->name);
98 SVEC_FOR_EACH (i, name, &names) {
99 ds_put_format(&ds, "\t%s\n", name);
101 svec_destroy(&names);
103 unixctl_command_reply(conn, 214, ds_cstr(&ds));
108 unixctl_command_register(const char *name, unixctl_cb_func *cb, void *aux)
110 struct unixctl_command *command;
112 assert(!shash_find_data(&commands, name)
113 || shash_find_data(&commands, name) == cb);
114 command = xmalloc(sizeof *command);
117 shash_add(&commands, name, command);
121 translate_reply_code(int code)
124 case 200: return "OK";
125 case 201: return "Created";
126 case 202: return "Accepted";
127 case 204: return "No Content";
128 case 211: return "System Status";
129 case 214: return "Help";
130 case 400: return "Bad Request";
131 case 401: return "Unauthorized";
132 case 403: return "Forbidden";
133 case 404: return "Not Found";
134 case 500: return "Internal Server Error";
135 case 501: return "Invalid Argument";
136 case 503: return "Service Unavailable";
137 default: return "Unknown";
142 unixctl_command_reply(struct unixctl_conn *conn,
143 int code, const char *body)
145 struct ds *out = &conn->out;
147 COVERAGE_INC(unixctl_replied);
148 assert(conn->state == S_PROCESS);
149 conn->state = S_SEND;
153 ds_put_format(out, "%03d %s\n", code, translate_reply_code(code));
156 for (p = body; *p != '\0'; ) {
157 size_t n = strcspn(p, "\n");
160 ds_put_char(out, '.');
162 ds_put_buffer(out, p, n);
163 ds_put_char(out, '\n');
170 ds_put_cstr(out, ".\n");
173 /* Creates a unixctl server listening on 'path', which may be:
175 * - NULL, in which case <rundir>/<program>.<pid>.ctl is used.
177 * - A name that does not start with '/', in which case it is put in
180 * - An absolute path (starting with '/') that gives the exact name of
181 * the Unix domain socket to listen on.
183 * A program that (optionally) daemonizes itself should call this function
184 * *after* daemonization, so that the socket name contains the pid of the
185 * daemon instead of the pid of the program that exited. (Otherwise,
186 * "ovs-appctl --target=<program>" will fail.)
188 * Returns 0 if successful, otherwise a positive errno value. If successful,
189 * sets '*serverp' to the new unixctl_server, otherwise to NULL. */
191 unixctl_server_create(const char *path, struct unixctl_server **serverp)
193 struct unixctl_server *server;
196 unixctl_command_register("help", unixctl_help, NULL);
198 server = xmalloc(sizeof *server);
199 list_init(&server->conns);
202 server->path = abs_file_name(ovs_rundir, path);
204 server->path = xasprintf("%s/%s.%ld.ctl", ovs_rundir,
205 program_name, (long int) getpid());
208 server->fd = make_unix_socket(SOCK_STREAM, true, false, server->path,
210 if (server->fd < 0) {
212 ovs_error(error, "could not initialize control socket %s",
217 if (chmod(server->path, S_IRUSR | S_IWUSR) < 0) {
219 ovs_error(error, "failed to chmod control socket %s", server->path);
223 if (listen(server->fd, 10) < 0) {
225 ovs_error(error, "Failed to listen on control socket %s",
234 if (server->fd >= 0) {
244 new_connection(struct unixctl_server *server, int fd)
246 struct unixctl_conn *conn;
250 conn = xmalloc(sizeof *conn);
251 list_push_back(&server->conns, &conn->node);
253 conn->state = S_RECV;
254 ofpbuf_init(&conn->in, 128);
260 run_connection_output(struct unixctl_conn *conn)
262 while (conn->out_pos < conn->out.length) {
263 size_t bytes_written;
266 error = write_fully(conn->fd, conn->out.string + conn->out_pos,
267 conn->out.length - conn->out_pos, &bytes_written);
268 conn->out_pos += bytes_written;
273 conn->state = S_RECV;
278 process_command(struct unixctl_conn *conn, char *s)
280 struct unixctl_command *command;
284 COVERAGE_INC(unixctl_received);
285 conn->state = S_PROCESS;
288 name_len = strcspn(name, " ");
289 args = name + name_len;
290 args += strspn(args, " ");
291 name[name_len] = '\0';
293 command = shash_find_data(&commands, name);
295 command->cb(conn, args, command->aux);
297 char *msg = xasprintf("\"%s\" is not a valid command", name);
298 unixctl_command_reply(conn, 400, msg);
304 run_connection_input(struct unixctl_conn *conn)
311 newline = memchr(conn->in.data, '\n', conn->in.size);
313 char *command = conn->in.data;
314 size_t n = newline - command + 1;
316 if (n > 0 && newline[-1] == '\r') {
321 process_command(conn, command);
323 ofpbuf_pull(&conn->in, n);
324 if (!conn->in.size) {
325 ofpbuf_clear(&conn->in);
330 ofpbuf_prealloc_tailroom(&conn->in, 128);
331 error = read_fully(conn->fd, ofpbuf_tail(&conn->in),
332 ofpbuf_tailroom(&conn->in), &bytes_read);
333 conn->in.size += bytes_read;
334 if (conn->in.size > 65536) {
335 VLOG_WARN_RL(&rl, "excess command length, killing connection");
339 if (error == EAGAIN || error == EWOULDBLOCK) {
344 if (error != EOF || conn->in.size != 0) {
345 VLOG_WARN_RL(&rl, "read failed: %s",
347 ? "connection dropped mid-command"
357 run_connection(struct unixctl_conn *conn)
363 old_state = conn->state;
364 switch (conn->state) {
366 error = run_connection_input(conn);
374 error = run_connection_output(conn);
383 } while (conn->state != old_state);
388 kill_connection(struct unixctl_conn *conn)
390 list_remove(&conn->node);
391 ofpbuf_uninit(&conn->in);
392 ds_destroy(&conn->out);
398 unixctl_server_run(struct unixctl_server *server)
400 struct unixctl_conn *conn, *next;
403 for (i = 0; i < 10; i++) {
404 int fd = accept(server->fd, NULL, NULL);
406 if (errno != EAGAIN && errno != EWOULDBLOCK) {
407 VLOG_WARN_RL(&rl, "accept failed: %s", strerror(errno));
411 new_connection(server, fd);
414 LIST_FOR_EACH_SAFE (conn, next,
415 struct unixctl_conn, node, &server->conns) {
416 int error = run_connection(conn);
417 if (error && error != EAGAIN) {
418 kill_connection(conn);
424 unixctl_server_wait(struct unixctl_server *server)
426 struct unixctl_conn *conn;
428 poll_fd_wait(server->fd, POLLIN);
429 LIST_FOR_EACH (conn, struct unixctl_conn, node, &server->conns) {
430 if (conn->state == S_RECV) {
431 poll_fd_wait(conn->fd, POLLIN);
432 } else if (conn->state == S_SEND) {
433 poll_fd_wait(conn->fd, POLLOUT);
438 /* Destroys 'server' and stops listening for connections. */
440 unixctl_server_destroy(struct unixctl_server *server)
443 struct unixctl_conn *conn, *next;
445 LIST_FOR_EACH_SAFE (conn, next,
446 struct unixctl_conn, node, &server->conns) {
447 kill_connection(conn);
451 fatal_signal_unlink_file_now(server->path);
457 /* Connects to a Vlog server socket. 'path' should be the name of a Vlog
458 * server socket. If it does not start with '/', it will be prefixed with
459 * ovs_rundir (e.g. /var/run/openvswitch).
461 * Returns 0 if successful, otherwise a positive errno value. If successful,
462 * sets '*clientp' to the new unixctl_client, otherwise to NULL. */
464 unixctl_client_create(const char *path, struct unixctl_client **clientp)
467 struct unixctl_client *client;
471 /* Determine location. */
472 client = xmalloc(sizeof *client);
473 client->connect_path = abs_file_name(ovs_rundir, path);
474 client->bind_path = xasprintf("/tmp/vlog.%ld.%d",
475 (long int) getpid(), counter++);
478 fd = make_unix_socket(SOCK_STREAM, false, false,
479 client->bind_path, client->connect_path);
485 /* Bind socket to stream. */
486 client->stream = fdopen(fd, "r+");
487 if (!client->stream) {
489 VLOG_WARN("%s: fdopen failed (%s)",
490 client->connect_path, strerror(error));
500 free(client->connect_path);
501 free(client->bind_path);
507 /* Destroys 'client'. */
509 unixctl_client_destroy(struct unixctl_client *client)
512 fatal_signal_unlink_file_now(client->bind_path);
513 free(client->bind_path);
514 free(client->connect_path);
515 fclose(client->stream);
520 /* Sends 'request' to the server socket and waits for a reply. Returns 0 if
521 * successful, otherwise to a positive errno value. If successful, sets
522 * '*reply' to the reply, which the caller must free, otherwise to NULL. */
524 unixctl_client_transact(struct unixctl_client *client,
526 int *reply_code, char **reply_body)
528 struct ds line = DS_EMPTY_INITIALIZER;
529 struct ds reply = DS_EMPTY_INITIALIZER;
532 /* Send 'request' to server. Add a new-line if 'request' didn't end in
534 fputs(request, client->stream);
535 if (request[0] == '\0' || request[strlen(request) - 1] != '\n') {
536 putc('\n', client->stream);
538 if (ferror(client->stream)) {
539 VLOG_WARN("error sending request to %s: %s",
540 client->connect_path, strerror(errno));
544 /* Wait for response. */
549 error = ds_get_line(&line, client->stream);
551 VLOG_WARN("error reading reply from %s: %s",
552 client->connect_path,
553 (error == EOF ? "unexpected end of file"
559 if (*reply_code == -1) {
560 if (!isdigit((unsigned char)s[0])
561 || !isdigit((unsigned char)s[1])
562 || !isdigit((unsigned char)s[2])) {
563 VLOG_WARN("reply from %s does not start with 3-digit code",
564 client->connect_path);
568 sscanf(s, "%3d", reply_code);
576 ds_put_cstr(&reply, s);
577 ds_put_char(&reply, '\n');
580 *reply_body = ds_cstr(&reply);
589 return error == EOF ? EPROTO : error;
592 /* Returns the path of the server socket to which 'client' is connected. The
593 * caller must not modify or free the returned string. */
595 unixctl_client_target(const struct unixctl_client *client)
597 return client->connect_path;