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 * - "none", in which case the function will return successfully but
178 * no socket will actually be created.
180 * - A name that does not start with '/', in which case it is put in
183 * - An absolute path (starting with '/') that gives the exact name of
184 * the Unix domain socket to listen on.
186 * A program that (optionally) daemonizes itself should call this function
187 * *after* daemonization, so that the socket name contains the pid of the
188 * daemon instead of the pid of the program that exited. (Otherwise,
189 * "ovs-appctl --target=<program>" will fail.)
191 * Returns 0 if successful, otherwise a positive errno value. If successful,
192 * sets '*serverp' to the new unixctl_server (or to NULL if 'path' was "none"),
193 * otherwise to NULL. */
195 unixctl_server_create(const char *path, struct unixctl_server **serverp)
197 struct unixctl_server *server;
200 if (path && !strcmp(path, "none")) {
205 unixctl_command_register("help", unixctl_help, NULL);
207 server = xmalloc(sizeof *server);
208 list_init(&server->conns);
211 server->path = abs_file_name(ovs_rundir(), path);
213 server->path = xasprintf("%s/%s.%ld.ctl", ovs_rundir(),
214 program_name, (long int) getpid());
217 server->fd = make_unix_socket(SOCK_STREAM, true, false, server->path,
219 if (server->fd < 0) {
221 ovs_error(error, "could not initialize control socket %s",
226 if (chmod(server->path, S_IRUSR | S_IWUSR) < 0) {
228 ovs_error(error, "failed to chmod control socket %s", server->path);
232 if (listen(server->fd, 10) < 0) {
234 ovs_error(error, "Failed to listen on control socket %s",
243 if (server->fd >= 0) {
253 new_connection(struct unixctl_server *server, int fd)
255 struct unixctl_conn *conn;
259 conn = xmalloc(sizeof *conn);
260 list_push_back(&server->conns, &conn->node);
262 conn->state = S_RECV;
263 ofpbuf_init(&conn->in, 128);
269 run_connection_output(struct unixctl_conn *conn)
271 while (conn->out_pos < conn->out.length) {
272 size_t bytes_written;
275 error = write_fully(conn->fd, conn->out.string + conn->out_pos,
276 conn->out.length - conn->out_pos, &bytes_written);
277 conn->out_pos += bytes_written;
282 conn->state = S_RECV;
287 process_command(struct unixctl_conn *conn, char *s)
289 struct unixctl_command *command;
293 COVERAGE_INC(unixctl_received);
294 conn->state = S_PROCESS;
297 name_len = strcspn(name, " ");
298 args = name + name_len;
299 args += strspn(args, " ");
300 name[name_len] = '\0';
302 command = shash_find_data(&commands, name);
304 command->cb(conn, args, command->aux);
306 char *msg = xasprintf("\"%s\" is not a valid command", name);
307 unixctl_command_reply(conn, 400, msg);
313 run_connection_input(struct unixctl_conn *conn)
320 newline = memchr(conn->in.data, '\n', conn->in.size);
322 char *command = conn->in.data;
323 size_t n = newline - command + 1;
325 if (n > 0 && newline[-1] == '\r') {
330 process_command(conn, command);
332 ofpbuf_pull(&conn->in, n);
333 if (!conn->in.size) {
334 ofpbuf_clear(&conn->in);
339 ofpbuf_prealloc_tailroom(&conn->in, 128);
340 error = read_fully(conn->fd, ofpbuf_tail(&conn->in),
341 ofpbuf_tailroom(&conn->in), &bytes_read);
342 conn->in.size += bytes_read;
343 if (conn->in.size > 65536) {
344 VLOG_WARN_RL(&rl, "excess command length, killing connection");
348 if (error == EAGAIN || error == EWOULDBLOCK) {
353 if (error != EOF || conn->in.size != 0) {
354 VLOG_WARN_RL(&rl, "read failed: %s",
356 ? "connection dropped mid-command"
366 run_connection(struct unixctl_conn *conn)
372 old_state = conn->state;
373 switch (conn->state) {
375 error = run_connection_input(conn);
383 error = run_connection_output(conn);
392 } while (conn->state != old_state);
397 kill_connection(struct unixctl_conn *conn)
399 list_remove(&conn->node);
400 ofpbuf_uninit(&conn->in);
401 ds_destroy(&conn->out);
407 unixctl_server_run(struct unixctl_server *server)
409 struct unixctl_conn *conn, *next;
416 for (i = 0; i < 10; i++) {
417 int fd = accept(server->fd, NULL, NULL);
419 if (errno != EAGAIN && errno != EWOULDBLOCK) {
420 VLOG_WARN_RL(&rl, "accept failed: %s", strerror(errno));
424 new_connection(server, fd);
427 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
428 int error = run_connection(conn);
429 if (error && error != EAGAIN) {
430 kill_connection(conn);
436 unixctl_server_wait(struct unixctl_server *server)
438 struct unixctl_conn *conn;
444 poll_fd_wait(server->fd, POLLIN);
445 LIST_FOR_EACH (conn, node, &server->conns) {
446 if (conn->state == S_RECV) {
447 poll_fd_wait(conn->fd, POLLIN);
448 } else if (conn->state == S_SEND) {
449 poll_fd_wait(conn->fd, POLLOUT);
454 /* Destroys 'server' and stops listening for connections. */
456 unixctl_server_destroy(struct unixctl_server *server)
459 struct unixctl_conn *conn, *next;
461 LIST_FOR_EACH_SAFE (conn, next, node, &server->conns) {
462 kill_connection(conn);
466 fatal_signal_unlink_file_now(server->path);
472 /* Connects to a Vlog server socket. 'path' should be the name of a Vlog
473 * server socket. If it does not start with '/', it will be prefixed with
474 * the rundir (e.g. /usr/local/var/run/openvswitch).
476 * Returns 0 if successful, otherwise a positive errno value. If successful,
477 * sets '*clientp' to the new unixctl_client, otherwise to NULL. */
479 unixctl_client_create(const char *path, struct unixctl_client **clientp)
482 struct unixctl_client *client;
486 /* Determine location. */
487 client = xmalloc(sizeof *client);
488 client->connect_path = abs_file_name(ovs_rundir(), path);
489 client->bind_path = xasprintf("/tmp/vlog.%ld.%d",
490 (long int) getpid(), counter++);
493 fd = make_unix_socket(SOCK_STREAM, false, false,
494 client->bind_path, client->connect_path);
500 /* Bind socket to stream. */
501 client->stream = fdopen(fd, "r+");
502 if (!client->stream) {
504 VLOG_WARN("%s: fdopen failed (%s)",
505 client->connect_path, strerror(error));
515 free(client->connect_path);
516 free(client->bind_path);
522 /* Destroys 'client'. */
524 unixctl_client_destroy(struct unixctl_client *client)
527 fatal_signal_unlink_file_now(client->bind_path);
528 free(client->bind_path);
529 free(client->connect_path);
530 fclose(client->stream);
535 /* Sends 'request' to the server socket and waits for a reply. Returns 0 if
536 * successful, otherwise to a positive errno value. If successful, sets
537 * '*reply' to the reply, which the caller must free, otherwise to NULL. */
539 unixctl_client_transact(struct unixctl_client *client,
541 int *reply_code, char **reply_body)
543 struct ds line = DS_EMPTY_INITIALIZER;
544 struct ds reply = DS_EMPTY_INITIALIZER;
547 /* Send 'request' to server. Add a new-line if 'request' didn't end in
549 fputs(request, client->stream);
550 if (request[0] == '\0' || request[strlen(request) - 1] != '\n') {
551 putc('\n', client->stream);
553 if (ferror(client->stream)) {
554 VLOG_WARN("error sending request to %s: %s",
555 client->connect_path, strerror(errno));
559 /* Wait for response. */
564 error = ds_get_line(&line, client->stream);
566 VLOG_WARN("error reading reply from %s: %s",
567 client->connect_path,
568 (error == EOF ? "unexpected end of file"
574 if (*reply_code == -1) {
575 if (!isdigit((unsigned char)s[0])
576 || !isdigit((unsigned char)s[1])
577 || !isdigit((unsigned char)s[2])) {
578 VLOG_WARN("reply from %s does not start with 3-digit code",
579 client->connect_path);
583 sscanf(s, "%3d", reply_code);
591 ds_put_cstr(&reply, s);
592 ds_put_char(&reply, '\n');
595 *reply_body = ds_cstr(&reply);
604 return error == EOF ? EPROTO : error;
607 /* Returns the path of the server socket to which 'client' is connected. The
608 * caller must not modify or free the returned string. */
610 unixctl_client_target(const struct unixctl_client *client)
612 return client->connect_path;