-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpmt.c
801 lines (711 loc) · 14.9 KB
/
httpmt.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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//
// HTTPMT.C HTTPサーバー関数
//
// マルチスレッドモデル
//
#include "httpMT.h"
//
// Internal linkage
//
static SOCKET listenSocket;
static char szWebRoot[_MAX_PATH];
static HWND ghwnd;
static UINT guAppMsg;
HANDLE ghExit;
DWORD gdwListenThread;
////////////////////////////////////////////////////////////
BOOL StartHTTP(LPHTTPSERVINFO lpInfo)
{
SOCKADDR_IN saServer;
LPSERVENT lpServEnt;
unsigned ThreadAddr;
char szBuf[256];
char szAddress[80];
DWORD dwAddrStrLen;
int nRet;
//
// Save the Window handle and message
// ID for further use
//
ghwnd = lpInfo->hwnd;
guAppMsg = lpInfo->uMsgApp;
if (lpInfo->lpRootDir != NULL)
strcpy(szWebRoot, lpInfo->lpRootDir);
else
strcpy(szWebRoot, "/WebPages");
//
// Create the exit signal event object
//
ghExit = CreateEvent(NULL, // Security
TRUE, // Manual reset
FALSE, // Initial State
NULL); // Name
if (ghExit == NULL)
return FALSE;
//
// Create a TCP/IP stream socket
//
listenSocket = socket(AF_INET,
SOCK_STREAM,
IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
LogWinSockError(ghwnd,
"Could not create listen socket",
WSAGetLastError());
return FALSE;
}
//
// If a specific port number was specified
// then use it
//
if (lpInfo->nPort != 0)
saServer.sin_port = htons(lpInfo->nPort);
else
{
//
// Find a port number
//
lpServEnt = getservbyname("http", "tcp");
if (lpServEnt != NULL)
saServer.sin_port = lpServEnt->s_port;
else
saServer.sin_port = htons(HTTPPORT);
}
//
// Fill in the rest of the address structure
//
saServer.sin_family = AF_INET;
saServer.sin_addr.s_addr = INADDR_ANY;
//
// bind our name to the socket
//
nRet = bind(listenSocket,
(LPSOCKADDR)&saServer,
sizeof(struct sockaddr));
if (nRet == SOCKET_ERROR)
{
LogWinSockError(ghwnd,
"bind() error",
WSAGetLastError());
closesocket(listenSocket);
return FALSE;
}
//
// Set the socket to listen
//
nRet = listen(listenSocket, SOMAXCONN);
if (nRet == SOCKET_ERROR)
{
LogWinSockError(ghwnd,
"listen() error",
WSAGetLastError());
closesocket(listenSocket);
return FALSE;
}
//
// Create the listening thread
//
gdwListenThread = _beginthreadex(
NULL, // Security
0, // Stack size
ListenThread,// Function address
&ghExit, // Argument
0, // Init flag
&ThreadAddr);// Thread address
if (!gdwListenThread)
{
LogEvent(ghwnd,
"Could not create listening thread: %d",
GetLastError());
closesocket(listenSocket);
return FALSE;
}
//
// Display the host name and address
//
gethostname(szBuf, sizeof(szBuf));
dwAddrStrLen = sizeof(szAddress);
GetLocalAddress(szAddress, &dwAddrStrLen);
LogEvent(ghwnd,
"HTTP Server Started: %s [%s] on port %d",
szBuf,
szAddress,
htons(saServer.sin_port));
return TRUE;
}
////////////////////////////////////////////////////////////
void StopHTTP()
{
int nRet;
//
// Signal the exit event
//
SetEvent(ghExit);
//
// Close the listening socket
//
nRet = closesocket(listenSocket);
//
// And wait for the listen thread to stop
//
nRet = WaitForSingleObject((HANDLE)gdwListenThread, 10000);
if (nRet == WAIT_TIMEOUT)
LogEvent(ghwnd, "TIMEOUT waiting for ListenThread");
CloseHandle((HANDLE)gdwListenThread);
CloseHandle(ghExit);
LogEvent(ghwnd, "Server Stopped");
}
////////////////////////////////////////////////////////////
unsigned __stdcall ListenThread(void *pVoid)
{
SOCKET socketClient;
unsigned ThreadAddr;
DWORD dwClientThread;
SOCKADDR_IN SockAddr;
LPREQUEST lpReq;
int nLen;
DWORD dwRet;
HANDLE hNoClients;
LPHANDLE pHandle = (LPHANDLE)pVoid;
//
// Initialize client thread count to 0
//
hNoClients = InitClientCount();
//
// Loop forever accepting connections
//
while(1)
{
//
// Block on accept()
//
nLen = sizeof(SOCKADDR_IN);
socketClient = accept(listenSocket,
(LPSOCKADDR)&SockAddr,
&nLen);
if (socketClient == INVALID_SOCKET)
{
//
// StopHTTP() closes the listening socket
// when it wants this thread to stop.
break;
}
//
// We have a connection
//
LogEvent(ghwnd,
"Connection accepted on socket:%d from:%s",
socketClient,
inet_ntoa(SockAddr.sin_addr));
//
// Allocate parms for client and fill in defaults
//
lpReq = malloc(sizeof(REQUEST));
if (lpReq == NULL)
{
LogEvent(ghwnd,
"No memory for client request");
continue;
}
lpReq->hExit = *pHandle;
lpReq->Socket = socketClient;
lpReq->dwConnectTime = GetTickCount();
lpReq->hFile = INVALID_HANDLE_VALUE;
lpReq->dwRecv = 0;;
lpReq->dwSend = 0;
//
// Start a client thread to handle this request
//
dwClientThread = _beginthreadex(
NULL, // Security
0, // Stack size
ClientThread, // Thread function
lpReq, // Argument
0, // Init flag
&ThreadAddr); // Thread address
if (!dwClientThread)
{
LogEvent(ghwnd, "Couldn't start client thread");
}
//
// We won't be using client thread handles,
// so we close them when they are created.
// The thread will continue to execute.
//
CloseHandle((HANDLE)dwClientThread);
}
//
// Wait for exit event
//
WaitForSingleObject((HANDLE)*pHandle, INFINITE);
//
// Wait for ALL clients to exit
//
dwRet = WaitForSingleObject(hNoClients, 5000);
if (dwRet == WAIT_TIMEOUT)
{
LogEvent(ghwnd,
"One or more client threads did not exit");
}
DeleteClientCount();
return 0;
}
////////////////////////////////////////////////////////////
unsigned __stdcall ClientThread(void *pVoid)
{
int nRet;
BYTE buf[1024];
LPREQUEST lpReq = (LPREQUEST)pVoid;
//
// Count this client
//
IncrementClientCount();
//
// Recv the request data
//
if (!RecvRequest(lpReq, buf, sizeof(buf)))
{
CloseConnection(lpReq);
free(lpReq);
DecrementClientCount();
return 0;
}
//
// Parse the request info
//
nRet = ParseRequest(lpReq, buf);
if (nRet)
{
SendError(lpReq, nRet);
CloseConnection(lpReq);
free(lpReq);
DecrementClientCount();
return 0;
}
//
// Send the file to the client
//
SendFile(lpReq);
//
// Clean up
CloseConnection(lpReq);
free(pVoid);
//
// Subtract this client
//
DecrementClientCount();
return 0;
}
////////////////////////////////////////////////////////////
BOOL RecvRequest(LPREQUEST lpReq, LPBYTE pBuf, DWORD dwBufSize)
{
WSABUF wsabuf;
WSAOVERLAPPED over;
DWORD dwRecv;
DWORD dwFlags;
DWORD dwRet;
HANDLE hEvents[2];
BOOL fPending;
int nRet;
//
// Zero the buffer so the recv is null-terminated
//
memset(pBuf, 0, dwBufSize);
//
// Setup the WSABUF and WSAOVERLAPPED structures
//
wsabuf.buf = pBuf;
wsabuf.len = dwBufSize;
over.hEvent = WSACreateEvent();
dwFlags = 0;
fPending = FALSE;
nRet = WSARecv(lpReq->Socket, // Socket
&wsabuf, // WSABUF
1, // Number of buffers
&dwRecv, // Bytes received
&dwFlags, // Flags
&over, // WSAOVERLAPPED
NULL); // Completion function
if (nRet != 0)
{
if (WSAGetLastError() != WSA_IO_PENDING)
{
LogWinSockError(ghwnd,
"WSARecv()",
WSAGetLastError());
CloseHandle(over.hEvent);
return FALSE;
}
else
fPending = TRUE;
}
//
// If the I/O isn't finished...
//
if (fPending)
{
//
// Wait for the request to complete or the exit event
//
hEvents[0] = over.hEvent;
hEvents[1] = lpReq->hExit;
dwRet = WaitForMultipleObjects(2,
hEvents,
FALSE,
INFINITE);
//
// Was the recv event signaled?
//
if (dwRet != 0)
{
CloseHandle(over.hEvent);
return FALSE;
}
if (!WSAGetOverlappedResult(lpReq->Socket,
&over,
&dwRecv,
FALSE,
&dwFlags))
CloseHandle(over.hEvent);
return FALSE;
}
//
// Recv event is complete -- keep statistics
//
lpReq->dwRecv += dwRecv;
CloseHandle(over.hEvent);
return TRUE;
}
////////////////////////////////////////////////////////////
int ParseRequest(LPREQUEST lpReq, LPBYTE lpBuf)
{
char szSeps[] = " \n";
char *cpToken;
//
// Don't let requests include ".." characters
// in requests
//
if (strstr(lpBuf, "..") != NULL)
{
// Send "bad request" error
return(HTTP_STATUS_BADREQUEST);
}
//
// Determine request method
//
cpToken = strtok(lpBuf, szSeps);
if (!_stricmp(cpToken, "GET"))
lpReq->nMethod = METHOD_GET;
else
{
// Send "not implemented" error
return(HTTP_STATUS_NOTIMPLEMENTED);
}
//
// Get the file name
//
cpToken = strtok(NULL, szSeps);
if (cpToken == NULL)
{
// Send "bad request" error
return(HTTP_STATUS_BADREQUEST);
}
strcpy(lpReq->szFileName, szWebRoot);
if (strlen(cpToken) > 1)
strcat(lpReq->szFileName, cpToken);
else
strcat(lpReq->szFileName, "/index.html");
return 0;
}
////////////////////////////////////////////////////////////
void CloseConnection(LPREQUEST lpReq)
{
HTTPSTATS stats;
int nRet;
//
// Log the event and close the socket
//
LogEvent(ghwnd,
"Closing socket: %d",
lpReq->Socket);
nRet = closesocket(lpReq->Socket);
if (nRet == SOCKET_ERROR)
{
LogWinSockError(ghwnd,
"closesocket()",
WSAGetLastError());
}
//
// Give the user interface the stats
//
stats.dwElapsedTime =
(GetTickCount() - lpReq->dwConnectTime);
stats.dwRecv = lpReq->dwRecv;
stats.dwSend = lpReq->dwSend;
SendMessage(ghwnd,
guAppMsg,
HTTP_STATS_MSG,
(LPARAM)&stats);
}
////////////////////////////////////////////////////////////
void SendFile(LPREQUEST lpReq)
{
//
// Open the file for reading
//
lpReq->hFile = CreateFile(lpReq->szFileName,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (lpReq->hFile == INVALID_HANDLE_VALUE)
{
SendMessage(ghwnd,
guAppMsg,
HTTP_FILENOTFOUND_MSG,
(LPARAM)(LPCSTR)lpReq->szFileName);
// Send "404 Not Found" error
SendError(lpReq, HTTP_STATUS_NOTFOUND);
return;
}
//
// Tell the user interface about the file hit
// (Sending just the request portion -- without
// the root web directory portion
//
SendMessage(ghwnd,
guAppMsg,
HTTP_FILEOK_MSG,
(LPARAM)(LPCSTR)&lpReq->szFileName[strlen(szWebRoot)]);
//
// Send the file contents to the client
//
SendFileContents(lpReq);
//
// Close the file
//
if (CloseHandle(lpReq->hFile))
lpReq->hFile = INVALID_HANDLE_VALUE;
else
LogEvent(ghwnd,
"Error closing file: %d",
GetLastError());
}
////////////////////////////////////////////////////////////
void SendFileContents(LPREQUEST lpReq)
{
static BYTE buf[1024];
DWORD dwRead;
BOOL fRet;
//
// Read and send data until EOF
//
while(1)
{
//
// Read a buffer full from the file
//
fRet = ReadFile(lpReq->hFile,
buf,
sizeof(buf),
&dwRead,
NULL);
if (!fRet)
{
// Send "404 Not Found" error
SendError(lpReq, HTTP_STATUS_SERVERERROR);
break;
}
if (dwRead == 0)
break;
//
// Send this buffer to the client
//
if (!SendBuffer(lpReq, buf, dwRead))
break;
//
// Add for statistics
//
lpReq->dwSend += dwRead;
}
}
////////////////////////////////////////////////////////////
BOOL SendBuffer(LPREQUEST lpReq, LPBYTE pBuf, DWORD dwBufSize)
{
WSABUF wsabuf;
WSAOVERLAPPED over;
DWORD dwRecv;
DWORD dwFlags;
DWORD dwRet;
HANDLE hEvents[2];
BOOL fPending;
int nRet;
//
// Setup the WSABUF and WSAOVERLAPPED structures
//
wsabuf.buf = pBuf;
wsabuf.len = dwBufSize;
over.hEvent = WSACreateEvent();
fPending = FALSE;
nRet = WSASend(lpReq->Socket, // Socket
&wsabuf, // WSABUF
1, // Number of buffers
&dwRecv, // Bytes received
0, // Flags
&over, // WSAOVERLAPPED
NULL); // Completion function
if (nRet != 0)
{
if (WSAGetLastError() == WSA_IO_PENDING)
fPending = TRUE;
else
{
LogWinSockError(ghwnd,
"WSASend()",
WSAGetLastError());
CloseHandle(over.hEvent);
return FALSE;
}
}
//
// If the I/O isn't finished...
//
if (fPending)
{
//
// Wait for the request to complete
// or the exit event to be signaled
//
hEvents[0] = over.hEvent;
hEvents[1] = lpReq->hExit;
dwRet = WaitForMultipleObjects(2,
hEvents,
FALSE,
INFINITE);
//
// Was the recv event signaled?
//
if (dwRet != 0)
{
CloseHandle(over.hEvent);
return FALSE;
}
//
// Get I/O result
//
if (!WSAGetOverlappedResult(lpReq->Socket,
&over,
&dwRecv,
FALSE,
&dwFlags))
{
LogWinSockError(ghwnd,
"WSAGetOverlappedResult()",
WSAGetLastError());
CloseHandle(over.hEvent);
return FALSE;
}
}
CloseHandle(over.hEvent);
return TRUE;
}
////////////////////////////////////////////////////////////
void SendError(LPREQUEST lpReq, UINT uError)
{
static char szMsg[512];
static char *szStatMsgs [] = {
"200 OK",
"201 Created",
"202 Accepted",
"204 No Content",
"301 Moved Permanently",
"302 Moved Temporarily",
"304 Not Modified",
"400 Bad Request",
"401 Unauthorized",
"403 Forbidden",
"404 Not Found",
"500 Internal Server Error",
"501 Not Implemented",
"502 Bad Gateway",
"503 Service Unavailable"
};
#define NUMSTATMSGS sizeof(szStatMsgs) / sizeof(szStatMsgs[0])
if (uError < 0 || uError > NUMSTATMSGS)
return;
wsprintf(szMsg, "<body><h1>%s</h1></body>",
szStatMsgs[uError]);
send(lpReq->Socket,
szMsg,
strlen(szMsg),
0);
}
////////////////////////////////////////////////////////////
void LogEvent(HWND hwnd, LPCSTR lpFormat, ...)
{
va_list Marker;
char szBuf[256];
// Write text to string
// and append to edit control
va_start(Marker, lpFormat);
vsprintf(szBuf, lpFormat, Marker);
va_end(Marker);
SendMessage(ghwnd,
guAppMsg,
HTTP_EVENT_MSG,
(LPARAM)szBuf);
}
////////////////////////////////////////////////////////////
void LogWinSockError(HWND hwnd, LPCSTR lpText, int nErrorCode)
{
char szBuf[256];
szBuf[0] = '\0';
LoadString(GetWindowInstance(hwnd),
nErrorCode,
szBuf,
sizeof(szBuf));
LogEvent(hwnd, "%s : %s", lpText, szBuf);
}
////////////////////////////////////////////////////////////
int GetLocalAddress(LPSTR lpStr, LPDWORD lpdwStrLen)
{
struct in_addr *pinAddr;
LPHOSTENT lpHostEnt;
int nRet;
int nLen;
//
// Get our local name
//
nRet = gethostname(lpStr, *lpdwStrLen);
if (nRet == SOCKET_ERROR)
{
lpStr[0] = '\0';
return SOCKET_ERROR;
}
//
// "Lookup" the local name
//
lpHostEnt = gethostbyname(lpStr);
if (lpHostEnt == NULL)
{
lpStr[0] = '\0';
return SOCKET_ERROR;
}
//
// Format first address in the list
//
pinAddr = ((LPIN_ADDR)lpHostEnt->h_addr);
nLen = strlen(inet_ntoa(*pinAddr));
if ((DWORD)nLen > *lpdwStrLen)
{
*lpdwStrLen = nLen;
WSASetLastError(WSAEINVAL);
return SOCKET_ERROR;
}
*lpdwStrLen = nLen;
strcpy(lpStr, inet_ntoa(*pinAddr));
return 0;
}