physfshttpd.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. int amount_read;
  187. strncpy(ipstr, inet_ntoa(((struct sockaddr_in *) args->addr)->sin_addr),
  188. sizeof (ipstr));
  189. ipstr[sizeof (ipstr) - 1] = '\0';
  190. printf("%s: connected.\n", ipstr);
  191. amount_read = read(args->sock, buffer, sizeof (buffer));
  192. if (amount_read > 0)
  193. {
  194. buffer[sizeof (buffer) - 1] = '\0';
  195. ptr = strchr(buffer, '\n');
  196. if (!ptr)
  197. printf("%s: potentially bogus request.\n", ipstr);
  198. else
  199. {
  200. *ptr = '\0';
  201. ptr = strchr(buffer, '\r');
  202. if (ptr != NULL)
  203. *ptr = '\0';
  204. if ((toupper(buffer[0]) == 'G') &&
  205. (toupper(buffer[1]) == 'E') &&
  206. (toupper(buffer[2]) == 'T') &&
  207. (toupper(buffer[3]) == ' ') &&
  208. (toupper(buffer[4]) == '/'))
  209. {
  210. ptr = strchr(buffer + 5, ' ');
  211. if (ptr != NULL)
  212. *ptr = '\0';
  213. feed_http_request(ipstr, args->sock, buffer + 4);
  214. } /* if */
  215. } /* else */
  216. } /* else */
  217. /* !!! FIXME: Time the transfer. */
  218. printf("%s: closing connection.\n", ipstr);
  219. close(args->sock);
  220. free(args->addr);
  221. free(args);
  222. return NULL;
  223. } /* do_http */
  224. static void serve_http_request(int sock, struct sockaddr *addr,
  225. socklen_t addrlen)
  226. {
  227. http_args *args = (http_args *) malloc(sizeof (http_args));
  228. if (args == NULL)
  229. {
  230. printf("out of memory.\n");
  231. return;
  232. } /* if */
  233. args->addr = (struct sockaddr *) malloc(addrlen);
  234. if (args->addr == NULL)
  235. {
  236. free(args);
  237. printf("out of memory.\n");
  238. return;
  239. } /* if */
  240. args->sock = sock;
  241. args->addrlen = addrlen;
  242. memcpy(args->addr, addr, addrlen);
  243. /* !!! FIXME: optionally spin a thread... */
  244. do_http((void *) args);
  245. } /* server_http_request */
  246. static int create_listen_socket(short portnum)
  247. {
  248. int retval = -1;
  249. int protocol = 0; /* pray this is right. */
  250. #ifndef LACKING_PROTOENT
  251. struct protoent *prot;
  252. setprotoent(0);
  253. prot = getprotobyname("tcp");
  254. if (prot != NULL)
  255. protocol = prot->p_proto;
  256. #endif
  257. retval = socket(PF_INET, SOCK_STREAM, protocol);
  258. if (retval >= 0)
  259. {
  260. struct sockaddr_in addr;
  261. addr.sin_family = AF_INET;
  262. addr.sin_port = htons(portnum);
  263. addr.sin_addr.s_addr = INADDR_ANY;
  264. if ((bind(retval, (struct sockaddr *) &addr, (socklen_t) sizeof (addr)) == -1) ||
  265. (listen(retval, 5) == -1))
  266. {
  267. close(retval);
  268. retval = -1;
  269. } /* if */
  270. } /* if */
  271. return retval;
  272. } /* create_listen_socket */
  273. static int listensocket = -1;
  274. void at_exit_cleanup(void)
  275. {
  276. /*
  277. * !!! FIXME: If thread support, signal threads to terminate and
  278. * !!! FIXME: wait for them to clean up.
  279. */
  280. if (listensocket >= 0)
  281. close(listensocket);
  282. if (!PHYSFS_deinit())
  283. printf("PHYSFS_deinit() failed: %s\n", lastError());
  284. } /* at_exit_cleanup */
  285. int main(int argc, char **argv)
  286. {
  287. int i;
  288. int portnum = DEFAULT_PORTNUM;
  289. setbuf(stdout, NULL);
  290. setbuf(stderr, NULL);
  291. #ifndef LACKING_SIGNALS
  292. /* I'm not sure if this qualifies as a cheap trick... */
  293. signal(SIGTERM, exit);
  294. signal(SIGINT, exit);
  295. signal(SIGFPE, exit);
  296. signal(SIGSEGV, exit);
  297. signal(SIGPIPE, exit);
  298. signal(SIGILL, exit);
  299. #endif
  300. if (argc == 1)
  301. {
  302. printf("USAGE: %s <archive1> [archive2 [... archiveN]]\n", argv[0]);
  303. return 42;
  304. } /* if */
  305. if (!PHYSFS_init(argv[0]))
  306. {
  307. printf("PHYSFS_init() failed: %s\n", lastError());
  308. return 42;
  309. } /* if */
  310. /* normally, this is bad practice, but oh well. */
  311. atexit(at_exit_cleanup);
  312. for (i = 1; i < argc; i++)
  313. {
  314. if (!PHYSFS_mount(argv[i], NULL, 1))
  315. printf(" WARNING: failed to add [%s] to search path.\n", argv[i]);
  316. } /* else */
  317. listensocket = create_listen_socket(portnum);
  318. if (listensocket < 0)
  319. {
  320. printf("listen socket failed to create.\n");
  321. return 42;
  322. } /* if */
  323. while (1) /* infinite loop for now. */
  324. {
  325. struct sockaddr addr;
  326. socklen_t len;
  327. int s = accept(listensocket, &addr, &len);
  328. if (s < 0)
  329. {
  330. printf("accept() failed: %s\n", strerror(errno));
  331. close(listensocket);
  332. return 42;
  333. } /* if */
  334. serve_http_request(s, &addr, len);
  335. } /* while */
  336. return 0;
  337. } /* main */
  338. /* end of physfshttpd.c ... */