-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.c
585 lines (427 loc) · 14 KB
/
http.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
/*
http.c - a simple web server to host HTML pages as the GUI.
Modifier: Ali.B
Originally Taken from http://www.paulgriffiths.net/program/c/webserv.php and modified to meet the requirements.
the original version of this code contains more .c files, for simplicity and learning purposes all of the .c modules were combined into a single file.
Major Modifications:
- buffer manipulation to parse the command and payload.
- bluetooth sending command messages according to the button clicked from the GUI.
- bluettoth sending payload assembled according to the given coordinates from the GUI.
- making a thread for the bluetooth server to handle incomming bluetooth messages at the same time of processing and hosting GUI(HTML pages).
- return_msg to display a text after a message is sent.
*/
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <ctype.h>
#include <sys/time.h>
#include <pthread.h>
#include "server.h"
#include "http.h"
//HTTP server resource path - modify if needed.
static char web_pages_path[20] = "./web_pages";
//Author: Ali.B
//thread function for bluetooth receive function
void *bt_main_recv(void *arg)
{
printf("Starting Bluetooth Server....Done!\n");
printf("BT Server: Awaiting connection from other device...\n");
printf("=====================================================\n");
while(1)
{
bt_recv();
}
return NULL;
}
//http main - this is where the whole system is started.
int main(int argc, char *argv[]) {
int sock;
int conn;
pid_t pid;
struct sockaddr_in servaddr;
printf("Starting Web Server....Done!\n");
printf("=====================================================\n");
//Create Socket
sock = socket(AF_INET, SOCK_STREAM, 0);
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERVER_PORT);
//Bind Socket
bind(sock, (struct sockaddr *) &servaddr, sizeof(servaddr));
//Listening Socket
listen(sock, LISTENQ);
pthread_t bt_thread;
//creates a new thread for bt_main_recv
if ( pthread_create( &bt_thread, NULL, bt_main_recv, NULL) ) {
printf("error creating thread.");
abort();
}
//endless loop for accepting connection and servicing
while ( 1 ) {
//Accept Connection
if ( (conn = accept(sock, NULL, NULL)) < 0 )
printf("Error on accepting Connection");
//use for to make a child process for http process
if ( (pid = fork()) == 0 ) {
//close listening socket...
if ( close(sock) < 0 )
printf("Error on close in child");
//and service http request
Service_Request(conn);
//close connected socket
if ( close(conn) < 0 )
printf("Error on close");
exit(EXIT_SUCCESS);
}
//close connected socket in parent process.
if ( close(conn) < 0 )
printf("Error on close in parent");
waitpid(-1, NULL, WNOHANG);
}
return EXIT_FAILURE; /* We shouldn't get here */
//joins the created thread to the main thread
if ( pthread_join ( bt_thread, NULL ) ) {
printf("error joining thread.");
abort();
}
}
/* Service an HTTP request */
int Service_Request(int conn) {
struct ReqInfo reqinfo;
int resource = 0;
InitReqInfo(&reqinfo);
/* Get HTTP request */
if ( Get_Request(conn, &reqinfo) < 0 )
return -1;
/* Check whether resource exists, whether we have permission
to access it, and update status code accordingly. */
if ( reqinfo.status == 200 )
if ( (resource = Check_Resource(&reqinfo)) < 0 ) {
if ( errno == EACCES )
reqinfo.status = 401;
else
reqinfo.status = 404;
}
/* Output HTTP response headers if we have a full request */
if ( reqinfo.type == FULL )
Output_HTTP_Headers(conn, &reqinfo);
/* Service the HTTP request */
if ( reqinfo.status == 200 ) {
if ( Return_Resource(conn, resource, &reqinfo) )
printf("Error on returning resource");
}
else
Return_Msg(conn, &reqinfo);
if ( resource > 0 )
if ( close(resource) < 0 )
printf("Error on HTTP request");
FreeReqInfo(&reqinfo);
return 0;
}
/* Returns a resource */
int Return_Resource(int conn, int resource, struct ReqInfo * reqinfo) {
char c;
int i;
while ( (i = read(resource, &c, 1)) ) {
if ( i < 0 )
printf("Error on reading from resource");
if ( write(conn, &c, 1) < 1 )
printf("Error on sending resource");
}
return 0;
}
/* Tries to open a resource. The calling function can use
the return value to check for success, and then examine
errno to determine the cause of failure if neceesary. */
int Check_Resource(struct ReqInfo * reqinfo) {
/* Resource name can contain urlencoded
data, so clean it up just in case. */
CleanURL(reqinfo->resource);
/* Concatenate resource name to server root, and try to open */
strcat(web_pages_path, reqinfo->resource);
return open(web_pages_path, O_RDONLY);
}
//Ali.B
//tells the http server to load the page with text to show a successfull message sending.
int Return_Msg(int conn, struct ReqInfo * reqinfo) {
char buffer[200];//Had to increase the size of the array , otherwise would get stack smashing detected
sprintf(buffer, "<HTML>\n<HEAD>\n<TITLE>Base Command Center | Message Sent</TITLE>\n"
"</HEAD>\n\n", reqinfo->status);
Writeline(conn, buffer, strlen(buffer));
sprintf(buffer, "<BODY>\n<H1>Message Sent Successfully</H1>\n", reqinfo->status);
Writeline(conn, buffer, strlen(buffer));
sprintf(buffer, "<P>The message has been sent successfully. You may click back now to return to home page.</P>\n"
"</BODY>\n</HTML>\n");
Writeline(conn, buffer, strlen(buffer));
return 0;
}
/* Parses a string and updates a request
information structure if necessary. */
int Parse_HTTP_Header(char * buffer, struct ReqInfo * reqinfo) {
static int first_header = 1;
char *temp;
char *endptr;
int len;
if ( first_header == 1 ) {
/* If first_header is 0, this is the first line of
the HTTP request, so this should be the request line. */
/* Get the request method, which is case-sensitive. This
version of the server only supports the GET and HEAD
request methods. */
if ( !strncmp(buffer, "GET ", 4) ) {
reqinfo->method = GET;
//---------------------------------------------------------------
//Author: Ali.B
//this is the part that manipulates the buffer.
//takes out the command part from the buffer and call bt_send function accordingly.
char command_buffer[80] = {0};
char *s,*t;
if(s = strchr(buffer, '='))
{
if(t = strchr(s, ' '))
strncpy(command_buffer, s+1, t-s);
}
//Checks to see it command_buffer is STOP and sends STOP message if so.
if( strcmp( command_buffer, "STOP " ) == 0 )
bt_send("STOP");
//Checks to see if the buffer contains START, ( to see if START was sent from HTML Page)
if (strstr(buffer, "START"))
//assembles the payload and sends it via bluetooth followed by the START message.
payload_assembler(buffer);
//----------------------------------------------------------
buffer += 4;
}
else if ( !strncmp(buffer, "HEAD ", 5) ) {
reqinfo->method = HEAD;
buffer += 5;
}
else {
reqinfo->method = UNSUPPORTED;
reqinfo->status = 501;
return -1;
}
/* Skip to start of resource */
while ( *buffer && isspace(*buffer) )
buffer++;
/* Calculate string length of resource... */
endptr = strchr(buffer, ' ');
if ( endptr == NULL )
len = strlen(buffer);
else
len = endptr - buffer;
if ( len == 0 ) {
reqinfo->status = 400;
return -1;
}
/* ...and store it in the request information structure. */
reqinfo->resource = calloc(len + 1, sizeof(char));
strncpy(reqinfo->resource, buffer, len);
/* Test to see if we have any HTTP version information.
If there isn't, this is a simple HTTP request, and we
should not try to read any more headers. For simplicity,
we don't bother checking the validity of the HTTP version
information supplied - we just assume that if it is
supplied, then it's a full request. */
if ( strstr(buffer, "HTTP/") )
reqinfo->type = FULL;
else
reqinfo->type = SIMPLE;
first_header = 0;
return 0;
}
/* If we get here, we have further headers aside from the
request line to parse, so this is a "full" HTTP request. */
/* HTTP field names are case-insensitive, so make an
upper-case copy of the field name to aid comparison.
We need to make a copy of the header up until the colon.
If there is no colon, we return a status code of 400
(bad request) and terminate the connection. Note that
HTTP/1.0 allows (but discourages) headers to span multiple
lines if the following lines start with a space or a
tab. For simplicity, we do not allow this here. */
endptr = strchr(buffer, ':');
if ( endptr == NULL ) {
reqinfo->status = 400;
return -1;
}
temp = calloc( (endptr - buffer) + 1, sizeof(char) );
strncpy(temp, buffer, (endptr - buffer));
StrUpper(temp);
/* Increment buffer so that it now points to the value.
If there is no value, just return. */
buffer = endptr + 1;
while ( *buffer && isspace(*buffer) )
++buffer;
if ( *buffer == '\0' )
return 0;
/* Now update the request information structure with the
appropriate field value. This version only supports the
"Referer:" and "User-Agent:" headers, ignoring all others. */
if ( !strcmp(temp, "USER-AGENT") ) {
reqinfo->useragent = malloc( strlen(buffer) + 1 );
strcpy(reqinfo->useragent, buffer);
}
else if ( !strcmp(temp, "REFERER") ) {
reqinfo->referer = malloc( strlen(buffer) + 1 );
strcpy(reqinfo->referer, buffer);
}
free(temp);
return 0;
}
/* Gets request headers. A CRLF terminates a HTTP header line,
but if one is never sent we would wait forever. Therefore,
we use select() to set a maximum length of time we will
wait for the next complete header. If we timeout before
this is received, we terminate the connection. */
int Get_Request(int conn, struct ReqInfo * reqinfo) {
char buffer[MAX_REQ_LINE] = {0};
int rval;
fd_set fds;
struct timeval tv;
/* Set timeout to 5 seconds */
tv.tv_sec = 5;
tv.tv_usec = 0;
/* Loop through request headers. If we have a simple request,
then we will loop only once. Otherwise, we will loop until
we receive a blank line which signifies the end of the headers,
or until select() times out, whichever is sooner. */
do {
/* Reset file descriptor set */
FD_ZERO(&fds);
FD_SET (conn, &fds);
/* Wait until the timeout to see if input is ready */
rval = select(conn + 1, &fds, NULL, NULL, &tv);
/* Take appropriate action based on return from select() */
if ( rval < 0 ) {
printf("Error calling select() in get_request()");
}
else if ( rval == 0 ) {
/* input not ready after timeout */
return -1;
}
else {
/* We have an input line waiting, so retrieve it */
Readline(conn, buffer, MAX_REQ_LINE - 1);
Trim(buffer);
if ( buffer[0] == '\0' )
break;
if ( Parse_HTTP_Header(buffer, reqinfo) )
break;
}
} while ( reqinfo->type != SIMPLE );
return 0;
}
/* Initialises a request information structure */
void InitReqInfo(struct ReqInfo * reqinfo) {
reqinfo->useragent = NULL;
reqinfo->referer = NULL;
reqinfo->resource = NULL;
reqinfo->method = UNSUPPORTED;
reqinfo->status = 200;
}
/* Frees memory allocated for a request information structure */
void FreeReqInfo(struct ReqInfo * reqinfo) {
if ( reqinfo->useragent )
free(reqinfo->useragent);
if ( reqinfo->referer )
free(reqinfo->referer);
if ( reqinfo->resource )
free(reqinfo->resource);
}
/* Outputs HTTP response headers */
int Output_HTTP_Headers(int conn, struct ReqInfo * reqinfo) {
char buffer[100];
sprintf(buffer, "HTTP/1.0 %d OK\r\n", reqinfo->status);
Writeline(conn, buffer, strlen(buffer));
Writeline(conn, "Server: BASEwebServer \r\n", 24);
Writeline(conn, "Content-Type: text/html\r\n", 25);
Writeline(conn, "\r\n", 2);
return 0;
}
/* Read a line from a socket */
ssize_t Readline(int sockd, void *vptr, size_t maxlen) {
ssize_t n, rc;
char c, *buffer;
buffer = vptr;
for ( n = 1; n < maxlen; n++ ) {
if ( (rc = read(sockd, &c, 1)) == 1 ) {
*buffer++ = c;
if ( c == '\n' )
break;
}
else if ( rc == 0 ) {
if ( n == 1 )
return 0;
else
break;
}
else {
if ( errno == EINTR )
continue;
printf("Error in Readline()");
}
}
*buffer = 0;
return n;
}
/* Write a line to a socket */
ssize_t Writeline(int sockd, const void *vptr, size_t n) {
size_t nleft;
ssize_t nwritten;
const char *buffer;
buffer = vptr;
nleft = n;
while ( nleft > 0 ) {
if ( (nwritten = write(sockd, buffer, nleft)) <= 0 ) {
if ( errno == EINTR )
nwritten = 0;
else
printf("Error in Writeline()");
}
nleft -= nwritten;
buffer += nwritten;
}
return n;
}
/* Removes trailing whitespace from a string */
int Trim(char * buffer) {
int n = strlen(buffer) - 1;
while ( !isalnum(buffer[n]) && n >= 0 )
buffer[n--] = '\0';
return 0;
}
/* Converts a string to upper-case */
int StrUpper(char * buffer) {
while ( *buffer ) {
*buffer = toupper(*buffer);
++buffer;
}
return 0;
}
/* Cleans up url-encoded string */
void CleanURL(char * buffer) {
char asciinum[3] = {0};
int i = 0, c;
while ( buffer[i] ) {
if ( buffer[i] == '+' )
buffer[i] = ' ';
else if ( buffer[i] == '%' ) {
asciinum[0] = buffer[i+1];
asciinum[1] = buffer[i+2];
buffer[i] = strtol(asciinum, NULL, 16);
c = i+1;
do {
buffer[c] = buffer[c+2];
} while ( buffer[2+(c++)] );
}
++i;
}
}