forked from avih/miniweb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
miniweb.c
451 lines (397 loc) · 12.4 KB
/
miniweb.c
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/////////////////////////////////////////////////////////////////////////////
//
// miniweb.c
//
// MiniWeb start-up code
//
/////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include "httppil.h"
#include "httpapi.h"
#include "revision.h"
#ifdef MEDIA_SERVER
#include "mediaserver.h"
#endif
#include "win32/win_compat.h"
#ifdef HAS_POSIX_TIMERS
#include <signal.h>
#include <time.h>
#endif
#define APP_NAME "MiniWeb-avih"
int uhMpd(UrlHandlerParam* param);
int ehMpd(MW_EVENT msg, int argi, void* argp);
int uhStats(UrlHandlerParam* param);
int uhVod(UrlHandlerParam* param);
int uhLib(UrlHandlerParam* param);
int uhVodStream(UrlHandlerParam* param);
int uhStream(UrlHandlerParam* param);
int ehVod(MW_EVENT msg, int argi, void* argp);
int uhTest(UrlHandlerParam* param);
int uh7Zip(UrlHandlerParam* param);
int uhFileStream(UrlHandlerParam* param);
int uhAsyncDataTest(UrlHandlerParam* param);
int uhRTSP(UrlHandlerParam* param);
int uhSerial(UrlHandlerParam* param);
UrlHandler urlHandlerList[]={
{"stats", uhStats, NULL},
#ifdef ENABLE_SERIAL
{"serial", uhSerial, NULL},
#endif
#ifdef HAVE_THREAD
{"async", uhAsyncDataTest, NULL},
#endif
#ifdef MEDIA_SERVER
{"test.sdp", uhRTSP, NULL},
{"MediaServer/VideoItems/", uhMediaItemsTranscode, ehMediaItemsEvent},
#endif
#ifdef _7Z
{"7z", uh7Zip, NULL},
#endif
#ifdef _MPD
{"mpd", uhMpd, ehMpd},
#endif
#ifdef _VOD
{"vodstream", uhVodStream,NULL},
{"vodlib", uhLib,0},
{"vodplay", uhVod,ehVod},
{"stream", uhStream,NULL},
#endif
{NULL},
};
#ifndef DISABLE_BASIC_WWWAUTH
AuthHandler authHandlerList[]={
{"stats", "user", "pass", "group=admin", ""},
{NULL}
};
#endif
HttpParam httpParam;
extern FILE *fpLog;
//////////////////////////////////////////////////////////////////////////
// callback from the web server whenever it needs to substitute variables
//////////////////////////////////////////////////////////////////////////
int DefaultWebSubstCallback(SubstParam* sp)
{
// the maximum length of variable value should never exceed the number
// given by sp->iMaxValueBytes
if (!strcmp(sp->pchParamName,"mykeyword")) {
return sprintf(sp->pchParamValue, "%d", 1234);
}
return -1;
}
//////////////////////////////////////////////////////////////////////////
// callback from the web server whenever it recevies posted data
//////////////////////////////////////////////////////////////////////////
int DefaultWebPostCallback(PostParam* pp)
{
int iReturn=WEBPOST_OK;
// by default redirect to config page
//strcpy(pp->chFilename,"index.htm");
return iReturn;
}
//////////////////////////////////////////////////////////////////////////
// callback from the web server whenever it receives a multipart
// upload file chunk
//////////////////////////////////////////////////////////////////////////
int DefaultWebFileUploadCallback(HttpMultipart *pxMP, OCTET *poData, size_t dwDataChunkSize)
{
// Do nothing with the data
int *fd = &pxMP->fd;
if (!poData) {
// to cleanup
if (*fd > 0) {
close(*fd);
*fd = 0;
}
return 0;
}
if (!*fd) {
char filename[256];
snprintf(filename, sizeof(filename), "%s/%s", httpParam.pchWebPath, pxMP->pchFilename);
*fd = open(filename, O_CREAT | O_TRUNC | O_RDWR | O_BINARY, 0);
}
if (*fd <= 0) return -1;
if (write(pxMP->fd, poData, dwDataChunkSize) < 0) {
close(*fd);
*fd = -1;
return -1;
}
if (pxMP->oFileuploadStatus & HTTPUPLOAD_LASTCHUNK) {
close(*fd);
*fd = 0;
}
printf("Received %u bytes for multipart upload file %s\n", (unsigned int)dwDataChunkSize, pxMP->pchFilename);
return 0;
}
int Shutdown(mwShutdownCallback cb, unsigned int timeout)
{
//shutdown server
int rv = mwServerShutdown(&httpParam, cb, timeout);
fclose(fpLog);
UninitSocket();
return rv;
}
#define SHUTDOWN_TIMEOUT_MS 5000
#ifdef WIN32 /* Windows - Console control handler on ctrl-c (new thread) */
BOOL MiniWebQuit(DWORD arg) {
static int quitting = 0;
if (quitting) return 1; // shouldn't reenter on windows. regardless, already being handled
quitting = 1;
printf("\nCaught control signal (%d). Shutting down...\n", (int)arg);
// Shutdown() runs in the handler thread, waits for the server (main
// thread) to finish - up to timeout. Returns TRUE if stop succeeded.
if (Shutdown(0, SHUTDOWN_TIMEOUT_MS)) {
printf("Cannot shut down the server, killing it instead...\n");
return 0; // couldn't kill the server, let the system kill us.
}
// success, the program continues to finish main, don't let the system kill us.
// possibly we never get here - if main finishes before Shutdown returns.
return 1;
}
#else /* *nix - signal handler - main thread */
void onShutdown()
{
// Good to know. Now main can finish.
}
#ifdef HAS_POSIX_TIMERS
static void killIn(uint32_t timeout_ms)
{
static timer_t kill_timer;
struct itimerspec its;
struct sigevent sev;
static int killing = 0;
if (killing) return;
killing = 1;
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIGKILL;
sev.sigev_value.sival_ptr = &kill_timer;
if (timer_create(CLOCK_REALTIME, &sev, &kill_timer)) {
printf("Cannot set shutdown timeout. Kill manually if hangs.\n");
return;
}
its.it_value.tv_sec = timeout_ms / 1000;
its.it_value.tv_nsec = 1000000 * (timeout_ms % 1000);
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0;
timer_settime(kill_timer, 0, &its, NULL);
}
#endif
void MiniWebQuit(int arg) {
static int quitting = 0;
if (quitting) return;
quitting = 1;
printf("\nCaught signal (%d). Shutting down...\n", arg);
Shutdown(onShutdown, 0); // tell the server to shutdown but don't wait for it.
#ifdef HAS_POSIX_TIMERS
killIn(SHUTDOWN_TIMEOUT_MS);
#endif
}
#endif
// returns 0 on success (result with '\0' fits in max_bytes), -1 otherwise
int GetFullPath(char* buffer, char* argv0, char* path, int max_bytes)
{
char* p = strrchr(argv0, '/');
if (!p) p = strrchr(argv0, '\\');
if (!p) {
if (strlen(path) >= max_bytes)
return -1;
strcpy(buffer, path);
} else {
int l = p - argv0 + 1;
if (l + strlen(path) >= max_bytes)
return -1;
memcpy(buffer, argv0, l);
strcpy(buffer + l, path);
}
return 0;
}
#ifdef WIN32
#include <iphlpapi.h>
// returns number of printed interfaces
static int print_interfaces(const char *prefix, int port)
{
MIB_IPADDRTABLE *iptable = NULL;
DWORD tablesize = 0;
int i = 0;
if (ERROR_INSUFFICIENT_BUFFER == GetIpAddrTable(NULL, &tablesize, 1) &&
(iptable = (MIB_IPADDRTABLE*)malloc(tablesize)) &&
NO_ERROR == GetIpAddrTable(iptable, &tablesize, 1))
{
for (i = 0; i < iptable->dwNumEntries; i++) {
IN_ADDR ip = {0};
ip.S_un.S_addr = iptable->table[i].dwAddr;
printf ("%s%s:%d\n", prefix, inet_ntoa(ip), port);
}
}
if (iptable)
free(iptable);
return i;
}
#else
#include <sys/types.h>
#include <ifaddrs.h>
// returns number of printed interfaces
static int print_interfaces(const char *prefix, int port)
{
struct ifaddrs *ifaddr, *ifa;
char host[NI_MAXHOST];
int printed = 0;
if (getifaddrs(&ifaddr) == -1)
return 0;
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr &&
ifa->ifa_addr->sa_family == AF_INET && // ipv6??
!getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in),
host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST))
{
printed++;
printf("%s%s:%d (%s)\n", prefix, host, port,
ifa->ifa_name ? ifa->ifa_name : "???");
}
}
freeifaddrs(ifaddr);
return printed;
}
#endif
int cc_main(int argc,char* argv[])
{
fprintf(stderr,"%s https://github.com/avih/miniweb (built on %s)\n"
"Originally: (C)2005-2013 Written by Stanley Huang <[email protected]>\n\n",
APP_NAME, __DATE__);
#ifdef WIN32
SetConsoleCtrlHandler( (PHANDLER_ROUTINE) MiniWebQuit, TRUE );
#else
signal(SIGINT, MiniWebQuit);
signal(SIGTERM, MiniWebQuit);
signal(SIGPIPE, SIG_IGN);
#endif
//fill in default settings
mwInitParam(&httpParam);
httpParam.maxClients=32;
httpParam.httpPort = 80;
httpParam.pchWebPath[0] = '\0'; // filled below if no -r argument is given
#ifndef DISABLE_BASIC_WWWAUTH
httpParam.pxAuthHandler = authHandlerList;
#endif
httpParam.pxUrlHandler=urlHandlerList;
httpParam.flags=FLAG_DIR_LISTING;
httpParam.tmSocketExpireTime = 15;
httpParam.pfnPost = DefaultWebPostCallback;
#ifdef MEDIA_SERVER
httpParam.pfnFileUpload = TranscodeUploadCallback;
#else
httpParam.pfnFileUpload = DefaultWebFileUploadCallback;
#endif
const char *ifcarg = 0;
//parsing command line arguments
{
int i;
for (i=1;i<argc;i++) {
if (argv[i][0]=='-') {
switch (argv[i][1]) {
case 'h':
fprintf(stderr,"Usage: miniweb -h : display this help screen\n"
" -v : log status/error info\n"
" -p : specifiy http port [default 80]\n"
" -i : interface [default 0.0.0.0]\n"
" -r : specify http document directory [default htdocs]\n"
" -l : specify log file\n"
" -m : specifiy max clients [default 32]\n"
" -M : specifiy max clients per IP\n"
" -s : specifiy download speed limit in KB/s [default: none]\n"
" -n : disallow multi-part download [default: allow]\n"
" -d : disallow directory listing [default: allow]\n\n"
);
fflush(stderr);
exit(1);
case 'p':
if ((++i)<argc) httpParam.httpPort=atoi(argv[i]);
break;
case 'i':
if ((++i)<argc) httpParam.hlBindIP = inet_addr(argv[i]);
if (httpParam.hlBindIP) ifcarg = argv[i];
break;
case 'r':
if ((++i) >= argc || !argv[i][0] || strlen(argv[i]) >= sizeof(httpParam.pchWebPath)) {
fprintf(stderr, "Error: invalid or too long path argument\n");
return -1;
}
strcpy(httpParam.pchWebPath, argv[i]);
break;
case 'l':
if ((++i)<argc) fpLog=freopen(argv[i],"w",stderr);
break;
case 'm':
if ((++i)<argc) httpParam.maxClients=atoi(argv[i]);
break;
case 'M':
if ((++i)<argc) httpParam.maxClientsPerIP=atoi(argv[i]);
break;
case 's':
if ((++i)<argc) httpParam.maxDownloadSpeed=atoi(argv[i]);
break;
case 'n':
httpParam.flags |= FLAG_DISABLE_RANGE;
break;
case 'd':
httpParam.flags &= ~FLAG_DIR_LISTING;
break;
}
}
}
}
if (!httpParam.pchWebPath[0]) {
if (GetFullPath(httpParam.pchWebPath, argv[0], "htdocs", sizeof(httpParam.pchWebPath))) {
fprintf(stderr, "Error: root path ends up too long\n");
return -1;
}
}
{
int i;
int error = 0;
for (i = 0; urlHandlerList[i].pchUrlPrefix; i++) {
if (urlHandlerList[i].pfnEventHandler) {
if (urlHandlerList[i].pfnEventHandler(MW_PARSE_ARGS, urlHandlerList[i].pfnEventHandler, &httpParam))
error++;
}
}
if (error > 0) {
printf("Error parsing command line options\n");
return -1;
}
}
InitSocket();
{
int n;
if (ifcarg) {
printf("Host: %s:%d\n", ifcarg, (int)httpParam.httpPort);
} else {
printf("Host: port %d on all interfaces:\n", (int)httpParam.httpPort);
if (!print_interfaces(" ", httpParam.httpPort))
printf(" 0.0.0.0:%d (generic)\n", (int)httpParam.httpPort);
}
printf("Web root: %s\n",httpParam.pchWebPath);
printf("Max clients (per IP): %d (%d)\n",httpParam.maxClients, httpParam.maxClientsPerIP);
for (n=0;urlHandlerList[n].pchUrlPrefix;n++);
printf("URL handlers: %d\n",n);
if (httpParam.flags & FLAG_DIR_LISTING) printf("Dir listing enabled\n");
if (httpParam.flags & FLAG_DISABLE_RANGE) printf("Byte-range disabled\n");
fflush(stdout);
//register page variable substitution callback
//httpParam[i].pfnSubst=DefaultWebSubstCallback;
//start server
if (mwServerStart(&httpParam)) {
printf("Error starting HTTP server\n");
Shutdown(0, 0); // the server is not running but for the socket/log file.
} else {
mwHttpLoop(&httpParam);
printf("Shutdown complete\n");
}
}
// No need for Shutdown() here since it must have already happened:
// the only way for mwHttpLoop to exit is if hp->bKillWebserver, and
// it's set only from mwServerShutdown, and only Shutdown calls it.
return 0;
}
////////////////////////////// END OF FILE //////////////////////////////