physfshttpd.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /*
  2. * This is a quick and dirty HTTP server that uses PhysicsFS to retrieve
  3. * files. It is not robust at all, probably buggy, and definitely poorly
  4. * designed. It's just meant to show that it can be done.
  5. *
  6. * Basically, you compile this code, and run it:
  7. * ./physfshttpd archive1.zip archive2.zip /path/to/a/real/dir etc...
  8. *
  9. * The files are appended in order to the PhysicsFS search path, and when
  10. * a client request comes in, it looks for the file in said search path.
  11. *
  12. * My goal was to make this work in less than 300 lines of C, so again, it's
  13. * not to be used for any serious purpose. Patches to make this application
  14. * suck less will be readily and gratefully accepted.
  15. *
  16. * Command line I used to build this on Linux:
  17. * gcc -Wall -Werror -g -o bin/physfshttpd extras/physfshttpd.c -lphysfs
  18. *
  19. * License: this code is public domain. I make no warranty that it is useful,
  20. * correct, harmless, or environmentally safe.
  21. *
  22. * This particular file may be used however you like, including copying it
  23. * verbatim into a closed-source project, exploiting it commercially, and
  24. * removing any trace of my name from the source (although I hope you won't
  25. * do that). I welcome enhancements and corrections to this file, but I do
  26. * not require you to send me patches if you make changes. This code has
  27. * NO WARRANTY.
  28. *
  29. * Unless otherwise stated, the rest of PhysicsFS falls under the zlib license.
  30. * Please see LICENSE.txt in the root of the source tree.
  31. *
  32. * This file was written by Ryan C. Gordon. (icculus@icculus.org).
  33. */
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <stdarg.h>
  37. #include <string.h>
  38. #include <unistd.h>
  39. #include <errno.h>
  40. #include <ctype.h>
  41. #include <sys/types.h>
  42. #include <sys/socket.h>
  43. #include <netinet/in.h>
  44. #include <arpa/inet.h>
  45. #ifndef LACKING_SIGNALS
  46. #include <signal.h>
  47. #endif
  48. #ifndef LACKING_PROTOENT
  49. #include <netdb.h>
  50. #endif
  51. #include "physfs.h"
  52. #define DEFAULT_PORTNUM 8080
  53. typedef struct
  54. {
  55. int sock;
  56. struct sockaddr *addr;
  57. socklen_t addrlen;
  58. } http_args;
  59. #define txt404 \
  60. "HTTP/1.0 404 Not Found\n" \
  61. "Connection: close\n" \
  62. "Content-Type: text/html; charset=utf-8\n" \
  63. "\n" \
  64. "<html><head><title>404 Not Found</title></head>\n" \
  65. "<body>Can't find '%s'.</body></html>\n\n" \
  66. #define txt200 \
  67. "HTTP/1.0 200 OK\n" \
  68. "Connection: close\n" \
  69. "Content-Type: %s\n" \
  70. "\n"
  71. static const char *lastError(void)
  72. {
  73. return PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode());
  74. } /* lastError */
  75. static int writeAll(const char *ipstr, const int sock, void *buf, const size_t len)
  76. {
  77. PHYSFS_sint64 amount_written = write(sock, buf, len);
  78. if (amount_written < 0 || (size_t)amount_written != len)
  79. {
  80. printf("%s: Write error to socket.\n", ipstr);
  81. return 0;
  82. } /* if */
  83. return 1;
  84. } /* writeAll */
  85. static int writeString(const char *ipstr, const int sock, const char *fmt, ...)
  86. {
  87. /* none of this is robust against large strings or HTML escaping. */
  88. char buffer[1024];
  89. int len;
  90. va_list ap;
  91. va_start(ap, fmt);
  92. len = vsnprintf(buffer, sizeof (buffer), fmt, ap);
  93. va_end(ap);
  94. if (len < 0)
  95. {
  96. printf("uhoh, vsnprintf() failed!\n");
  97. return 0;
  98. } /* if */
  99. return writeAll(ipstr, sock, buffer, len);
  100. } /* writeString */
  101. static void feed_file_http(const char *ipstr, int sock, const char *fname)
  102. {
  103. PHYSFS_File *in = PHYSFS_openRead(fname);
  104. if (in == NULL)
  105. {
  106. printf("%s: Can't open [%s]: %s.\n", ipstr, fname, lastError());
  107. writeString(ipstr, sock, txt404, fname);
  108. return;
  109. } /* if */
  110. /* !!! FIXME: mimetype */
  111. if (writeString(ipstr, sock, txt200, "text/plain; charset=utf-8"))
  112. {
  113. do
  114. {
  115. char buffer[1024];
  116. PHYSFS_sint64 br = PHYSFS_readBytes(in, buffer, sizeof (buffer));
  117. if (br == -1)
  118. {
  119. printf("%s: Read error: %s.\n", ipstr, lastError());
  120. break;
  121. } /* if */
  122. else if (!writeAll(ipstr, sock, buffer, (size_t) br))
  123. {
  124. break;
  125. } /* else if */
  126. } while (!PHYSFS_eof(in));
  127. } /* if */
  128. PHYSFS_close(in);
  129. } /* feed_file_http */
  130. static void feed_dirlist_http(const char *ipstr, int sock,
  131. const char *dname, char **list)
  132. {
  133. int i;
  134. if (!writeString(ipstr, sock, txt200, "text/html; charset=utf-8"))
  135. return;
  136. else if (!writeString(ipstr, sock,
  137. "<html><head><title>Directory %s</title></head>"
  138. "<body><p><h1>Directory %s</h1></p><p><ul>\n",
  139. dname, dname))
  140. return;
  141. if (strcmp(dname, "/") == 0)
  142. dname = "";
  143. for (i = 0; list[i]; i++)
  144. {
  145. const char *fname = list[i];
  146. if (!writeString(ipstr, sock,
  147. "<li><a href='%s/%s'>%s</a></li>\n", dname, fname, fname))
  148. break;
  149. } /* for */
  150. writeString(ipstr, sock, "</ul></body></html>\n");
  151. } /* feed_dirlist_http */
  152. static void feed_dir_http(const char *ipstr, int sock, const char *dname)
  153. {
  154. char **list = PHYSFS_enumerateFiles(dname);
  155. if (list == NULL)
  156. {
  157. printf("%s: Can't enumerate directory [%s]: %s.\n",
  158. ipstr, dname, lastError());
  159. writeString(ipstr, sock, txt404, dname);
  160. return;
  161. } /* if */
  162. feed_dirlist_http(ipstr, sock, dname, list);
  163. PHYSFS_freeList(list);
  164. } /* feed_dir_http */
  165. static void feed_http_request(const char *ipstr, int sock, const char *fname)
  166. {
  167. PHYSFS_Stat statbuf;
  168. printf("%s: requested [%s].\n", ipstr, fname);
  169. if (!PHYSFS_stat(fname, &statbuf))
  170. {
  171. printf("%s: Can't stat [%s]: %s.\n", ipstr, fname, lastError());
  172. writeString(ipstr, sock, txt404, fname);
  173. return;
  174. } /* if */
  175. if (statbuf.filetype == PHYSFS_FILETYPE_DIRECTORY)
  176. feed_dir_http(ipstr, sock, fname);
  177. else
  178. feed_file_http(ipstr, sock, fname);
  179. } /* feed_http_request */
  180. static void *do_http(void *_args)
  181. {
  182. http_args *args = (http_args *) _args;
  183. char ipstr[128];
  184. char buffer[512];
  185. char *ptr;
  186. strncpy(ipstr, inet_ntoa(((struct sockaddr_in *) args->addr)->sin_addr),
  187. sizeof (ipstr));
  188. ipstr[sizeof (ipstr) - 1] = '\0';
  189. printf("%s: connected.\n", ipstr);
  190. read(args->sock, buffer, sizeof (buffer));
  191. buffer[sizeof (buffer) - 1] = '\0';
  192. ptr = strchr(buffer, '\n');
  193. if (!ptr)
  194. printf("%s: potentially bogus request.\n", ipstr);
  195. else
  196. {
  197. *ptr = '\0';
  198. ptr = strchr(buffer, '\r');
  199. if (ptr != NULL)
  200. *ptr = '\0';
  201. if ((toupper(buffer[0]) == 'G') &&
  202. (toupper(buffer[1]) == 'E') &&
  203. (toupper(buffer[2]) == 'T') &&
  204. (toupper(buffer[3]) == ' ') &&
  205. (toupper(buffer[4]) == '/'))
  206. {
  207. ptr = strchr(buffer + 5, ' ');
  208. if (ptr != NULL)
  209. *ptr = '\0';
  210. feed_http_request(ipstr, args->sock, buffer + 4);
  211. } /* if */
  212. } /* else */
  213. /* !!! FIXME: Time the transfer. */
  214. printf("%s: closing connection.\n", ipstr);
  215. close(args->sock);
  216. free(args->addr);
  217. free(args);
  218. return NULL;
  219. } /* do_http */
  220. static void serve_http_request(int sock, struct sockaddr *addr,
  221. socklen_t addrlen)
  222. {
  223. http_args *args = (http_args *) malloc(sizeof (http_args));
  224. if (args == NULL)
  225. {
  226. printf("out of memory.\n");
  227. return;
  228. } /* if */
  229. args->addr = (struct sockaddr *) malloc(addrlen);
  230. if (args->addr == NULL)
  231. {
  232. free(args);
  233. printf("out of memory.\n");
  234. return;
  235. } /* if */
  236. args->sock = sock;
  237. args->addrlen = addrlen;
  238. memcpy(args->addr, addr, addrlen);
  239. /* !!! FIXME: optionally spin a thread... */
  240. do_http((void *) args);
  241. } /* server_http_request */
  242. static int create_listen_socket(short portnum)
  243. {
  244. int retval = -1;
  245. int protocol = 0; /* pray this is right. */
  246. #ifndef LACKING_PROTOENT
  247. struct protoent *prot;
  248. setprotoent(0);
  249. prot = getprotobyname("tcp");
  250. if (prot != NULL)
  251. protocol = prot->p_proto;
  252. #endif
  253. retval = socket(PF_INET, SOCK_STREAM, protocol);
  254. if (retval >= 0)
  255. {
  256. struct sockaddr_in addr;
  257. addr.sin_family = AF_INET;
  258. addr.sin_port = htons(portnum);
  259. addr.sin_addr.s_addr = INADDR_ANY;
  260. if ((bind(retval, (struct sockaddr *) &addr, (socklen_t) sizeof (addr)) == -1) ||
  261. (listen(retval, 5) == -1))
  262. {
  263. close(retval);
  264. retval = -1;
  265. } /* if */
  266. } /* if */
  267. return retval;
  268. } /* create_listen_socket */
  269. static int listensocket = -1;
  270. void at_exit_cleanup(void)
  271. {
  272. /*
  273. * !!! FIXME: If thread support, signal threads to terminate and
  274. * !!! FIXME: wait for them to clean up.
  275. */
  276. if (listensocket >= 0)
  277. close(listensocket);
  278. if (!PHYSFS_deinit())
  279. printf("PHYSFS_deinit() failed: %s\n", lastError());
  280. } /* at_exit_cleanup */
  281. int main(int argc, char **argv)
  282. {
  283. int i;
  284. int portnum = DEFAULT_PORTNUM;
  285. setbuf(stdout, NULL);
  286. setbuf(stderr, NULL);
  287. #ifndef LACKING_SIGNALS
  288. /* I'm not sure if this qualifies as a cheap trick... */
  289. signal(SIGTERM, exit);
  290. signal(SIGINT, exit);
  291. signal(SIGFPE, exit);
  292. signal(SIGSEGV, exit);
  293. signal(SIGPIPE, exit);
  294. signal(SIGILL, exit);
  295. #endif
  296. if (argc == 1)
  297. {
  298. printf("USAGE: %s <archive1> [archive2 [... archiveN]]\n", argv[0]);
  299. return 42;
  300. } /* if */
  301. if (!PHYSFS_init(argv[0]))
  302. {
  303. printf("PHYSFS_init() failed: %s\n", lastError());
  304. return 42;
  305. } /* if */
  306. /* normally, this is bad practice, but oh well. */
  307. atexit(at_exit_cleanup);
  308. for (i = 1; i < argc; i++)
  309. {
  310. if (!PHYSFS_mount(argv[i], NULL, 1))
  311. printf(" WARNING: failed to add [%s] to search path.\n", argv[i]);
  312. } /* else */
  313. listensocket = create_listen_socket(portnum);
  314. if (listensocket < 0)
  315. {
  316. printf("listen socket failed to create.\n");
  317. return 42;
  318. } /* if */
  319. while (1) /* infinite loop for now. */
  320. {
  321. struct sockaddr addr;
  322. socklen_t len;
  323. int s = accept(listensocket, &addr, &len);
  324. if (s < 0)
  325. {
  326. printf("accept() failed: %s\n", strerror(errno));
  327. close(listensocket);
  328. return 42;
  329. } /* if */
  330. serve_http_request(s, &addr, len);
  331. } /* while */
  332. return 0;
  333. } /* main */
  334. /* end of physfshttpd.c ... */