Nuova versione con unificata la stampa degli errori e dei codici HTTP
[gapil.git] / sources / wwwd.c
1 /* wwwd.c
2  * 
3  * Copyright (C) 2005 Simone Piccardi
4  * 
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or (at
8  * your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 /****************************************************************
20  *
21  * Program wwwd 
22  * Elementary WWW server (port 80)
23  *
24  * Author: Simone Piccardi
25  * Mar. 2005
26  *
27  * Usage: wwwd -h give all info
28  *
29  * $Id$ 
30  *
31  ****************************************************************/
32 /* 
33  * Include needed headers
34  */
35 #define _GNU_SOURCE
36 #include <string.h>      /* error strings */
37 #include <sys/types.h>   /* predefined types */
38 #include <unistd.h>      /* include unix standard library */
39 #include <arpa/inet.h>   /* IP addresses conversion utiliites */
40 #include <sys/socket.h>  /* socket library */
41 #include <stdio.h>       /* include standard I/O library */
42 #include <time.h>
43 #include <syslog.h>      /* syslog system functions */
44 #include <signal.h>      /* signal functions */
45 #include <errno.h>       /* error code */
46 #include <stdlib.h>
47
48 #include "Gapil.h"
49
50 #define BACKLOG 10
51 #define MAXLINE 256
52 int demonize  = 1;  /* daemon use option: default is daemon */
53 int debugging = 0;  /* debug info printing option: default is no debug */
54
55 /* Subroutines declaration */
56 struct code_page {
57     char * code; 
58     char * name;
59     char * body;
60 };
61
62 void usage(void);
63 void ServPage(int sockfd);
64 void PrintErr(char * error);
65 void print_headers(FILE *file, struct code_page code);
66 void print_error(FILE *file, struct code_page page, char * string);
67
68 /* Program beginning */
69 int main(int argc, char *argv[])
70 {
71 /* 
72  * Variables definition  
73  */
74     int list_fd, conn_fd;
75     int compat = 0;
76     int reroot = 0;
77     char * rootdir;
78     pid_t pid;
79     struct sockaddr_in cli_add;
80     socklen_t len;
81     char debug[MAXLINE], ipaddr[20];
82     /*
83      * Input section: decode parameters passed in the calling 
84      * Use getopt function
85      */
86     int i;
87     opterr = 0;  /* don't want writing to stderr */
88     while ( (i = getopt(argc, argv, "hdicr:")) != -1) {
89         switch (i) {
90         /* 
91          * Handling options 
92          */ 
93         case 'h':  
94             printf("Wrong -h option use\n");
95             usage();
96             return(0);
97             break;
98         case 'i':
99             demonize = 0;
100             break;
101         case 'c':
102             compat = 1;
103             break;
104         case 'd':
105             debugging = 1;
106             break;
107         case 'r':
108             reroot = 1;
109             rootdir = optarg;
110             break;
111         case '?':   /* unrecognized options */
112             printf("Unrecognized options -%c\n",optopt);
113             usage();
114         default:    /* should not reached */
115             usage();
116         }
117     }
118     /* ***********************************************************
119      * 
120      *           Options processing completed
121      *
122      *                Main code beginning
123      * 
124      * ***********************************************************/
125     /* Main code begin here */
126     if (compat) {                             /* install signal handler */
127         Signal(SIGCHLD, HandSigCHLD);         /* non restarting handler */
128     } else {
129         SignalRestart(SIGCHLD, HandSigCHLD);  /* restarting handler */
130     }
131     /* create and bind socket */
132     if ( (list_fd = sockbind2(argv[optind], "www", 6, SOCK_STREAM)) < 0) {
133         return 1;
134     }   
135     /* chroot if requested */
136     if (reroot) {
137         if (chdir(rootdir)) {
138             perror("Cannot find directory to chroot");
139             exit(1);
140         }
141         if (chroot(rootdir)) {
142             perror("Cannot chroot");
143             exit(1);
144         }
145     }
146     /* release privileges and go daemon */
147     if (setgid(65534) !=0) { /* first give away group privileges */
148         perror("cannot give away group privileges");
149         exit(1);
150     }
151     if (setuid(65534) !=0) { /* and only after user ... */
152         perror("cannot give away user privileges");
153         exit(1);
154     }
155     if (demonize) {          /* go daemon */
156         openlog(argv[0], 0, LOG_DAEMON); /* open logging */
157         if (daemon(0, 0) != 0) {
158             perror("cannot start as daemon");
159             exit(1);
160         }
161     }
162     /* main body */
163     if (listen(list_fd, BACKLOG) < 0 ) {
164         PrintErr("listen error");
165         exit(1);
166     }
167     /* handle echo to client */
168     while (1) {
169         /* accept connection */
170         len = sizeof(cli_add);
171         while (((conn_fd = accept(list_fd, (struct sockaddr *)&cli_add, &len)) 
172                 < 0) && (errno == EINTR)); 
173         if (conn_fd < 0) {
174             PrintErr("accept error");
175             exit(1);
176         }
177         if (debugging) {
178             inet_ntop(AF_INET, &cli_add.sin_addr, ipaddr, sizeof(ipaddr));
179             snprintf(debug, MAXLINE, "Accepted connection form %s\n", ipaddr);
180             if (demonize) {
181                 syslog(LOG_DEBUG, debug);
182             } else {
183                 printf("%s", debug);
184             }
185         }
186         /* fork to handle connection */
187         if ( (pid = fork()) < 0 ){
188             PrintErr("fork error");
189             exit(1);
190         }
191         if (pid == 0) {      /* child */
192             close(list_fd);          /* close listening socket */   
193             ServPage(conn_fd);       /* handle echo */
194             if (debugging) {
195                 snprintf(debug, MAXLINE, "Closed connection %s\n", ipaddr);
196                 if (demonize) {
197                     syslog(LOG_DEBUG, debug);
198                 } else {
199                     printf("%s", debug);
200                 }
201             }
202             exit(0);
203         } else {             /* parent */
204             close(conn_fd);          /* close connected socket */
205         }
206     }
207     /* normal exit, never reached */
208     exit(0);
209 }
210 /*
211  * routine to print usage info and exit
212  */
213 void usage(void) 
214 {
215     printf("Elementary echo server\n");
216     printf("Usage:\n");
217     printf("  echod [-h] \n");
218     printf("  -h           print this help\n");
219     printf("  -d           write debug info\n");
220     printf("  -i           use interactively\n");
221     printf("  -c           disable BSD semantics\n");
222     printf("  -r /path     chroot on /path\n");
223     exit(1);
224 }
225 /*
226  * routine to handle echo for connection
227  */
228 void ServPage(int sockfd) 
229 {
230     char buffer[MAXLINE];
231     char outbuf[1024];
232     FILE *sock, *file;
233     char *line, *copy, *method, *ptr, *filename, *version;
234     char *methods[] = { "GET", "HEAD", NULL };
235     struct code_page codes[] = {
236         { "200", "OK", "%s"},
237         { "400", "Bad Request", 
238           "Your browser sent a request that this server could not understand."
239           "<P>The request line<P>%s<P> is invalid following the protocol<P>"}, 
240         { "404", "Not Found", 
241           "The requested URL %s was not found on this server.<P>"},
242         { "500", "Internal Server Error", 
243           "We got an error processing your request.<P>Error is: %s<P>"},
244         { "405", "Method Not Allowed", "Method %s not allowed.<P>"},
245         { "403", "Forbidden", "You cannot access %s.<P>"}
246     };
247     int nleft;
248     int i;
249
250     sock = fdopen(sockfd, "w+");
251     /* main loop, reading 0 char means client close connection */
252     line = fgets(buffer, MAXLINE, sock);
253     if (line == NULL) {
254         PrintErr("Errore in lettura");
255         return;
256     }
257     /* parsing first line, getting method and filename */
258     copy = strndupa(line, MAXLINE);
259     if ((method = strtok_r(copy, " ", &ptr)) == NULL) {
260         print_headers(sock, codes[1]);
261         print_error(sock, codes[1], line);
262         return;
263     }
264     if ((filename = strtok_r(NULL, " ", &ptr)) == NULL) {
265         print_headers(sock, codes[1]);
266         print_error(sock, codes[1], line);
267         return;
268     }
269     if ((version = strtok_r(NULL, " ", &ptr)) == NULL) {
270         print_headers(sock, codes[1]);
271         print_error(sock, codes[1], line);
272         return;
273     }
274     i = 0;
275     while ( (ptr = methods[i]) != NULL) {
276         if ( (strncmp(ptr, method, strlen(ptr)) == 0)) {
277             break;
278         }
279         i++;
280     }
281     if (i>=2) {
282         print_headers(sock, codes[4]);
283         print_error(sock, codes[4], method);
284         return;
285     }
286
287     while (strcmp(line,"\r\n")) {
288         line = fgets(buffer, MAXLINE, sock);
289     }
290
291     if ( (file = fopen(filename, "r")) == NULL) {
292         if ( (errno == EACCES)||(errno == EPERM) ) {
293             print_headers(sock, codes[5]);
294             print_error(sock, codes[5], filename);
295         } else {
296             print_headers(sock, codes[2]);
297             print_error(sock, codes[2], filename);
298         }
299         return;
300     }
301     print_headers(sock, codes[0]);
302     while (!feof(file)) {
303         if ( (nleft = full_fread(file, outbuf, 1024)) != 0) {
304             if (ferror(file)) {
305                 strncpy(buffer, strerror(errno), MAXLINE);
306                 print_headers(sock, codes[3]);
307                 print_error(sock, codes[3], buffer);
308                 return;
309             }
310         }
311         if (full_fwrite(sock, outbuf, 1024-nleft) != 0) {
312             if (ferror(file)) {
313                 strncpy(buffer, strerror(errno), MAXLINE);
314                 print_headers(sock, codes[3]);
315                 print_error(sock, codes[3], buffer);
316                 return;
317             }   
318         }
319     }
320     fclose(file);
321     fclose(sock);
322     return;
323 }
324 /*
325  * routine to print error on stout or syslog
326  */
327 void PrintErr(char * error) 
328 {
329     if (demonize) {                       /* daemon mode */
330         syslog(LOG_ERR, "%s: %m", error); /* log string and error message */
331     } else {
332         perror(error);
333     }
334     return;
335 }
336
337 void print_headers(FILE *file, struct code_page code)
338 {
339     time_t tempo;
340
341     fprintf(file, "HTTP/1.0 %s %s \n", code.code, code.name);
342     time(&tempo);
343     fprintf(file, "Date: %s", ctime(&tempo));
344     fprintf(file, "Server: WWWd test server\n");
345     fprintf(file, "Connection: close\n");
346     fprintf(file, "Content-Type: text/html; charset=iso-8859-1\n");
347     fprintf(file, "\n");
348     return;
349 }
350
351 void print_error(FILE *file, struct code_page page, char * string)
352 {
353     fprintf(file, "<HTML><HEAD><TITLE>%s %s</TITLE></HEAD>\n",
354             page.code, page.name);
355     fprintf(file, "<BODY><H1>%s</H1>\n", page.name);
356     fprintf(file, page.body, string);
357     fprintf(file, "<HR><ADDRESS>WWWd by S. Piccardi</ADDRESS></BODY></HTML>");
358     return;
359 }
360