2 * Copyright (c) 2008, 2009 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 {
47 void (*cb)(struct unixctl_conn *, const char *args);
54 enum { S_RECV, S_PROCESS, S_SEND } state;
60 /* Server for control connection. */
61 struct unixctl_server {
67 /* Client for control connection. */
68 struct unixctl_client {
74 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
76 static struct shash commands = SHASH_INITIALIZER(&commands);
79 unixctl_help(struct unixctl_conn *conn, const char *args UNUSED)
81 struct ds ds = DS_EMPTY_INITIALIZER;
82 struct shash_node *node;
84 ds_put_cstr(&ds, "The available commands are:\n");
85 SHASH_FOR_EACH (node, &commands) {
86 ds_put_format(&ds, "\t%s\n", node->name);
88 unixctl_command_reply(conn, 214, ds_cstr(&ds));
93 unixctl_command_register(const char *name,
94 void (*cb)(struct unixctl_conn *, const char *args))
96 struct unixctl_command *command;
98 assert(!shash_find_data(&commands, name)
99 || shash_find_data(&commands, name) == cb);
100 command = xmalloc(sizeof *command);
102 shash_add(&commands, name, command);
106 translate_reply_code(int code)
109 case 200: return "OK";
110 case 201: return "Created";
111 case 202: return "Accepted";
112 case 204: return "No Content";
113 case 211: return "System Status";
114 case 214: return "Help";
115 case 400: return "Bad Request";
116 case 401: return "Unauthorized";
117 case 403: return "Forbidden";
118 case 404: return "Not Found";
119 case 500: return "Internal Server Error";
120 case 501: return "Invalid Argument";
121 case 503: return "Service Unavailable";
122 default: return "Unknown";
127 unixctl_command_reply(struct unixctl_conn *conn,
128 int code, const char *body)
130 struct ds *out = &conn->out;
132 COVERAGE_INC(unixctl_replied);
133 assert(conn->state == S_PROCESS);
134 conn->state = S_SEND;
138 ds_put_format(out, "%03d %s\n", code, translate_reply_code(code));
141 for (p = body; *p != '\0'; ) {
142 size_t n = strcspn(p, "\n");
145 ds_put_char(out, '.');
147 ds_put_buffer(out, p, n);
148 ds_put_char(out, '\n');
155 ds_put_cstr(out, ".\n");
158 /* Creates a unixctl server listening on 'path', which may be:
160 * - NULL, in which case <rundir>/<program>.<pid>.ctl is used.
162 * - A name that does not start with '/', in which case it is put in
165 * - An absolute path (starting with '/') that gives the exact name of
166 * the Unix domain socket to listen on.
168 * A program that (optionally) daemonizes itself should call this function
169 * *after* daemonization, so that the socket name contains the pid of the
170 * daemon instead of the pid of the program that exited. (Otherwise,
171 * "ovs-appctl --target=<program>" will fail.)
173 * Returns 0 if successful, otherwise a positive errno value. If successful,
174 * sets '*serverp' to the new unixctl_server, otherwise to NULL. */
176 unixctl_server_create(const char *path, struct unixctl_server **serverp)
178 struct unixctl_server *server;
181 unixctl_command_register("help", unixctl_help);
183 server = xmalloc(sizeof *server);
184 list_init(&server->conns);
187 if (path[0] == '/') {
188 server->path = xstrdup(path);
190 server->path = xasprintf("%s/%s", ovs_rundir, path);
193 server->path = xasprintf("%s/%s.%ld.ctl", ovs_rundir,
194 program_name, (long int) getpid());
197 server->fd = make_unix_socket(SOCK_STREAM, true, false, server->path,
199 if (server->fd < 0) {
201 fprintf(stderr, "Could not initialize control socket %s (%s)\n",
202 server->path, strerror(error));
206 if (chmod(server->path, S_IRUSR | S_IWUSR) < 0) {
208 fprintf(stderr, "Failed to chmod control socket %s (%s)\n",
209 server->path, strerror(error));
213 if (listen(server->fd, 10) < 0) {
215 fprintf(stderr, "Failed to listen on control socket %s (%s)\n",
216 server->path, strerror(error));
224 if (server->fd >= 0) {
234 new_connection(struct unixctl_server *server, int fd)
236 struct unixctl_conn *conn;
240 conn = xmalloc(sizeof *conn);
241 list_push_back(&server->conns, &conn->node);
243 conn->state = S_RECV;
244 ofpbuf_init(&conn->in, 128);
250 run_connection_output(struct unixctl_conn *conn)
252 while (conn->out_pos < conn->out.length) {
253 size_t bytes_written;
256 error = write_fully(conn->fd, conn->out.string + conn->out_pos,
257 conn->out.length - conn->out_pos, &bytes_written);
258 conn->out_pos += bytes_written;
263 conn->state = S_RECV;
268 process_command(struct unixctl_conn *conn, char *s)
270 struct unixctl_command *command;
274 COVERAGE_INC(unixctl_received);
275 conn->state = S_PROCESS;
278 name_len = strcspn(name, " ");
279 args = name + name_len;
280 args += strspn(args, " ");
281 name[name_len] = '\0';
283 command = shash_find_data(&commands, name);
285 command->cb(conn, args);
287 char *msg = xasprintf("\"%s\" is not a valid command", name);
288 unixctl_command_reply(conn, 400, msg);
294 run_connection_input(struct unixctl_conn *conn)
301 newline = memchr(conn->in.data, '\n', conn->in.size);
303 char *command = conn->in.data;
304 size_t n = newline - command + 1;
306 if (n > 0 && newline[-1] == '\r') {
311 process_command(conn, command);
313 ofpbuf_pull(&conn->in, n);
314 if (!conn->in.size) {
315 ofpbuf_clear(&conn->in);
320 ofpbuf_prealloc_tailroom(&conn->in, 128);
321 error = read_fully(conn->fd, ofpbuf_tail(&conn->in),
322 ofpbuf_tailroom(&conn->in), &bytes_read);
323 conn->in.size += bytes_read;
324 if (conn->in.size > 65536) {
325 VLOG_WARN_RL(&rl, "excess command length, killing connection");
329 if (error == EAGAIN || error == EWOULDBLOCK) {
334 if (error != EOF || conn->in.size != 0) {
335 VLOG_WARN_RL(&rl, "read failed: %s",
337 ? "connection dropped mid-command"
347 run_connection(struct unixctl_conn *conn)
353 old_state = conn->state;
354 switch (conn->state) {
356 error = run_connection_input(conn);
364 error = run_connection_output(conn);
373 } while (conn->state != old_state);
378 kill_connection(struct unixctl_conn *conn)
380 list_remove(&conn->node);
381 ofpbuf_uninit(&conn->in);
382 ds_destroy(&conn->out);
388 unixctl_server_run(struct unixctl_server *server)
390 struct unixctl_conn *conn, *next;
393 for (i = 0; i < 10; i++) {
394 int fd = accept(server->fd, NULL, NULL);
396 if (errno != EAGAIN && errno != EWOULDBLOCK) {
397 VLOG_WARN_RL(&rl, "accept failed: %s", strerror(errno));
401 new_connection(server, fd);
404 LIST_FOR_EACH_SAFE (conn, next,
405 struct unixctl_conn, node, &server->conns) {
406 int error = run_connection(conn);
407 if (error && error != EAGAIN) {
408 kill_connection(conn);
414 unixctl_server_wait(struct unixctl_server *server)
416 struct unixctl_conn *conn;
418 poll_fd_wait(server->fd, POLLIN);
419 LIST_FOR_EACH (conn, struct unixctl_conn, node, &server->conns) {
420 if (conn->state == S_RECV) {
421 poll_fd_wait(conn->fd, POLLIN);
422 } else if (conn->state == S_SEND) {
423 poll_fd_wait(conn->fd, POLLOUT);
428 /* Destroys 'server' and stops listening for connections. */
430 unixctl_server_destroy(struct unixctl_server *server)
433 struct unixctl_conn *conn, *next;
435 LIST_FOR_EACH_SAFE (conn, next,
436 struct unixctl_conn, node, &server->conns) {
437 kill_connection(conn);
441 fatal_signal_unlink_file_now(server->path);
447 /* Connects to a Vlog server socket. 'path' should be the name of a Vlog
448 * server socket. If it does not start with '/', it will be prefixed with
449 * ovs_rundir (e.g. /var/run).
451 * Returns 0 if successful, otherwise a positive errno value. If successful,
452 * sets '*clientp' to the new unixctl_client, otherwise to NULL. */
454 unixctl_client_create(const char *path, struct unixctl_client **clientp)
457 struct unixctl_client *client;
461 /* Determine location. */
462 client = xmalloc(sizeof *client);
463 if (path[0] == '/') {
464 client->connect_path = xstrdup(path);
466 client->connect_path = xasprintf("%s/%s", ovs_rundir, path);
468 client->bind_path = xasprintf("/tmp/vlog.%ld.%d",
469 (long int) getpid(), counter++);
472 fd = make_unix_socket(SOCK_STREAM, false, false,
473 client->bind_path, client->connect_path);
479 /* Bind socket to stream. */
480 client->stream = fdopen(fd, "r+");
481 if (!client->stream) {
483 VLOG_WARN("%s: fdopen failed (%s)",
484 client->connect_path, strerror(error));
494 free(client->connect_path);
495 free(client->bind_path);
501 /* Destroys 'client'. */
503 unixctl_client_destroy(struct unixctl_client *client)
506 fatal_signal_unlink_file_now(client->bind_path);
507 free(client->bind_path);
508 free(client->connect_path);
509 fclose(client->stream);
514 /* Sends 'request' to the server socket and waits for a reply. Returns 0 if
515 * successful, otherwise to a positive errno value. If successful, sets
516 * '*reply' to the reply, which the caller must free, otherwise to NULL. */
518 unixctl_client_transact(struct unixctl_client *client,
520 int *reply_code, char **reply_body)
522 struct ds line = DS_EMPTY_INITIALIZER;
523 struct ds reply = DS_EMPTY_INITIALIZER;
526 /* Send 'request' to server. Add a new-line if 'request' didn't end in
528 fputs(request, client->stream);
529 if (request[0] == '\0' || request[strlen(request) - 1] != '\n') {
530 putc('\n', client->stream);
532 if (ferror(client->stream)) {
533 VLOG_WARN("error sending request to %s: %s",
534 client->connect_path, strerror(errno));
538 /* Wait for response. */
543 error = ds_get_line(&line, client->stream);
545 VLOG_WARN("error reading reply from %s: %s",
546 client->connect_path,
547 (error == EOF ? "unexpected end of file"
553 if (*reply_code == -1) {
554 if (!isdigit((unsigned char)s[0])
555 || !isdigit((unsigned char)s[1])
556 || !isdigit((unsigned char)s[2])) {
557 VLOG_WARN("reply from %s does not start with 3-digit code",
558 client->connect_path);
562 sscanf(s, "%3d", reply_code);
570 ds_put_cstr(&reply, s);
571 ds_put_char(&reply, '\n');
574 *reply_body = ds_cstr(&reply);
583 return error == EOF ? EPROTO : error;
586 /* Returns the path of the server socket to which 'client' is connected. The
587 * caller must not modify or free the returned string. */
589 unixctl_client_target(const struct unixctl_client *client)
591 return client->connect_path;