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"
39 #ifndef SCM_CREDENTIALS
43 #define THIS_MODULE VLM_unixctl
46 struct unixctl_command {
55 enum { S_RECV, S_PROCESS, S_SEND } state;
61 /* Server for control connection. */
62 struct unixctl_server {
68 /* Client for control connection. */
69 struct unixctl_client {
75 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
77 static struct shash commands = SHASH_INITIALIZER(&commands);
80 unixctl_help(struct unixctl_conn *conn, const char *args OVS_UNUSED,
83 struct ds ds = DS_EMPTY_INITIALIZER;
84 struct shash_node *node;
86 ds_put_cstr(&ds, "The available commands are:\n");
87 SHASH_FOR_EACH (node, &commands) {
88 ds_put_format(&ds, "\t%s\n", node->name);
90 unixctl_command_reply(conn, 214, ds_cstr(&ds));
95 unixctl_command_register(const char *name, unixctl_cb_func *cb, void *aux)
97 struct unixctl_command *command;
99 assert(!shash_find_data(&commands, name)
100 || shash_find_data(&commands, name) == cb);
101 command = xmalloc(sizeof *command);
104 shash_add(&commands, name, command);
108 translate_reply_code(int code)
111 case 200: return "OK";
112 case 201: return "Created";
113 case 202: return "Accepted";
114 case 204: return "No Content";
115 case 211: return "System Status";
116 case 214: return "Help";
117 case 400: return "Bad Request";
118 case 401: return "Unauthorized";
119 case 403: return "Forbidden";
120 case 404: return "Not Found";
121 case 500: return "Internal Server Error";
122 case 501: return "Invalid Argument";
123 case 503: return "Service Unavailable";
124 default: return "Unknown";
129 unixctl_command_reply(struct unixctl_conn *conn,
130 int code, const char *body)
132 struct ds *out = &conn->out;
134 COVERAGE_INC(unixctl_replied);
135 assert(conn->state == S_PROCESS);
136 conn->state = S_SEND;
140 ds_put_format(out, "%03d %s\n", code, translate_reply_code(code));
143 for (p = body; *p != '\0'; ) {
144 size_t n = strcspn(p, "\n");
147 ds_put_char(out, '.');
149 ds_put_buffer(out, p, n);
150 ds_put_char(out, '\n');
157 ds_put_cstr(out, ".\n");
160 /* Creates a unixctl server listening on 'path', which may be:
162 * - NULL, in which case <rundir>/<program>.<pid>.ctl is used.
164 * - A name that does not start with '/', in which case it is put in
167 * - An absolute path (starting with '/') that gives the exact name of
168 * the Unix domain socket to listen on.
170 * A program that (optionally) daemonizes itself should call this function
171 * *after* daemonization, so that the socket name contains the pid of the
172 * daemon instead of the pid of the program that exited. (Otherwise,
173 * "ovs-appctl --target=<program>" will fail.)
175 * Returns 0 if successful, otherwise a positive errno value. If successful,
176 * sets '*serverp' to the new unixctl_server, otherwise to NULL. */
178 unixctl_server_create(const char *path, struct unixctl_server **serverp)
180 struct unixctl_server *server;
183 unixctl_command_register("help", unixctl_help, NULL);
185 server = xmalloc(sizeof *server);
186 list_init(&server->conns);
189 server->path = abs_file_name(ovs_rundir, path);
191 server->path = xasprintf("%s/%s.%ld.ctl", ovs_rundir,
192 program_name, (long int) getpid());
195 server->fd = make_unix_socket(SOCK_STREAM, true, false, server->path,
197 if (server->fd < 0) {
199 ovs_error(error, "could not initialize control socket %s",
204 if (chmod(server->path, S_IRUSR | S_IWUSR) < 0) {
206 ovs_error(error, "failed to chmod control socket %s", server->path);
210 if (listen(server->fd, 10) < 0) {
212 ovs_error(error, "Failed to listen on control socket %s",
221 if (server->fd >= 0) {
231 new_connection(struct unixctl_server *server, int fd)
233 struct unixctl_conn *conn;
237 conn = xmalloc(sizeof *conn);
238 list_push_back(&server->conns, &conn->node);
240 conn->state = S_RECV;
241 ofpbuf_init(&conn->in, 128);
247 run_connection_output(struct unixctl_conn *conn)
249 while (conn->out_pos < conn->out.length) {
250 size_t bytes_written;
253 error = write_fully(conn->fd, conn->out.string + conn->out_pos,
254 conn->out.length - conn->out_pos, &bytes_written);
255 conn->out_pos += bytes_written;
260 conn->state = S_RECV;
265 process_command(struct unixctl_conn *conn, char *s)
267 struct unixctl_command *command;
271 COVERAGE_INC(unixctl_received);
272 conn->state = S_PROCESS;
275 name_len = strcspn(name, " ");
276 args = name + name_len;
277 args += strspn(args, " ");
278 name[name_len] = '\0';
280 command = shash_find_data(&commands, name);
282 command->cb(conn, args, command->aux);
284 char *msg = xasprintf("\"%s\" is not a valid command", name);
285 unixctl_command_reply(conn, 400, msg);
291 run_connection_input(struct unixctl_conn *conn)
298 newline = memchr(conn->in.data, '\n', conn->in.size);
300 char *command = conn->in.data;
301 size_t n = newline - command + 1;
303 if (n > 0 && newline[-1] == '\r') {
308 process_command(conn, command);
310 ofpbuf_pull(&conn->in, n);
311 if (!conn->in.size) {
312 ofpbuf_clear(&conn->in);
317 ofpbuf_prealloc_tailroom(&conn->in, 128);
318 error = read_fully(conn->fd, ofpbuf_tail(&conn->in),
319 ofpbuf_tailroom(&conn->in), &bytes_read);
320 conn->in.size += bytes_read;
321 if (conn->in.size > 65536) {
322 VLOG_WARN_RL(&rl, "excess command length, killing connection");
326 if (error == EAGAIN || error == EWOULDBLOCK) {
331 if (error != EOF || conn->in.size != 0) {
332 VLOG_WARN_RL(&rl, "read failed: %s",
334 ? "connection dropped mid-command"
344 run_connection(struct unixctl_conn *conn)
350 old_state = conn->state;
351 switch (conn->state) {
353 error = run_connection_input(conn);
361 error = run_connection_output(conn);
370 } while (conn->state != old_state);
375 kill_connection(struct unixctl_conn *conn)
377 list_remove(&conn->node);
378 ofpbuf_uninit(&conn->in);
379 ds_destroy(&conn->out);
385 unixctl_server_run(struct unixctl_server *server)
387 struct unixctl_conn *conn, *next;
390 for (i = 0; i < 10; i++) {
391 int fd = accept(server->fd, NULL, NULL);
393 if (errno != EAGAIN && errno != EWOULDBLOCK) {
394 VLOG_WARN_RL(&rl, "accept failed: %s", strerror(errno));
398 new_connection(server, fd);
401 LIST_FOR_EACH_SAFE (conn, next,
402 struct unixctl_conn, node, &server->conns) {
403 int error = run_connection(conn);
404 if (error && error != EAGAIN) {
405 kill_connection(conn);
411 unixctl_server_wait(struct unixctl_server *server)
413 struct unixctl_conn *conn;
415 poll_fd_wait(server->fd, POLLIN);
416 LIST_FOR_EACH (conn, struct unixctl_conn, node, &server->conns) {
417 if (conn->state == S_RECV) {
418 poll_fd_wait(conn->fd, POLLIN);
419 } else if (conn->state == S_SEND) {
420 poll_fd_wait(conn->fd, POLLOUT);
425 /* Destroys 'server' and stops listening for connections. */
427 unixctl_server_destroy(struct unixctl_server *server)
430 struct unixctl_conn *conn, *next;
432 LIST_FOR_EACH_SAFE (conn, next,
433 struct unixctl_conn, node, &server->conns) {
434 kill_connection(conn);
438 fatal_signal_unlink_file_now(server->path);
444 /* Connects to a Vlog server socket. 'path' should be the name of a Vlog
445 * server socket. If it does not start with '/', it will be prefixed with
446 * ovs_rundir (e.g. /var/run/openvswitch).
448 * Returns 0 if successful, otherwise a positive errno value. If successful,
449 * sets '*clientp' to the new unixctl_client, otherwise to NULL. */
451 unixctl_client_create(const char *path, struct unixctl_client **clientp)
454 struct unixctl_client *client;
458 /* Determine location. */
459 client = xmalloc(sizeof *client);
460 client->connect_path = abs_file_name(ovs_rundir, path);
461 client->bind_path = xasprintf("/tmp/vlog.%ld.%d",
462 (long int) getpid(), counter++);
465 fd = make_unix_socket(SOCK_STREAM, false, false,
466 client->bind_path, client->connect_path);
472 /* Bind socket to stream. */
473 client->stream = fdopen(fd, "r+");
474 if (!client->stream) {
476 VLOG_WARN("%s: fdopen failed (%s)",
477 client->connect_path, strerror(error));
487 free(client->connect_path);
488 free(client->bind_path);
494 /* Destroys 'client'. */
496 unixctl_client_destroy(struct unixctl_client *client)
499 fatal_signal_unlink_file_now(client->bind_path);
500 free(client->bind_path);
501 free(client->connect_path);
502 fclose(client->stream);
507 /* Sends 'request' to the server socket and waits for a reply. Returns 0 if
508 * successful, otherwise to a positive errno value. If successful, sets
509 * '*reply' to the reply, which the caller must free, otherwise to NULL. */
511 unixctl_client_transact(struct unixctl_client *client,
513 int *reply_code, char **reply_body)
515 struct ds line = DS_EMPTY_INITIALIZER;
516 struct ds reply = DS_EMPTY_INITIALIZER;
519 /* Send 'request' to server. Add a new-line if 'request' didn't end in
521 fputs(request, client->stream);
522 if (request[0] == '\0' || request[strlen(request) - 1] != '\n') {
523 putc('\n', client->stream);
525 if (ferror(client->stream)) {
526 VLOG_WARN("error sending request to %s: %s",
527 client->connect_path, strerror(errno));
531 /* Wait for response. */
536 error = ds_get_line(&line, client->stream);
538 VLOG_WARN("error reading reply from %s: %s",
539 client->connect_path,
540 (error == EOF ? "unexpected end of file"
546 if (*reply_code == -1) {
547 if (!isdigit((unsigned char)s[0])
548 || !isdigit((unsigned char)s[1])
549 || !isdigit((unsigned char)s[2])) {
550 VLOG_WARN("reply from %s does not start with 3-digit code",
551 client->connect_path);
555 sscanf(s, "%3d", reply_code);
563 ds_put_cstr(&reply, s);
564 ds_put_char(&reply, '\n');
567 *reply_body = ds_cstr(&reply);
576 return error == EOF ? EPROTO : error;
579 /* Returns the path of the server socket to which 'client' is connected. The
580 * caller must not modify or free the returned string. */
582 unixctl_client_target(const struct unixctl_client *client)
584 return client->connect_path;