forked from Skycrab/Linux-C-Web-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
755 lines (640 loc) · 16.7 KB
/
main.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
#include "wrap.h"
#include "parse.h"
#define PID_FILE "pid.file"
static void doit(int fd);
static void writePid(int option);
static void get_requesthdrs(rio_t *rp);
static void post_requesthdrs(rio_t *rp,int *length);
static int parse_uri(char *uri, char *filename, char *cgiargs);
static void serve_static(int fd, char *filename, int filesize);
static void serve_dir(int fd,char *filename);
static void get_filetype(const char *filename, char *filetype);
static void get_dynamic(int fd, char *filename, char *cgiargs);
static void post_dynamic(int fd, char *filename, int contentLength,rio_t *rp);
static void clienterror(int fd, char *cause, char *errnum,
char *shortmsg, char *longmsg);
static void sigChldHandler(int signo);
/* $begin ssl */
#ifdef HTTPS
static void ssl_init(void);
static void https_getlength(char* buf,int* length);
#endif
/* $end ssl */
static int isShowdir=1;
char* cwd;
#ifdef HTTPS
static SSL_CTX* ssl_ctx;
static SSL* ssl;
static char* certfile;
static int ishttps=0;
static char httpspostdata[MAXLINE];
#endif
int main(int argc, char **argv)
{
int listenfd,connfd, port,clientlen;
pid_t pid;
struct sockaddr_in clientaddr;
char isdaemon=0,*portp=NULL,*logp=NULL,tmpcwd[MAXLINE];
#ifdef HTTPS
int sslport;
char dossl=0,*sslportp=NULL;
#endif
openlog(argv[0],LOG_NDELAY|LOG_PID,LOG_DAEMON);
cwd=(char*)get_current_dir_name();
strcpy(tmpcwd,cwd);
strcat(tmpcwd,"/");
/* parse argv */
#ifdef HTTPS
parse_option(argc,argv,&isdaemon,&portp,&logp,&sslportp,&dossl);
sslportp==NULL ?(sslport=atoi(Getconfig("https"))) : (sslport=atoi(sslportp));
if(dossl==1||strcmp(Getconfig("dossl"),"yes")==0)
dossl=1;
#else
parse_option(argc,argv,&isdaemon,&portp,&logp);
#endif
portp==NULL ?(port=atoi(Getconfig("http"))) : (port=atoi(portp));
Signal(SIGCHLD,sigChldHandler);
/* init log */
if(logp==NULL)
logp=Getconfig("log");
initlog(strcat(tmpcwd,logp));
/* whethe show dir */
if(strcmp(Getconfig("dir"),"no")==0)
isShowdir=0;
clientlen = sizeof(clientaddr);
if(isdaemon==1||strcmp(Getconfig("daemon"),"yes")==0)
Daemon(1,1);
writePid(1);
/* $https start */
#ifdef HTTPS
if(dossl)
{
if((pid=Fork())==0)
{
listenfd= Open_listenfd(sslport);
ssl_init();
while(1)
{
connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
if(access_ornot(inet_ntoa(clientaddr.sin_addr))==0)
{
clienterror(connfd,"maybe this web server not open to you!" , "403", "Forbidden", "Tiny couldn't read the file");
continue;
}
if((pid=Fork())>0)
{
Close(connfd);
continue;
}
else if(pid==0)
{
ishttps=1;
doit(connfd);
exit(1);
}
}
}
}
#endif
/* $end https */
listenfd = Open_listenfd(port);
while (1)
{
connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
if(access_ornot(inet_ntoa(clientaddr.sin_addr))==0)
{
clienterror(connfd,"maybe this web server not open to you!" , "403", "Forbidden", "Tiny couldn't read the file");
continue;
}
if((pid=Fork())>0)
{
Close(connfd);
continue;
}
else if(pid==0)
{
doit(connfd);
exit(1);
}
}
}
/* $end main */
/*$sigChldHandler to protect zimble process */
static void sigChldHandler(int signo)
{
Waitpid(-1,NULL,WNOHANG);
return;
}
/*$end sigChldHandler */
/* $begin ssl init */
#ifdef HTTPS
static void ssl_init(void)
{
static char crypto[]="RC4-MD5";
certfile=Getconfig("ca");
SSL_load_error_strings();
SSLeay_add_ssl_algorithms();
ssl_ctx = SSL_CTX_new( SSLv23_server_method() );
if ( certfile[0] != '\0' )
if ( SSL_CTX_use_certificate_file( ssl_ctx, certfile, SSL_FILETYPE_PEM ) == 0 || SSL_CTX_use_PrivateKey_file( ssl_ctx, certfile, SSL_FILETYPE_PEM ) == 0 || SSL_CTX_check_private_key( ssl_ctx ) == 0 )
{
ERR_print_errors_fp( stderr );
exit( 1 );
}
if ( crypto != (char*) 0 )
{
if ( SSL_CTX_set_cipher_list( ssl_ctx, crypto ) == 0 )
{
ERR_print_errors_fp( stderr );
exit( 1 );
}
}
}
#endif
/* $end ssl init */
/*
* doit - handle one HTTP request/response transaction
*/
/* $begin doit */
static void doit(int fd)
{
int is_static,contentLength=0,isGet=1;
struct stat sbuf;
char buf[MAXLINE], method[MAXLINE], uri[MAXLINE], version[MAXLINE];
char filename[MAXLINE], cgiargs[MAXLINE],httpspostdata[MAXLINE];
rio_t rio;
memset(buf,0,MAXLINE);
#ifdef HTTPS
if(ishttps)
{
ssl=SSL_new(ssl_ctx);
SSL_set_fd(ssl,fd);
if(SSL_accept(ssl)==0)
{
ERR_print_errors_fp(stderr);
exit(1);
}
SSL_read(ssl,buf,sizeof(buf));
}
else
#endif
{
/* Read request line and headers */
Rio_readinitb(&rio, fd);
Rio_readlineb(&rio, buf, MAXLINE);
}
sscanf(buf, "%s %s %s", method, uri, version);
if (strcasecmp(method, "GET")!=0&&strcasecmp(method,"POST")!=0)
{
clienterror(fd, method, "501", "Not Implemented",
"Tiny does not implement this method");
return;
}
/* Parse URI from GET request */
is_static = parse_uri(uri, filename, cgiargs);
if (lstat(filename, &sbuf) < 0)
{
clienterror(fd, filename, "404", "Not found",
"Tiny couldn't find this file");
return;
}
if(S_ISDIR(sbuf.st_mode)&&isShowdir)
serve_dir(fd,filename);
if (strcasecmp(method, "POST")==0)
isGet=0;
if (is_static)
{ /* Serve static content */
#ifdef HTTPS
if(!ishttps)
#endif
get_requesthdrs(&rio); /* because https already read the headers -> SSL_read() */
if (!(S_ISREG(sbuf.st_mode)) || !(S_IRUSR & sbuf.st_mode))
{
clienterror(fd, filename, "403", "Forbidden",
"Tiny couldn't read the file");
return;
}
serve_static(fd, filename, sbuf.st_size);
}
else
{ /* Serve dynamic content */
if (!(S_ISREG(sbuf.st_mode)) || !(S_IXUSR & sbuf.st_mode))
{
clienterror(fd, filename, "403", "Forbidden",
"Tiny couldn't run the CGI program");
return;
}
if(isGet)
{
#ifdef HTTPS
if(!ishttps)
#endif
get_requesthdrs(&rio); /* because https already read headers by SSL_read() */
get_dynamic(fd, filename, cgiargs);
}
else
{
#ifdef HTTPS
if(ishttps)
https_getlength(buf,&contentLength);
else
#endif
post_requesthdrs(&rio,&contentLength);
post_dynamic(fd, filename,contentLength,&rio);
}
}
}
/* $end doit */
/* $begin https_getlength */
#ifdef HTTPS
static void https_getlength(char* buf,int* length)
{
char *p,line[MAXLINE];
char *tmpbuf=buf;
int lengthfind=0;
while(*tmpbuf!='\0')
{
p=line;
while(*tmpbuf!='\n' && *tmpbuf!='\0')
*p++=*tmpbuf++;
*p='\0';
if(!lengthfind)
{
if(strncasecmp(line,"Content-Length:",15)==0)
{
p=&line[15];
p+=strspn(p," \t");
*length=atoi(p);
lengthfind=1;
}
}
if(strncasecmp(line,"\r",1)==0)
{
strcpy(httpspostdata,++tmpbuf);
break;
}
++tmpbuf;
}
return;
}
#endif
/* $end https_getlength */
/*
* read_requesthdrs - read and parse HTTP request headers
*/
/* $begin get_requesthdrs */
static void get_requesthdrs(rio_t *rp)
{
char buf[MAXLINE];
Rio_readlineb(rp, buf, MAXLINE);
writetime(); /* write access time in log file */
//printf("%s", buf);
while(strcmp(buf, "\r\n"))
{
Rio_readlineb(rp, buf, MAXLINE);
writelog(buf);
//printf("%s", buf);
}
return;
}
/* $end get_requesthdrs */
/* $begin post_requesthdrs */
static void post_requesthdrs(rio_t *rp,int *length)
{
char buf[MAXLINE];
char *p;
Rio_readlineb(rp, buf, MAXLINE);
writetime(); /* write access time in log file */
while(strcmp(buf, "\r\n"))
{
Rio_readlineb(rp, buf, MAXLINE);
if(strncasecmp(buf,"Content-Length:",15)==0)
{
p=&buf[15];
p+=strspn(p," \t");
*length=atol(p);
}
writelog(buf);
//printf("%s", buf);
}
return;
}
/* $end post_requesthdrs */
/* $begin post_dynamic */
static void serve_dir(int fd,char *filename)
{
DIR *dp;
struct dirent *dirp;
struct stat sbuf;
struct passwd *filepasswd;
int num=1;
char files[MAXLINE],buf[MAXLINE],name[MAXLINE],img[MAXLINE],modifyTime[MAXLINE],dir[MAXLINE];
char *p;
/*
* Start get the dir
* for example: /home/yihaibo/kerner/web/doc/dir -> dir[]="dir/";
*/
p=strrchr(filename,'/');
++p;
strcpy(dir,p);
strcat(dir,"/");
/* End get the dir */
if((dp=opendir(filename))==NULL)
syslog(LOG_ERR,"cannot open dir:%s",filename);
sprintf(files, "<html><title>Dir Browser</title>");
sprintf(files,"%s<style type=""text/css""> a:link{text-decoration:none;} </style>",files);
sprintf(files, "%s<body bgcolor=""ffffff"" font-family=Arial color=#fff font-size=14px>\r\n", files);
while((dirp=readdir(dp))!=NULL)
{
if(strcmp(dirp->d_name,".")==0||strcmp(dirp->d_name,"..")==0)
continue;
sprintf(name,"%s/%s",filename,dirp->d_name);
Stat(name,&sbuf);
filepasswd=getpwuid(sbuf.st_uid);
if(S_ISDIR(sbuf.st_mode))
{
sprintf(img,"<img src=""dir.png"" width=""24px"" height=""24px"">");
}
else if(S_ISFIFO(sbuf.st_mode))
{
sprintf(img,"<img src=""fifo.png"" width=""24px"" height=""24px"">");
}
else if(S_ISLNK(sbuf.st_mode))
{
sprintf(img,"<img src=""link.png"" width=""24px"" height=""24px"">");
}
else if(S_ISSOCK(sbuf.st_mode))
{
sprintf(img,"<img src=""sock.png"" width=""24px"" height=""24px"">");
}
else
sprintf(img,"<img src=""file.png"" width=""24px"" height=""24px"">");
sprintf(files,"%s<p><pre>%-2d %s ""<a href=%s%s"">%-15s</a>%-10s%10d %24s</pre></p>\r\n",files,num++,img,dir,dirp->d_name,dirp->d_name,filepasswd->pw_name,(int)sbuf.st_size,timeModify(sbuf.st_mtime,modifyTime));
}
closedir(dp);
sprintf(files,"%s</body></html>",files);
/* Send response headers to client */
sprintf(buf, "HTTP/1.0 200 OK\r\n");
sprintf(buf, "%sServer: Tiny Web Server\r\n", buf);
sprintf(buf, "%sContent-length: %d\r\n", buf, strlen(files));
sprintf(buf, "%sContent-type: %s\r\n\r\n", buf, "text/html");
#ifdef HTTPS
if(ishttps)
{
SSL_write(ssl,buf,strlen(buf));
SSL_write(ssl,files,strlen(files));
}
else
#endif
{
Rio_writen(fd, buf, strlen(buf));
Rio_writen(fd, files, strlen(files));
}
exit(0);
}
/* $end serve_dir */
/* $begin post_dynamic */
static void post_dynamic(int fd, char *filename, int contentLength,rio_t *rp)
{
char buf[MAXLINE],length[32], *emptylist[] = { NULL },data[MAXLINE];
int p[2];
#ifdef HTTPS
int httpsp[2];
#endif
sprintf(length,"%d",contentLength);
memset(data,0,MAXLINE);
Pipe(p);
/* The post data is sended by client,we need to redirct the data to cgi stdin.
* so, child read contentLength bytes data from fp,and write to p[1];
* parent should redirct p[0] to stdin. As a result, the cgi script can
* read the post data from the stdin.
*/
/* https already read all data ,include post data by SSL_read() */
if (Fork() == 0)
{ /* child */
Close(p[0]);
#ifdef HTTPS
if(ishttps)
{
Write(p[1],httpspostdata,contentLength);
}
else
#endif
{
Rio_readnb(rp,data,contentLength);
Rio_writen(p[1],data,contentLength);
}
exit(0) ;
}
/* Send response headers to client */
sprintf(buf, "HTTP/1.0 200 OK\r\n");
sprintf(buf, "%sServer: Tiny Web Server\r\n",buf);
#ifdef HTTPS
if(ishttps)
SSL_write(ssl,buf,strlen(buf));
else
#endif
Rio_writen(fd, buf, strlen(buf));
//Wait(NULL);
Dup2(p[0],STDIN_FILENO); /* Redirct p[0] to stdin */
Close(p[0]);
Close(p[1]);
setenv("CONTENT-LENGTH",length , 1);
#ifdef HTTPS
if(ishttps) /* if ishttps,we couldnot redirct stdout to client,we must use SSL_write */
{
Pipe(httpsp);
if(Fork()==0)
{
Dup2(httpsp[1],STDOUT_FILENO); /* Redirct stdout to https[1] */
Execve(filename, emptylist, environ);
}
//Wait(NULL);
Read(httpsp[0],data,MAXLINE);
SSL_write(ssl,data,strlen(data));
}
else
#endif
{
Dup2(fd,STDOUT_FILENO); /* Redirct stdout to client */
Execve(filename, emptylist, environ);
}
}
/* $end post_dynamic */
/*
* parse_uri - parse URI into filename and CGI args
* return 0 if dynamic content, 1 if static
*/
/* $begin parse_uri */
static int parse_uri(char *uri, char *filename, char *cgiargs)
{
char *ptr;
char tmpcwd[MAXLINE];
strcpy(tmpcwd,cwd);
strcat(tmpcwd,"/");
if (!strstr(uri, "cgi-bin"))
{ /* Static content */
strcpy(cgiargs, "");
strcpy(filename, strcat(tmpcwd,Getconfig("root")));
strcat(filename, uri);
if (uri[strlen(uri)-1] == '/')
strcat(filename, "home.html");
return 1;
}
else
{ /* Dynamic content */
ptr = index(uri, '?');
if (ptr)
{
strcpy(cgiargs, ptr+1);
*ptr = '\0';
}
else
strcpy(cgiargs, "");
strcpy(filename, cwd);
strcat(filename, uri);
return 0;
}
}
/* $end parse_uri */
/*
* serve_static - copy a file back to the client
*/
/* $begin serve_static */
static void serve_static(int fd, char *filename, int filesize)
{
int srcfd;
char *srcp, filetype[MAXLINE], buf[MAXBUF];
/* Send response headers to client */
get_filetype(filename, filetype);
sprintf(buf, "HTTP/1.0 200 OK\r\n");
sprintf(buf, "%sServer: Tiny Web Server\r\n", buf);
sprintf(buf, "%sContent-length: %d\r\n", buf, filesize);
sprintf(buf, "%sContent-type: %s\r\n\r\n", buf, filetype);
/* Send response body to client */
srcfd = Open(filename, O_RDONLY, 0);
srcp = Mmap(0, filesize, PROT_READ, MAP_PRIVATE, srcfd, 0);
Close(srcfd);
#ifdef HTTPS
if(ishttps)
{
SSL_write(ssl, buf, strlen(buf));
SSL_write(ssl, srcp, filesize);
}
else
#endif
{
Rio_writen(fd, buf, strlen(buf));
Rio_writen(fd, srcp, filesize);
}
Munmap(srcp, filesize);
}
/*
* get_filetype - derive file type from file name
*/
static void get_filetype(const char *filename, char *filetype)
{
if (strstr(filename, ".html"))
strcpy(filetype, "text/html");
else if (strstr(filename, ".gif"))
strcpy(filetype, "image/gif");
else if (strstr(filename, ".jpg"))
strcpy(filetype, "image/jpeg");
else if (strstr(filename, ".png"))
strcpy(filetype, "image/png");
else
strcpy(filetype, "text/plain");
}
/* $end serve_static */
/*
* serve_dynamic - run a CGI program on behalf of the client
*/
/* $begin get_dynamic */
void get_dynamic(int fd, char *filename, char *cgiargs)
{
char buf[MAXLINE], *emptylist[] = { NULL },httpsbuf[MAXLINE];
int p[2];
/* Return first part of HTTP response */
sprintf(buf, "HTTP/1.0 200 OK\r\n");
sprintf(buf, "%sServer: Tiny Web Server\r\n",buf);
#ifdef HTTPS
if(ishttps)
SSL_write(ssl,buf,strlen(buf));
else
#endif
Rio_writen(fd, buf, strlen(buf));
#ifdef HTTPS
if(ishttps)
{
Pipe(p);
if (Fork() == 0)
{ /* child */
Close(p[0]);
setenv("QUERY_STRING", cgiargs, 1);
Dup2(p[1], STDOUT_FILENO); /* Redirect stdout to p[1] */
Execve(filename, emptylist, environ); /* Run CGI program */
}
Close(p[1]);
Read(p[0],httpsbuf,MAXLINE); /* parent read from p[0] */
SSL_write(ssl,httpsbuf,strlen(httpsbuf));
}
else
#endif
{
if (Fork() == 0)
{ /* child */
/* Real server would set all CGI vars here */
setenv("QUERY_STRING", cgiargs, 1);
Dup2(fd, STDOUT_FILENO); /* Redirect stdout to client */
Execve(filename, emptylist, environ); /* Run CGI program */
}
}
//Wait(NULL); /* Parent waits for and reaps child */
}
/* $end get_dynamic */
/*
* clienterror - returns an error message to the client
*/
/* $begin clienterror */
static void clienterror(int fd, char *cause, char *errnum,
char *shortmsg, char *longmsg)
{
char buf[MAXLINE], body[MAXBUF];
/* Build the HTTP response body */
sprintf(body, "<html><title>Tiny Error</title>");
sprintf(body, "%s<body bgcolor=""ffffff"">\r\n", body);
sprintf(body, "%s%s: %s\r\n", body, errnum, shortmsg);
sprintf(body, "%s<p>%s: %s\r\n", body, longmsg, cause);
sprintf(body, "%s<hr><em>The Tiny Web server</em>\r\n", body);
/* Print the HTTP response */
sprintf(buf, "HTTP/1.0 %s %s\r\n", errnum, shortmsg);
sprintf(buf, "%sContent-type: text/html\r\n",buf);
sprintf(buf, "%sContent-length: %d\r\n\r\n",buf,(int)strlen(body));
#ifdef HTTPS
if(ishttps)
{
SSL_write(ssl,buf,strlen(buf));
SSL_write(ssl,body,strlen(body));
}
else
#endif
{
Rio_writen(fd, buf, strlen(buf));
Rio_writen(fd, body, strlen(body));
}
}
/* $end clienterror */
/* $begin writePid */
/* if the process is running, the interger in the pid file is the pid, else is -1 */
static void writePid(int option)
{
int pid;
FILE *fp=Fopen(PID_FILE,"w+");
if(option)
pid=(int)getpid();
else
pid=-1;
fprintf(fp,"%d",pid);
Fclose(fp);
}
/* $end writePid */