2eccdc68220e4630be141e7c596b547eadf81f7e
[cascardo/ovs.git] / lib / command-line.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2013, 2014 Nicira, Inc.
3  *
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:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <config.h>
18 #include "command-line.h"
19 #include <getopt.h>
20 #include <limits.h>
21 #include <stdlib.h>
22 #include "dynamic-string.h"
23 #include "ovs-thread.h"
24 #include "util.h"
25 #include "openvswitch/vlog.h"
26
27 VLOG_DEFINE_THIS_MODULE(command_line);
28
29 /* Given the GNU-style long options in 'options', returns a string that may be
30  * passed to getopt() with the corresponding short options.  The caller is
31  * responsible for freeing the string. */
32 char *
33 long_options_to_short_options(const struct option options[])
34 {
35     char short_options[UCHAR_MAX * 3 + 1];
36     char *p = short_options;
37
38     for (; options->name; options++) {
39         const struct option *o = options;
40         if (o->flag == NULL && o->val > 0 && o->val <= UCHAR_MAX) {
41             *p++ = o->val;
42             if (o->has_arg == required_argument) {
43                 *p++ = ':';
44             } else if (o->has_arg == optional_argument) {
45                 *p++ = ':';
46                 *p++ = ':';
47             }
48         }
49     }
50     *p = '\0';
51
52     return xstrdup(short_options);
53 }
54
55 /* Given the 'struct command' array, prints the usage of all commands. */
56 void
57 print_commands(const struct command commands[])
58 {
59     struct ds ds = DS_EMPTY_INITIALIZER;
60
61     ds_put_cstr(&ds, "The available commands are:\n");
62     for (; commands->name; commands++) {
63         const struct command *c = commands;
64         ds_put_format(&ds, "  %-23s %s\n", c->name, c->usage ? c->usage : "");
65     }
66     printf("%s", ds.string);
67     ds_destroy(&ds);
68 }
69
70 /* Given the GNU-style options in 'options', prints all options. */
71 void
72 print_options(const struct option options[])
73 {
74     struct ds ds = DS_EMPTY_INITIALIZER;
75
76     for (; options->name; options++) {
77         const struct option *o = options;
78         const char *arg = o->has_arg == required_argument ? "ARG" : "[ARG]";
79
80         ds_put_format(&ds, "--%s%s%s\n", o->name, o->has_arg ? "=" : "",
81                       o->has_arg ? arg : "");
82         if (o->flag == NULL && o->val > 0 && o->val <= UCHAR_MAX) {
83             ds_put_format(&ds, "-%c %s\n", o->val, o->has_arg ? arg : "");
84         }
85     }
86     printf("%s", ds.string);
87     ds_destroy(&ds);
88 }
89
90 /* Runs the command designated by argv[0] within the command table specified by
91  * 'commands', which must be terminated by a command whose 'name' member is a
92  * null pointer.
93  *
94  * Command-line options should be stripped off, so that a typical invocation
95  * looks like "run_command(argc - optind, argv + optind, my_commands);". */
96 void
97 run_command(int argc, char *argv[], const struct command commands[])
98 {
99     const struct command *p;
100
101     if (argc < 1) {
102         ovs_fatal(0, "missing command name; use --help for help");
103     }
104
105     for (p = commands; p->name != NULL; p++) {
106         if (!strcmp(p->name, argv[0])) {
107             int n_arg = argc - 1;
108             if (n_arg < p->min_args) {
109                 VLOG_FATAL( "'%s' command requires at least %d arguments",
110                             p->name, p->min_args);
111             } else if (n_arg > p->max_args) {
112                 VLOG_FATAL("'%s' command takes at most %d arguments",
113                            p->name, p->max_args);
114             } else {
115                 p->handler(argc, argv);
116                 if (ferror(stdout)) {
117                     VLOG_FATAL("write to stdout failed");
118                 }
119                 if (ferror(stderr)) {
120                     VLOG_FATAL("write to stderr failed");
121                 }
122                 return;
123             }
124         }
125     }
126
127     VLOG_FATAL("unknown command '%s'; use --help for help", argv[0]);
128 }
129 \f
130 /* Process title. */
131
132 #ifdef __linux__
133 static struct ovs_mutex proctitle_mutex = OVS_MUTEX_INITIALIZER;
134
135 /* Start of command-line arguments in memory. */
136 static char *argv_start OVS_GUARDED_BY(proctitle_mutex);
137
138 /* Number of bytes of command-line arguments. */
139 static size_t argv_size OVS_GUARDED_BY(proctitle_mutex);
140
141 /* Saved command-line arguments. */
142 static char *saved_proctitle OVS_GUARDED_BY(proctitle_mutex);
143
144 /* Prepares the process so that proctitle_set() can later succeed.
145  *
146  * This modifies the argv[] array so that it no longer points into the memory
147  * that it originally does.  Later, proctitle_set() might overwrite that
148  * memory.  That means that this function should be called before anything else
149  * that accesses the process's argv[] array.  Ideally, it should be called
150  * before anything else, period, at the very beginning of program
151  * execution.  */
152 void
153 proctitle_init(int argc, char **argv)
154 {
155     int i;
156
157     assert_single_threaded();
158     if (!argc || !argv[0]) {
159         /* This situation should never occur, but... */
160         return;
161     }
162
163     ovs_mutex_lock(&proctitle_mutex);
164     /* Specialized version of first loop iteration below. */
165     argv_start = argv[0];
166     argv_size = strlen(argv[0]) + 1;
167     argv[0] = xstrdup(argv[0]);
168
169     for (i = 1; i < argc; i++) {
170         size_t size = strlen(argv[i]) + 1;
171
172         /* Add (argv[i], strlen(argv[i])+1) to (argv_start, argv_size). */
173         if (argv[i] + size == argv_start) {
174             /* Arguments grow downward in memory. */
175             argv_start -= size;
176             argv_size += size;
177         } else if (argv[i] == argv_start + argv_size) {
178             /* Arguments grow upward in memory. */
179             argv_size += size;
180         } else {
181             /* Arguments not contiguous.  (Is this really Linux?) */
182         }
183
184         /* Copy out the old argument so we can reuse the space. */
185         argv[i] = xstrdup(argv[i]);
186     }
187     ovs_mutex_unlock(&proctitle_mutex);
188 }
189
190 /* Changes the name of the process, as shown by "ps", to the program name
191  * followed by 'format', which is formatted as if by printf(). */
192 void
193 proctitle_set(const char *format, ...)
194 {
195     va_list args;
196     int n;
197
198     ovs_mutex_lock(&proctitle_mutex);
199     if (!argv_start || argv_size < 8) {
200         goto out;
201     }
202
203     if (!saved_proctitle) {
204         saved_proctitle = xmemdup(argv_start, argv_size);
205     }
206
207     va_start(args, format);
208     n = snprintf(argv_start, argv_size, "%s: ", program_name);
209     if (n < argv_size) {
210         n += vsnprintf(argv_start + n, argv_size - n, format, args);
211     }
212     if (n >= argv_size) {
213         /* The name is too long, so add an ellipsis at the end. */
214         strcpy(&argv_start[argv_size - 4], "...");
215     } else {
216         /* Fill the extra space with null bytes, so that trailing bytes don't
217          * show up in the command line. */
218         memset(&argv_start[n], '\0', argv_size - n);
219     }
220     va_end(args);
221
222 out:
223     ovs_mutex_unlock(&proctitle_mutex);
224 }
225
226 /* Restores the process's original command line, as seen by "ps". */
227 void
228 proctitle_restore(void)
229 {
230     ovs_mutex_lock(&proctitle_mutex);
231     if (saved_proctitle) {
232         memcpy(argv_start, saved_proctitle, argv_size);
233         free(saved_proctitle);
234         saved_proctitle = NULL;
235     }
236     ovs_mutex_unlock(&proctitle_mutex);
237 }
238 #else  /* !__linux__ */
239 /* Stubs that don't do anything on non-Linux systems. */
240
241 void
242 proctitle_init(int argc OVS_UNUSED, char **argv OVS_UNUSED)
243 {
244 }
245
246 #if !(defined(__FreeBSD__) || defined(__NetBSD__))
247 /* On these platforms we #define this to setproctitle. */
248 void
249 proctitle_set(const char *format OVS_UNUSED, ...)
250 {
251 }
252 #endif
253
254 void
255 proctitle_restore(void)
256 {
257 }
258 #endif  /* !__linux__ */