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