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>
54 int http_sock, con_sock;
56 const char *fetch_mode = NULL;
60 void init_servconnection(void);
62 void http_output(const char *html);
63 void http_request(void);
64 void log_line(char *req);
65 void wait_connection(void);
68 struct sockaddr_in source;
71 static char httpd_server_ident[] = "Server: FreeBSD/PicoBSD simple_httpd 1.1\r";
73 static char http_200[] = "HTTP/1.0 200 OK\r";
75 const char *default_mime_type = "application/octet-stream";
77 const char *mime_type[][2] = {
78 { "txt", "text/plain" },
79 { "htm", "text/html" },
80 { "html", "text/html" },
81 { "gif", "image/gif" },
82 { "jpg", "image/jpeg" },
83 { "mp3", "audio/mpeg" }
86 const int mime_type_max = sizeof(mime_type) / sizeof(mime_type[0]) - 1;
88 /* Two parts, HTTP Header and then HTML */
89 static const char *http_404[2] =
90 {"HTTP/1.0 404 Not found\r\n",
91 "<HTML><HEAD><TITLE>Error</TITLE></HEAD><BODY><H1>Error 404</H1>\
92 Not found - file doesn't exist or you do not have permission.\n</BODY></HTML>\r\n"
95 static const char *http_405[2] =
96 {"HTTP/1.0 405 Method Not allowed\r\nAllow: GET,HEAD\r\n",
97 "<HTML><HEAD><TITLE>Error</TITLE></HEAD><BODY><H1>Error 405</H1>\
98 This server only supports GET and HEAD requests.\n</BODY></HTML>\r\n"
102 * Only called on initial invocation
105 init_servconnection(void)
107 struct sockaddr_in server;
109 /* Create a socket */
110 http_sock = socket(AF_INET, SOCK_STREAM, 0);
115 server.sin_family = AF_INET;
116 server.sin_port = htons(http_port);
117 server.sin_addr.s_addr = INADDR_ANY;
118 if (bind(http_sock, (struct sockaddr *) & server, sizeof(server)) < 0) {
119 perror("bind socket");
122 if (verbose) printf("simple_httpd:%d\n",http_port);
126 * Wait here until we see an incoming http request
129 wait_connection(void)
133 lg = sizeof(struct sockaddr_in);
135 con_sock = accept(http_sock, (struct sockaddr *) & source, &lg);
143 * Print timestamp for HTTP HEAD and GET
152 strftime(buff, 50, "Date: %a, %d %h %Y %H:%M:%S %Z\r\n", gmtime(&tl));
153 write(con_sock, buff, strlen(buff));
158 * Send data to the open socket
161 http_output(const char *html)
163 write(con_sock, html, strlen(html));
164 write(con_sock, "\r\n", 2);
169 * Create and write the log information to file
170 * Log file format is one line per entry
177 char env_host[80], env_addr[80];
181 strcpy(log_buff,inet_ntoa(source.sin_addr));
182 sprintf(env_addr, "REMOTE_ADDR=%s",log_buff);
184 addr=inet_addr(log_buff);
188 hst=gethostbyaddr((char*) &addr, 4, AF_INET);
190 /* If DNS hostname exists */
192 strcat(msg,hst->h_name);
193 sprintf(env_host, "REMOTE_HOST=%s",hst->h_name);
196 strcat(msg,log_buff);
201 log=fopen(logfile,"a");
202 fprintf(log,"%s\n",msg);
207 /* This is for CGI scripts */
213 * We have a connection. Identify what type of request GET, HEAD, CGI, etc
214 * and do what needs to be done
222 const char *filename, *c, *ext, *type;
223 struct stat file_status;
227 lg = read(con_sock, req, 1024);
229 if ((p=strstr(req,"\n"))) *p=0;
230 if ((p=strstr(req,"\r"))) *p=0;
234 c = strtok(req, " ");
236 /* Error msg if request is nothing */
238 http_output(http_404[0]);
239 http_output(http_404[1]);
243 if (strncmp(c, "GET", 3) == 0) cmd = 1;
244 if (strncmp(c, "HEAD", 4) == 0) cmd = 2;
246 /* Do error msg for any other type of request */
248 http_output(http_405[0]);
249 http_output(http_405[1]);
253 filename = strtok(NULL, " ");
255 c = strtok(NULL, " ");
256 if (fetch_mode != NULL) filename=fetch_mode;
257 if (filename == NULL ||
258 strlen(filename)==1) filename="/index.html";
260 while (filename[0]== '/') filename++;
262 /* CGI handling. Untested */
263 if (!strncmp(filename,"cgi-bin/",8))
266 if ((par=strstr(filename,"?")))
271 if (access(filename,X_OK)) goto conti;
272 stat (filename,&file_status);
273 if (setuid(file_status.st_uid)) return;
274 if (seteuid(file_status.st_uid)) return;
279 /*printf("HTTP/1.0 200 OK\nContent-type: text/html\n\n\n");*/
280 printf("HTTP/1.0 200 OK\r\n");
281 /* Plug in environment variable, others in log_line */
282 setenv("SERVER_SOFTWARE", "FreeBSD/PicoBSD", 1);
284 execlp (filename,filename,par,(char *)0);
290 if (filename == NULL) {
291 http_output(http_405[0]);
292 http_output(http_405[1]);
295 /* End of CGI handling */
297 /* Reject any request with '..' in it, bad hacker */
300 if (c[0] == '.' && c[1] == '.') {
301 http_output(http_404[0]);
302 http_output(http_404[1]);
308 fd = open(filename, O_RDONLY);
310 http_output(http_404[0]);
311 http_output(http_404[1]);
315 /* Get file status information */
316 if (fstat(fd, &file_status) < 0) {
317 http_output(http_404[0]);
318 http_output(http_404[1]);
322 /* Is it a regular file? */
323 if (!S_ISREG(file_status.st_mode)) {
324 http_output(http_404[0]);
325 http_output(http_404[1]);
329 /* Past this point we are serving either a GET or HEAD */
330 /* Print all the header info */
331 http_output(http_200);
332 http_output(httpd_server_ident);
335 sprintf(buff, "Content-length: %jd\r\n", (intmax_t)file_status.st_size);
336 write(con_sock, buff, strlen(buff));
338 strcpy(buff, "Content-type: ");
339 type = default_mime_type;
340 if ((ext = strrchr(filename, '.')) != NULL) {
341 for (i = mime_type_max; i >= 0; i--)
342 if (strcmp(ext + 1, mime_type[i][0]) == 0) {
343 type = mime_type[i][1];
350 strftime(buff, 50, "Last-Modified: %a, %d %h %Y %H:%M:%S %Z\r\n\r\n", gmtime(&file_status.st_mtime));
351 write(con_sock, buff, strlen(buff));
353 /* Send data only if GET request */
355 while ((lg = read(fd, buff, 8192)) > 0)
356 write(con_sock, buff, lg);
367 * Simple httpd server for use in PicoBSD or other embedded application.
368 * Should satisfy simple httpd needs. For more demanding situations
369 * apache is probably a better (but much larger) choice.
372 main(int argc, char *argv[])
375 int httpd_group = 65534;
378 /* Default for html directory */
379 strcpy (homedir,getenv("HOME"));
380 if (!geteuid()) strcpy (homedir,"/httphome");
381 else strcat (homedir,"/httphome");
383 /* Defaults for log file */
385 strcpy(logfile,getenv("HOME"));
387 strcat(logfile,"jhttp.log");
389 strcpy(logfile,"/var/log/jhttpd.log");
391 /* Parse command line arguments */
392 while ((ch = getopt(argc, argv, "d:f:g:l:p:vDh")) != -1)
395 strcpy(homedir,optarg);
403 httpd_group = atoi(optarg);
406 strcpy(logfile,optarg);
409 http_port = atoi(optarg);
420 printf("usage: simple_httpd [[-d directory][-g grpid][-l logfile][-p port][-vD]]\n");
425 /* Not running as root and no port supplied, assume 1080 */
426 if ((http_port == 80) && geteuid()) {
430 /* Do we really have rights in the html directory? */
431 if (fetch_mode == NULL) {
432 if (chdir(homedir)) {
439 /* Create log file if it doesn't exit */
440 if ((access(logfile,W_OK)) && daemonize) {
441 ld = open (logfile,O_WRONLY);
442 chmod (logfile,00600);
446 init_servconnection();
449 printf("Server started with options \n");
450 printf("port: %d\n",http_port);
451 if (fetch_mode == NULL) printf("html home: %s\n",homedir);
452 if (daemonize) printf("logfile: %s\n",logfile);
455 /* httpd is spawned */
457 if ((server_pid = fork()) != 0) {
459 if (verbose) printf("pid: %d\n",server_pid);
465 if (fetch_mode == NULL) setpgrp(0,httpd_group);
467 /* How many connections do you want?
468 * Keep this lower than the available number of processes
470 if (listen(http_sock,15) < 0) exit(1);
496 sprintf(out, "%02d:%02d:%02d %02d/%02d/%02d",
497 t->tm_hour, t->tm_min, t->tm_sec,
498 t->tm_mday, t->tm_mon+1, t->tm_year );