mkdata.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* This program is used to embed arbitrary data into a C binary. It takes
  2. * a list of files as an input, and produces a .c data file that contains
  3. * contents of all these files as collection of char arrays.
  4. *
  5. * Usage: ./mkdata <this_file> <file1> [file2, ...] > embedded_data.c
  6. */
  7. #include <stdlib.h>
  8. #include <stdio.h>
  9. #include <err.h>
  10. #include <errno.h>
  11. #include <string.h>
  12. const char* header =
  13. "#include <stddef.h>\n"
  14. "#include <string.h>\n"
  15. "#include <sys/types.h>\n"
  16. "#include \"src/http_server.h\"\n"
  17. "\n"
  18. "static const struct embedded_file embedded_files[] = {\n";
  19. const char* footer =
  20. " {NULL, NULL, NULL, 0}\n"
  21. "};\n"
  22. "\n"
  23. "const struct embedded_file *find_embedded_file(const char *name) {\n"
  24. " const struct embedded_file *p;\n"
  25. " for (p = embedded_files; p->name != NULL; p++)\n"
  26. " if (!strcmp(p->name, name))\n"
  27. " return p;\n"
  28. " return NULL;\n"
  29. "}\n";
  30. static const char* get_mime(char* filename)
  31. {
  32. const char *extension = strrchr(filename, '.');
  33. if(!strcmp(extension, ".js"))
  34. return "application/javascript";
  35. if(!strcmp(extension, ".css"))
  36. return "text/css";
  37. if(!strcmp(extension, ".ico"))
  38. return "image/vnd.microsoft.icon";
  39. if(!strcmp(extension, ".woff"))
  40. return "application/font-woff";
  41. if(!strcmp(extension, ".ttf"))
  42. return "application/x-font-ttf";
  43. if(!strcmp(extension, ".eot"))
  44. return "application/octet-stream";
  45. if(!strcmp(extension, ".svg"))
  46. return "image/svg+xml";
  47. if(!strcmp(extension, ".html"))
  48. return "text/html";
  49. return "text/plain";
  50. }
  51. int main(int argc, char *argv[])
  52. {
  53. int i, j, buf;
  54. FILE *fd;
  55. if(argc <= 1)
  56. err(EXIT_FAILURE, "Usage: ./%s <this_file> <file1> [file2, ...] > embedded_data.c", argv[0]);
  57. for(i = 1; i < argc; i++)
  58. {
  59. fd = fopen(argv[i], "r");
  60. if(!fd)
  61. err(EXIT_FAILURE, "%s", argv[i]);
  62. printf("static const unsigned char v%d[] = {", i);
  63. j = 0;
  64. while((buf = fgetc(fd)) != EOF)
  65. {
  66. if(!(j % 12))
  67. putchar('\n');
  68. printf(" %#04x, ", buf);
  69. j++;
  70. }
  71. printf(" 0x00\n};\n\n");
  72. fclose(fd);
  73. }
  74. fputs(header, stdout);
  75. for(i = 1; i < argc; i++)
  76. {
  77. printf(" {\"%s\", v%d, \"%s\", sizeof(v%d) - 1}, \n",
  78. argv[i]+6, i, get_mime(argv[i]), i);
  79. }
  80. fputs(footer, stdout);
  81. return EXIT_SUCCESS;
  82. }