2 * Simple_HTTPd v1.1 - a very small, barebones HTTP server
4 * Copyright (c) 1998-1999 Marc Nicholas <marc@netstor.com>
7 * Major rewrite by William Lloyd <wlloyd@slap.net>
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include <sys/types.h>
36 #include <sys/socket.h>
38 #include <netinet/in.h>
39 #include <arpa/inet.h>
53 int http_sock, con_sock;
55 const char *fetch_mode = NULL;
59 void init_servconnection(void);
61 void http_output(const char *html);
62 void http_request(void);
63 void log_line(char *req);
64 void wait_connection(void);
67 struct sockaddr_in source;
70 static char httpd_server_ident[] = "Server: FreeBSD/PicoBSD simple_httpd 1.1\r";
72 static char http_200[] = "HTTP/1.0 200 OK\r";
74 const char *default_mime_type = "application/octet-stream";
76 const char *mime_type[][2] = {
77 { "txt", "text/plain" },
78 { "htm", "text/html" },
79 { "html", "text/html" },
80 { "gif", "image/gif" },
81 { "jpg", "image/jpeg" },
82 { "mp3", "audio/mpeg" }
85 const int mime_type_max = sizeof(mime_type) / sizeof(mime_type[0]) - 1;
87 /* Two parts, HTTP Header and then HTML */
88 static const char *http_404[2] =
89 {"HTTP/1.0 404 Not found\r\n",
90 "<HTML><HEAD><TITLE>Error</TITLE></HEAD><BODY><H1>Error 404</H1>\
91 Not found - file doesn't exist or you do not have permission.\n</BODY></HTML>\r\n"
94 static const char *http_405[2] =
95 {"HTTP/1.0 405 Method Not allowed\r\nAllow: GET,HEAD\r\n",
96 "<HTML><HEAD><TITLE>Error</TITLE></HEAD><BODY><H1>Error 405</H1>\
97 This server only supports GET and HEAD requests.\n</BODY></HTML>\r\n"
101 * Only called on initial invocation
104 init_servconnection(void)
106 struct sockaddr_in server;
108 /* Create a socket */
109 http_sock = socket(AF_INET, SOCK_STREAM, 0);
114 server.sin_family = AF_INET;
115 server.sin_port = htons(http_port);
116 server.sin_addr.s_addr = INADDR_ANY;
117 if (bind(http_sock, (struct sockaddr *) & server, sizeof(server)) < 0) {
118 perror("bind socket");
121 if (verbose) printf("simple_httpd:%d\n",http_port);
125 * Wait here until we see an incoming http request
128 wait_connection(void)
132 lg = sizeof(struct sockaddr_in);
134 con_sock = accept(http_sock, (struct sockaddr *) & source, &lg);
142 * Print timestamp for HTTP HEAD and GET
151 strftime(buff, 50, "Date: %a, %d %h %Y %H:%M:%S %Z\r\n", gmtime(&tl));
152 write(con_sock, buff, strlen(buff));
157 * Send data to the open socket
160 http_output(const char *html)
162 write(con_sock, html, strlen(html));
163 write(con_sock, "\r\n", 2);
168 * Create and write the log information to file
169 * Log file format is one line per entry
176 char env_host[80], env_addr[80];
180 strcpy(log_buff,inet_ntoa(source.sin_addr));
181 sprintf(env_addr, "REMOTE_ADDR=%s",log_buff);
183 addr=inet_addr(log_buff);
187 hst=gethostbyaddr((char*) &addr, 4, AF_INET);
189 /* If DNS hostname exists */
191 strcat(msg,hst->h_name);
192 sprintf(env_host, "REMOTE_HOST=%s",hst->h_name);
195 strcat(msg,log_buff);
200 log=fopen(logfile,"a");
201 fprintf(log,"%s\n",msg);
206 /* This is for CGI scripts */
212 * We have a connection. Identify what type of request GET, HEAD, CGI, etc
213 * and do what needs to be done
221 const char *filename, *c, *ext, *type;
222 struct stat file_status;
226 lg = read(con_sock, req, 1024);
228 if ((p=strstr(req,"\n"))) *p=0;
229 if ((p=strstr(req,"\r"))) *p=0;
233 c = strtok(req, " ");
235 /* Error msg if request is nothing */
237 http_output(http_404[0]);
238 http_output(http_404[1]);
242 if (strncmp(c, "GET", 3) == 0) cmd = 1;
243 if (strncmp(c, "HEAD", 4) == 0) cmd = 2;
245 /* Do error msg for any other type of request */
247 http_output(http_405[0]);
248 http_output(http_405[1]);
252 filename = strtok(NULL, " ");
254 c = strtok(NULL, " ");
255 if (fetch_mode != NULL) filename=fetch_mode;
256 if (filename == NULL ||
257 strlen(filename)==1) filename="/index.html";
259 while (filename[0]== '/') filename++;
261 /* CGI handling. Untested */
262 if (!strncmp(filename,"cgi-bin/",8))
265 if ((par=strstr(filename,"?")))
270 if (access(filename,X_OK)) goto conti;
271 stat (filename,&file_status);
272 if (setuid(file_status.st_uid)) return;
273 if (seteuid(file_status.st_uid)) return;
278 /*printf("HTTP/1.0 200 OK\nContent-type: text/html\n\n\n");*/
279 printf("HTTP/1.0 200 OK\r\n");
280 /* Plug in environment variable, others in log_line */
281 putenv("SERVER_SOFTWARE=FreeBSD/PicoBSD");
283 execlp (filename,filename,par,(char *)0);
289 if (filename == NULL) {
290 http_output(http_405[0]);
291 http_output(http_405[1]);
294 /* End of CGI handling */
296 /* Reject any request with '..' in it, bad hacker */
299 if (c[0] == '.' && c[1] == '.') {
300 http_output(http_404[0]);
301 http_output(http_404[1]);
307 fd = open(filename, O_RDONLY);
309 http_output(http_404[0]);
310 http_output(http_404[1]);
314 /* Get file status information */
315 if (fstat(fd, &file_status) < 0) {
316 http_output(http_404[0]);
317 http_output(http_404[1]);
321 /* Is it a regular file? */
322 if (!S_ISREG(file_status.st_mode)) {
323 http_output(http_404[0]);
324 http_output(http_404[1]);
328 /* Past this point we are serving either a GET or HEAD */
329 /* Print all the header info */
330 http_output(http_200);
331 http_output(httpd_server_ident);
334 sprintf(buff, "Content-length: %lld\r\n", file_status.st_size);
335 write(con_sock, buff, strlen(buff));
337 strcpy(buff, "Content-type: ");
338 type = default_mime_type;
339 if ((ext = strrchr(filename, '.')) != NULL) {
340 for (i = mime_type_max; i >= 0; i--)
341 if (strcmp(ext + 1, mime_type[i][0]) == 0) {
342 type = mime_type[i][1];
349 strftime(buff, 50, "Last-Modified: %a, %d %h %Y %H:%M:%S %Z\r\n\r\n", gmtime(&file_status.st_mtime));
350 write(con_sock, buff, strlen(buff));
352 /* Send data only if GET request */
354 while ((lg = read(fd, buff, 8192)) > 0)
355 write(con_sock, buff, lg);
366 * Simple httpd server for use in PicoBSD or other embedded application.
367 * Should satisfy simple httpd needs. For more demanding situations
368 * apache is probably a better (but much larger) choice.
371 main(int argc, char *argv[])
374 int httpd_group = 65534;
377 /* Default for html directory */
378 strcpy (homedir,getenv("HOME"));
379 if (!geteuid()) strcpy (homedir,"/httphome");
380 else strcat (homedir,"/httphome");
382 /* Defaults for log file */
384 strcpy(logfile,getenv("HOME"));
386 strcat(logfile,"jhttp.log");
388 strcpy(logfile,"/var/log/jhttpd.log");
390 /* Parse command line arguments */
391 while ((ch = getopt(argc, argv, "d:f:g:l:p:vDh")) != -1)
394 strcpy(homedir,optarg);
402 httpd_group = atoi(optarg);
405 strcpy(logfile,optarg);
408 http_port = atoi(optarg);
419 printf("usage: simple_httpd [[-d directory][-g grpid][-l logfile][-p port][-vD]]\n");
424 /* Not running as root and no port supplied, assume 1080 */
425 if ((http_port == 80) && geteuid()) {
429 /* Do we really have rights in the html directory? */
430 if (fetch_mode == NULL) {
431 if (chdir(homedir)) {
438 /* Create log file if it doesn't exit */
439 if ((access(logfile,W_OK)) && daemonize) {
440 ld = open (logfile,O_WRONLY);
441 chmod (logfile,00600);
445 init_servconnection();
448 printf("Server started with options \n");
449 printf("port: %d\n",http_port);
450 if (fetch_mode == NULL) printf("html home: %s\n",homedir);
451 if (daemonize) printf("logfile: %s\n",logfile);
454 /* httpd is spawned */
456 if ((server_pid = fork()) != 0) {
458 if (verbose) printf("pid: %d\n",server_pid);
464 if (fetch_mode == NULL) setpgrp(0,httpd_group);
466 /* How many connections do you want?
467 * Keep this lower than the available number of processes
469 if (listen(http_sock,15) < 0) exit(1);
495 sprintf(out, "%02d:%02d:%02d %02d/%02d/%02d",
496 t->tm_hour, t->tm_min, t->tm_sec,
497 t->tm_mday, t->tm_mon+1, t->tm_year );