-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd_line.c
More file actions
executable file
·346 lines (298 loc) · 12 KB
/
cmd_line.c
File metadata and controls
executable file
·346 lines (298 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// --------------------------------------------------------
// uhttps : a minimal web server which compile under MacOS, Linux and Windows
// by Ph. Jounin September 2025
//
// License: GPLv2
// Sources :
// - nweb23.c from IBM and Nigel Griffiths
// - mweb.cpp from Ph. Jounin
// - uweb.cpp from Ph. Jounin
// ---------------------------------------------------------
// Changes:
#include "compat.h"
#include "uhttps.h"
#include "log.h"
/* Print usage/help text (kept local to avoid extra dependencies) */
void print_usage(FILE *out)
{
fprintf(out,
"uhttps - minimal static web server\n"
"\nUsage:\n"
" %s [options]\n"
"\nNetworking:\n"
" -4 IPv4 only\n"
" -6 IPv6 only\n"
" -i ADDR Bind to this local address (IPv4 or IPv6)\n"
" -p PORT HTTP port (default %s)\n"
" --tls Enable TLS (HTTPS)\n"
" --tls-port PORT HTTPS port (default %s)\n"
" --cert FILE PEM certificate (fullchain)\n"
" --key FILE PEM private key\n"
" --tls-dir DIR Directory where OpenSSL DLLs are located (Windows)\n"
" --redirect-http When TLS is enabled, redirect plain HTTP to https://\n"
"\nContent & files:\n"
" -d DIR Web root (default is current directory)\n"
" -x FILE Default index file for directories (default %s)\n"
" -e EXT if url is not found, try with EXT appended (no default)\n"
" -c t|b|TYPE Default content-type for unknown extensions\n"
" 't' or -ct => %s | 'b' or -cb => %s\n"
"\nConcurrency & logs:\n"
" -s N Max simultaneous connections (default %d)\n"
" -g MSEC Slow down: wait MSEC between chunks (dev/testing)\n"
" -v Increase verbosity (repeatable)\n"
" -q Decrease verbosity\n"
" -t Prefix logs with timestamps\n"
" -V Print version and exit\n"
" -h, --help Show this help and exit\n",
"uhttps",
DEFAULT_HTTP_PORT,
DEFAULT_TLS_PORT,
DEFAULT_HTMLFILE,
// DEFAULT_AUTO_EXTENSION, (NULL by default)
DEFAULT_TEXT_TYPE,
DEFAULT_BINARY_TYPE,
DEFAULT_MAXTHREADS
);
}; // Usage
// load default configuration
struct S_Settings sSettings =
{
WARN, FALSE, // logging
DEFAULT_MAXTHREADS, FALSE, // system
TRUE, TRUE, NULL, // Global Network
DEFAULT_HTTP_PORT, // HTTP settings
FALSE, "cert.pem", "private.key", DEFAULT_TLS_PORT,
DEFAULT_SSL_DIR, FALSE, // tls settings
".", DEFAULT_HTMLFILE,
DEFAULT_AUTO_EXTENSION, NULL // HTML settings
};
// -------------------
// inits
// -------------------
/* Fail with message + usage */
void die_bad(const char *msg, const char *opt)
{
fprintf(stderr, "Error: %s%s%s\n\n",
msg ? msg : "invalid option",
(opt ? " : " : ""), (opt ? opt : ""));
print_usage(stderr);
exit(1);
};
/* Parse an integer with bounds (inclusive). If lo==hi, skip range check. */
void parse_int_bounded(const char *opt, const char *val, int *out, int lo, int hi)
{
char *end = NULL;
long v = strtol(val, &end, 10);
if (!val || *val == '\0' || end == val || *end != '\0')
die_bad("invalid integer value for", opt);
if (lo != hi && (v < lo || v > hi))
die_bad("out-of-range value for", opt);
*out = (int)v;
} // parse_int_bounded
/* Set default content-type from token:
- "t" / "text" / "text/plain" => DEFAULT_TEXT_TYPE
- "b" / "binary" / "application/octet-stream" => DEFAULT_BINARY_TYPE
- anything else is taken literally as a MIME type string */
void set_default_ctype(const char *tok)
{
if (!tok || !*tok) die_bad("missing value for", "-c");
if (tok[1] == '\0')
{
char ch = (char)tolower((unsigned char)tok[0]);
if (ch == 't') sSettings.szDefaultContentType = DEFAULT_TEXT_TYPE;
else if (ch == 'b') sSettings.szDefaultContentType = DEFAULT_BINARY_TYPE;
else die_bad("unknown -c value (use t|b|<mime>)", tok);
}
else if (strcasecmp(tok, "t") == 0 || strcasecmp(tok, "text") == 0 || strcasecmp(tok, "text/plain") == 0)
{
sSettings.szDefaultContentType = DEFAULT_TEXT_TYPE;
}
else if (strcasecmp(tok, "b") == 0 || strcasecmp(tok, "binary") == 0 || strcasecmp(tok, "application/octet-stream") == 0)
{
sSettings.szDefaultContentType = DEFAULT_BINARY_TYPE;
}
else
{
sSettings.szDefaultContentType = tok; /* literal MIME string */
}
};
// process args (mostly populate settings structure)
// loosely processed : (user can crash with invalid args, may be not anymore)
int ParseCmdLine(int argc, char *argv[])
{
// Defaults are set elsewhere (sSettings is global). We only parse/override here.
for (int ark=1; ark < argc; ark++)
{
const char *arg = argv[ark];
if (!arg || !*arg) continue;
/* Non-option token? treat as error to keep interface clean */
if (arg[0] != '-') {
die_bad("unexpected positional argument", arg);
}
/* ---- Long options: --name or --name=value ---- */
if (arg[1] == '-') {
const char *name = arg + 2;
const char *eq = strchr(name, '=');
size_t namelen = eq ? (size_t)(eq - name) : strlen(name);
const char *val = NULL;
/* Compare name (len-limited) to a literal */
#define LONGOPT_IS(lit) (strncasecmp(name, (lit), namelen) == 0 && (lit)[namelen] == '\0')
/* Fetch value from "--opt=value" or the next argv token */
#define TAKE_STR_VALUE(entry, optlit) \
do { \
if (eq) { \
val = eq + 1; \
if (!*val) die_bad("missing value for", "--" optlit); \
} else { \
if (++ark >= argc) die_bad("missing value for", "--" optlit); \
val = argv[ark]; \
} \
entry = (char *) val; \
} while (0)
if (LONGOPT_IS("help"))
{
print_usage(stdout);
exit(0);
}
else if (LONGOPT_IS("tls"))
{
if (eq) die_bad("option does not take a value", "--tls");
sSettings.bTLS = TRUE;
}
else if (LONGOPT_IS("redirect-http"))
{
if (eq) die_bad("option does not take a value", "--redirect-http");
sSettings.bRedirectHttp = TRUE;
}
else if (LONGOPT_IS("cert"))
TAKE_STR_VALUE(sSettings.tls_cert, "cert");
else if (LONGOPT_IS("key"))
TAKE_STR_VALUE(sSettings.tls_key, "key");
else if (LONGOPT_IS("tls-port"))
TAKE_STR_VALUE(sSettings.szTlsPort, "tls-port");
else if (LONGOPT_IS("tls-dir"))
TAKE_STR_VALUE(sSettings.szOpenSSLDir, "tls-dir");
else
die_bad("unknown option", arg);
continue;
}
/* ---- Short options: -p8080, -p 8080, -ct, -c t, -vvt, etc. ---- */
for (size_t k = 1; arg[k] != '\0'; k++)
{
char ch = arg[k];
const char *val = NULL; /* for options that take a value */
// Helpers: value is the rest of this token or next argv
// TAKE_NEXT_VALUE is string type if low_int=high_int=0
#define REMAINS (&arg[k+1])
#define TAKE_NEXT_VALUE(optlit) \
do { \
if (REMAINS[0]) { \
val = REMAINS; \
k = strlen(arg) - 1; /* consume the rest of this token */ \
} else { \
if (++ark >= argc) die_bad("missing value for", optlit); \
val = argv[ark]; \
} \
} while (0)
switch (ch)
{
case '4': sSettings.bIPv6 = FALSE; break;
case '6': sSettings.bIPv4 = FALSE; break;
case 't': sSettings.timestamp = TRUE; break;
case 'q': sSettings.uVerbose--; break;
case 'v': sSettings.uVerbose++; break;
case 'V':
/* Print version and exit. Keep this simple to avoid extra deps. */
fprintf(stdout, "uhttps version %s\n", UHTTPS_VERSION);
exit(0);
case 'h':
print_usage(stdout);
exit(0);
case 'd':
TAKE_NEXT_VALUE("-d");
sSettings.szDirectory = (char *) val;
break;
case 'i':
TAKE_NEXT_VALUE("-i");
sSettings.szBoundTo = (char *) val;
break;
case 'p':
TAKE_NEXT_VALUE("-p");
sSettings.szHTTPPort = (char *) val;
break;
case 's':
TAKE_NEXT_VALUE("-s");
parse_int_bounded("-s", val, &sSettings.max_threads, 1, 1<<20);
break;
case 'g':
TAKE_NEXT_VALUE("-g");
parse_int_bounded("-g", val, &sSettings.slow_down, 0, 3600000);
break;
case 'x':
TAKE_NEXT_VALUE("-x");
sSettings.szDefaultHtmlFile = (char *) val;
break;
case 'e':
TAKE_NEXT_VALUE("-e");
sSettings.szAutoExtension = (char *) val; // .html and hmtl are ok
break;
case 'c':
/* Accept "-ct" / "-cb" / "-c t" / "-c b" / "-c application/json" */
if (REMAINS[0]) {
set_default_ctype(REMAINS);
k = strlen(arg) - 1; /* we consumed the rest of token */
} else {
if (++ark >= argc) die_bad("missing value for", "-c");
const char *v = argv[ark];
/* Allow legacy tokens "ct"/"cb" as well */
if (strcasecmp(v, "ct") == 0) set_default_ctype("t");
else if (strcasecmp(v, "cb") == 0) set_default_ctype("b");
else set_default_ctype(v);
}
break;
default:
{ char unk[3] = {'-', ch, 0};
die_bad("unknown option", unk); }
break;
} /* switch ch */
/* If we consumed the rest of a clustered token for a value option,
the inner loop already advanced 'k' to the string end. */
} /* for each char in clustered short option */
} /* for argv */
return 0;
} // ParseCmdLine
// check that args are ok
int SanityChecks (const struct S_Settings *p)
{
if (p->bTLS) {
if (!p->tls_cert || !p->tls_key) {
fprintf(stderr, "TLS enabled but --cert/--key not both provided\n");
return FALSE;
}
}
/* Final sanity: keep at least one IP family */
if (!sSettings.bIPv4 && !sSettings.bIPv6)
{
die_bad("IPv4 and IPv6 both disabled (use -4 or -6, not both)", NULL);
}
/* Clamp verbosity into known range if your enum defines bounds */
if (sSettings.uVerbose < FATAL) sSettings.uVerbose = FATAL;
if (sSettings.uVerbose > ALL) sSettings.uVerbose = ALL;
return TRUE;
}
// main program : read args, create listening socket and wait for incoming connections
int main(int argc, char *argv[])
{
ParseCmdLine(argc, argv); // override default settings
if (! SanityChecks (& sSettings))
exit(1);
if (! Setup ())
exit(1);
for ( ; ; )
{
doLoop ();
} // for (; ; )
// cleanup
Cleanup();
return 0;
}