tinywebd

view src/main.c @ 17:2874f61a43b1

implementing the directory index generation
author John Tsiombikas <nuclear@member.fsf.org>
date Tue, 21 Apr 2015 04:33:02 +0300
parents 0244b08cc9d3
children
line source
1 /* tinyweb - tiny web server library and daemon
2 * Author: John Tsiombikas <nuclear@member.fsf.org>
3 *
4 * This program is placed in the public domain. Feel free to use it any
5 * way you like. Mentions and retaining this attribution header will be
6 * appreciated, but not required.
7 */
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <errno.h>
12 #include <signal.h>
13 #include "tinyweb.h"
15 int parse_args(int argc, char **argv);
16 void sighandler(int s);
19 int main(int argc, char **argv)
20 {
21 int *sockets, num_sockets, sockets_arr_size = 0;
23 if(parse_args(argc, argv) == -1) {
24 return 1;
25 }
27 signal(SIGINT, sighandler);
28 signal(SIGTERM, sighandler);
29 signal(SIGQUIT, sighandler);
31 if(tw_start() == -1) {
32 return 1;
33 }
35 for(;;) {
36 int i;
37 fd_set rdset;
39 num_sockets = tw_get_sockets(0);
40 if(num_sockets > sockets_arr_size) {
41 int newsz = sockets_arr_size ? sockets_arr_size * 2 : 16;
42 int *newarr = realloc(sockets, newsz * sizeof *sockets);
43 if(!newarr) {
44 fprintf(stderr, "failed to allocate sockets array\n");
45 tw_stop();
46 return 1;
47 }
48 sockets = newarr;
49 sockets_arr_size = newsz;
50 }
51 tw_get_sockets(sockets);
53 FD_ZERO(&rdset);
54 for(i=0; i<num_sockets; i++) {
55 FD_SET(sockets[i], &rdset);
56 }
58 while(select(tw_get_maxfd() + 1, &rdset, 0, 0, 0) == -1 && errno == EINTR);
60 for(i=0; i<num_sockets; i++) {
61 if(FD_ISSET(sockets[i], &rdset)) {
62 tw_handle_socket(sockets[i]);
63 }
64 }
65 }
67 return 0; /* unreachable */
68 }
70 void sighandler(int s)
71 {
72 if(s == SIGINT || s == SIGTERM || s == SIGQUIT) {
73 tw_stop();
74 printf("bye!\n");
75 exit(0);
76 }
77 }
80 static void print_help(const char *argv0)
81 {
82 printf("Usage: %s [options]\n", argv0);
83 printf("Options:\n");
84 printf(" -p <port> set the TCP/IP port number to use\n");
85 printf(" -h print usage help and exit\n");
86 }
88 int parse_args(int argc, char **argv)
89 {
90 int i;
92 for(i=1; i<argc; i++) {
93 if(argv[i][0] == '-' && argv[i][2] == 0) {
94 switch(argv[i][1]) {
95 case 'p':
96 {
97 int port = atoi(argv[++i]);
98 if(!port) {
99 fprintf(stderr, "-p must be followed by a valid port number\n");
100 return -1;
101 }
102 tw_set_port(port);
103 }
104 break;
106 case 'c':
107 if(tw_set_root(argv[++i]) == -1) {
108 return -1;
109 }
110 break;
112 case 'h':
113 print_help(argv[0]);
114 exit(0);
116 default:
117 fprintf(stderr, "unrecognized option: %s\n", argv[i]);
118 return -1;
119 }
120 } else {
121 fprintf(stderr, "unexpected argument: %s\n", argv[i]);
122 return -1;
123 }
124 }
125 return 0;
126 }