aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

httpd.c (6669B)


      1 /* see LICENSE file for copyright and license details */
      2 
      3 #ifndef _XOPEN_SOURCE
      4 #define _XOPEN_SOURCE 500
      5 #endif
      6 
      7 #include "arg.h"
      8 #include "util.h"
      9 
     10 #include <arpa/inet.h>
     11 #include <ctype.h>
     12 #include <dirent.h>
     13 #include <errno.h>
     14 #include <fcntl.h>
     15 #include <netdb.h>
     16 #include <netinet/in.h>
     17 #include <stdio.h>
     18 #include <stdlib.h>
     19 #include <string.h>
     20 #include <strings.h>
     21 #include <sys/socket.h>
     22 #include <sys/stat.h>
     23 #include <sys/types.h>
     24 #include <time.h>
     25 #include <unistd.h>
     26 
     27 static void
     28 usage(void)
     29 {
     30   eprintf("usage: %s [-e string] [-d string] [-v] [dir]\n", argv0);
     31 }
     32 
     33 static char *
     34 url_decode(char *s)
     35 {
     36   char        *r, *w;
     37   unsigned int val;
     38 
     39   for (r = w = s; *r;) {
     40     if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) {
     41       sscanf(r + 1, "%2x", &val);
     42       *w++ = val;
     43       r += 3;
     44     } else if (*r == '+') {
     45       *w++ = ' ';
     46       r++;
     47     } else {
     48       *w++ = *r++;
     49     }
     50   }
     51   *w = '\0';
     52   return s;
     53 }
     54 
     55 static char *
     56 url_encode(const char *s)
     57 {
     58   char       *buf = emalloc(strlen(s) * 3 + 1);
     59   char       *w   = buf;
     60   const char *r   = s;
     61 
     62   while (*r) {
     63     if (isalnum((unsigned char)*r) || strchr("-._~", *r)) {
     64       *w++ = *r++;
     65     } else {
     66       w += sprintf(w, "%%%02X", (unsigned char)*r);
     67       r++;
     68     }
     69   }
     70   *w = '\0';
     71   return buf;
     72 }
     73 
     74 static void
     75 send_error(int status, const char *msg)
     76 {
     77   printf(
     78       "HTTP/1.1 %d %s\r\n"
     79       "Content-Type: text/html; charset=UTF-8\r\n"
     80       "Connection: close\r\n\r\n",
     81       status,
     82       msg
     83   );
     84   printf(
     85       "<html><head><title>%d %s</title></head>"
     86       "<body><h3>%d %s</h3></body></html>\n",
     87       status,
     88       msg,
     89       status,
     90       msg
     91   );
     92 }
     93 
     94 static int
     95 is_under(const char *file, const char *dir)
     96 {
     97   char  *rfile = realpath(file, NULL);
     98   char  *rdir  = realpath(dir, NULL);
     99   int    rc    = 0;
    100   size_t len;
    101 
    102   if (rfile && rdir) {
    103     len = strlen(rdir);
    104     if (strncmp(rfile, rdir, len) == 0) {
    105       if (rfile[len] == '\0' || rfile[len] == '/' || (len > 0 && rdir[len - 1] == '/'))
    106         rc = 1;
    107     }
    108   }
    109   free(rfile);
    110   free(rdir);
    111   return rc;
    112 }
    113 
    114 static const char *
    115 get_mime_type(const char *file)
    116 {
    117   const char *ext = strrchr(file, '.');
    118   if (!ext)
    119     return "application/octet-stream";
    120   ext++;
    121 
    122   if (strcasecmp(ext, "html") == 0 || strcasecmp(ext, "htm") == 0)
    123     return "text/html; charset=UTF-8";
    124   if (strcasecmp(ext, "css") == 0)
    125     return "text/css";
    126   if (strcasecmp(ext, "js") == 0)
    127     return "application/javascript";
    128   if (strcasecmp(ext, "png") == 0)
    129     return "image/png";
    130   if (strcasecmp(ext, "jpg") == 0 || strcasecmp(ext, "jpeg") == 0)
    131     return "image/jpeg";
    132   if (strcasecmp(ext, "gif") == 0)
    133     return "image/gif";
    134   if (strcasecmp(ext, "txt") == 0)
    135     return "text/plain; charset=UTF-8";
    136   if (strcasecmp(ext, "pdf") == 0)
    137     return "application/pdf";
    138   if (strcasecmp(ext, "zip") == 0)
    139     return "application/zip";
    140 
    141   return "application/octet-stream";
    142 }
    143 
    144 static void
    145 handle_connection(void)
    146 {
    147   struct stat    st, st_idx;
    148   struct dirent *de;
    149   DIR           *dir;
    150   char           line[4096];
    151   char           method[32], path[2048], proto[32];
    152   char           index_path[sizeof(path) + 32];
    153   char           file_buf[8192];
    154   char           date_buf[64];
    155   const char    *mime_type;
    156   char          *query, *p, *enc;
    157   ssize_t        n_read;
    158   size_t         len;
    159   int            fd;
    160 
    161   if (!fgets(line, sizeof(line), stdin))
    162     return;
    163 
    164   if (sscanf(line, "%31s %2047s %31s", method, path, proto) != 3) {
    165     send_error(400, "Bad Request");
    166     return;
    167   }
    168 
    169   while (fgets(line, sizeof(line), stdin)) {
    170     if (line[0] == '\r' || line[0] == '\n')
    171       break;
    172   }
    173 
    174   if (strcasecmp(method, "GET") != 0) {
    175     send_error(501, "Not Implemented");
    176     return;
    177   }
    178 
    179   url_decode(path);
    180 
    181   query = strchr(path, '?');
    182   if (query) {
    183     *query = '\0';
    184     setenv("QUERY_STRING", query + 1, 1);
    185   } else {
    186     unsetenv("QUERY_STRING");
    187   }
    188 
    189   p = path;
    190   while (*p == '/')
    191     p++;
    192   if (*p == '\0')
    193     p = ".";
    194 
    195   if (stat(p, &st) < 0) {
    196     send_error(404, "Not Found");
    197     return;
    198   }
    199 
    200   if (!is_under(p, ".")) {
    201     send_error(403, "Forbidden");
    202     return;
    203   }
    204 
    205   if (S_ISDIR(st.st_mode)) {
    206     len = strlen(path);
    207     if (len > 0 && path[len - 1] != '/') {
    208       printf(
    209           "HTTP/1.1 302 Found\r\n"
    210           "Location: %s/\r\n"
    211           "Connection: close\r\n\r\n",
    212           path
    213       );
    214       return;
    215     }
    216 
    217     snprintf(index_path, sizeof(index_path), "%s/index.html", p);
    218     if (stat(index_path, &st_idx) == 0 && S_ISREG(st_idx.st_mode)) {
    219       p  = index_path;
    220       st = st_idx;
    221       goto serve_file;
    222     }
    223 
    224     dir = opendir(p);
    225     if (!dir) {
    226       send_error(403, "Forbidden");
    227       return;
    228     }
    229 
    230     printf(
    231         "HTTP/1.1 200 OK\r\n"
    232         "Content-Type: text/html; charset=UTF-8\r\n"
    233         "Connection: close\r\n\r\n"
    234     );
    235     printf("<html><head><title>Index of %s</title></head><body>\n", path);
    236     printf("<h3>Index of %s</h3><hr><pre>\n", path);
    237 
    238     while ((de = readdir(dir))) {
    239       if (strcmp(de->d_name, ".") == 0)
    240         continue;
    241       enc = url_encode(de->d_name);
    242       printf("<a href=\"%s\">%s</a>\n", enc, de->d_name);
    243       free(enc);
    244     }
    245     printf("</pre><hr></body></html>\n");
    246     closedir(dir);
    247     return;
    248   }
    249 
    250 serve_file:
    251   fd = open(p, O_RDONLY);
    252   if (fd < 0) {
    253     send_error(403, "Forbidden");
    254     return;
    255   }
    256 
    257   mime_type = get_mime_type(p);
    258   strftime(date_buf, sizeof(date_buf), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&st.st_mtime));
    259 
    260   printf(
    261       "HTTP/1.1 200 OK\r\n"
    262       "Content-Type: %s\r\n"
    263       "Content-Length: %lld\r\n"
    264       "Last-Modified: %s\r\n"
    265       "Connection: close\r\n\r\n",
    266       mime_type,
    267       (long long)st.st_size,
    268       date_buf
    269   );
    270 
    271   while ((n_read = read(fd, file_buf, sizeof(file_buf))) > 0) {
    272     writeall(1, file_buf, n_read);
    273   }
    274   close(fd);
    275 }
    276 
    277 // ?man httpd: simple http daemon
    278 // ?man arguments: dir
    279 // ?man serve static files over http
    280 int
    281 main(int argc, char *argv[])
    282 {
    283   char *eflag = NULL;
    284   char *dflag = NULL;
    285   char *enc;
    286 
    287   ARGBEGIN
    288   {
    289     // ?man -e:str: specify expression or pattern
    290     case 'e':
    291       eflag = EARGF(usage());
    292       break;
    293     // ?man -d:str: specify directory
    294     case 'd':
    295       dflag = EARGF(usage());
    296       break;
    297     // ?man -v: verbose mode; show progress
    298     case 'v':
    299       break;
    300     default:
    301       usage();
    302   }
    303   ARGEND
    304 
    305   if (eflag) {
    306     enc = url_encode(eflag);
    307     printf("%s\n", enc);
    308     free(enc);
    309     return 0;
    310   }
    311 
    312   if (dflag) {
    313     printf("%s\n", url_decode(dflag));
    314     return 0;
    315   }
    316 
    317   if (argc > 0) {
    318     if (chdir(argv[0]) < 0)
    319       eprintf("chdir %s:\n", argv[0]);
    320   }
    321 
    322   handle_connection();
    323   return 0;
    324 }