xs_fcgi.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. /* copyright (c) 2022 - 2024 grunfink et al. / MIT license */
  2. /*
  3. This is an intentionally-dead-simple FastCGI implementation;
  4. only FCGI_RESPONDER type with *no* FCGI_KEEP_CON flag is supported.
  5. This means only one simultaneous connection and no multiplexing.
  6. It seems it's enough for nginx and OpenBSD's httpd, so here it goes.
  7. Almost fully compatible with xs_httpd.h
  8. */
  9. #ifndef _XS_FCGI_H
  10. #define _XS_FCGI_H
  11. xs_dict *xs_fcgi_request(FILE *f, xs_str **payload, int *p_size, int *id);
  12. void xs_fcgi_response(FILE *f, int status, xs_dict *headers, xs_str *body, int b_size, int id);
  13. #ifdef XS_IMPLEMENTATION
  14. struct fcgi_record_header {
  15. unsigned char version;
  16. unsigned char type;
  17. unsigned short id;
  18. unsigned short content_len;
  19. unsigned char padding_len;
  20. unsigned char reserved;
  21. } __attribute__((packed));
  22. /* version */
  23. #define FCGI_VERSION_1 1
  24. /* types */
  25. #define FCGI_BEGIN_REQUEST 1
  26. #define FCGI_ABORT_REQUEST 2
  27. #define FCGI_END_REQUEST 3
  28. #define FCGI_PARAMS 4
  29. #define FCGI_STDIN 5
  30. #define FCGI_STDOUT 6
  31. #define FCGI_STDERR 7
  32. #define FCGI_DATA 8
  33. #define FCGI_GET_VALUES 9
  34. #define FCGI_GET_VALUES_RESULT 10
  35. #define FCGI_UNKNOWN_TYPE 11
  36. #define FCGI_MAXTYPE (FCGI_UNKNOWN_TYPE)
  37. struct fcgi_begin_request {
  38. unsigned short role;
  39. unsigned char flags;
  40. unsigned char reserved[5];
  41. } __attribute__((packed));
  42. /* roles */
  43. #define FCGI_RESPONDER 1
  44. #define FCGI_AUTHORIZER 2
  45. #define FCGI_FILTER 3
  46. /* flags */
  47. #define FCGI_KEEP_CONN 1
  48. struct fcgi_end_request {
  49. unsigned int app_status;
  50. unsigned char protocol_status;
  51. unsigned char reserved[3];
  52. } __attribute__((packed));
  53. /* protocol statuses */
  54. #define FCGI_REQUEST_COMPLETE 0
  55. #define FCGI_CANT_MPX_CONN 1
  56. #define FCGI_OVERLOADED 2
  57. #define FCGI_UNKNOWN_ROLE 3
  58. xs_dict *xs_fcgi_request(FILE *f, xs_str **payload, int *p_size, int *fcgi_id)
  59. /* keeps receiving FCGI packets until a complete request is finished */
  60. {
  61. unsigned char p_buf[100000];
  62. struct fcgi_record_header hdr;
  63. struct fcgi_begin_request *breq = (struct fcgi_begin_request *)&p_buf;
  64. unsigned char *buf = NULL;
  65. int b_size = 0;
  66. xs_dict *req = NULL;
  67. unsigned char p_status = FCGI_REQUEST_COMPLETE;
  68. xs *q_vars = NULL;
  69. xs *p_vars = NULL;
  70. *fcgi_id = -1;
  71. for (;;) {
  72. int sz, psz;
  73. /* read the packet header */
  74. if (fread(&hdr, sizeof(hdr), 1, f) != 1)
  75. break;
  76. /* read the packet body */
  77. if ((psz = ntohs(hdr.content_len)) > 0) {
  78. if ((sz = fread(p_buf, 1, psz, f)) != psz)
  79. break;
  80. }
  81. /* read (and drop) the padding */
  82. if (hdr.padding_len > 0)
  83. fread(p_buf + sz, 1, hdr.padding_len, f);
  84. switch (hdr.type) {
  85. case FCGI_BEGIN_REQUEST:
  86. /* fail on unsupported roles */
  87. if (ntohs(breq->role) != FCGI_RESPONDER) {
  88. p_status = FCGI_UNKNOWN_ROLE;
  89. goto end;
  90. }
  91. /* fail on unsupported flags */
  92. if (breq->flags & FCGI_KEEP_CONN) {
  93. p_status = FCGI_CANT_MPX_CONN;
  94. goto end;
  95. }
  96. /* store the id for later */
  97. *fcgi_id = (int) hdr.id;
  98. break;
  99. case FCGI_PARAMS:
  100. /* unknown id? fail */
  101. if (hdr.id != *fcgi_id) {
  102. p_status = FCGI_CANT_MPX_CONN;
  103. goto end;
  104. }
  105. if (psz) {
  106. /* add to the buffer */
  107. buf = xs_realloc(buf, b_size + psz);
  108. memcpy(buf + b_size, p_buf, psz);
  109. b_size += psz;
  110. }
  111. else {
  112. /* no size, so the packet is complete; process it */
  113. xs *cgi_vars = xs_dict_new();
  114. req = xs_dict_new();
  115. int offset = 0;
  116. while (offset < b_size) {
  117. unsigned int ksz = buf[offset++];
  118. if (ksz & 0x80) {
  119. ksz &= 0x7f;
  120. ksz = (ksz << 8) | buf[offset++];
  121. ksz = (ksz << 8) | buf[offset++];
  122. ksz = (ksz << 8) | buf[offset++];
  123. }
  124. unsigned int vsz = buf[offset++];
  125. if (vsz & 0x80) {
  126. vsz &= 0x7f;
  127. vsz = (vsz << 8) | buf[offset++];
  128. vsz = (vsz << 8) | buf[offset++];
  129. vsz = (vsz << 8) | buf[offset++];
  130. }
  131. /* get the key */
  132. xs *k = xs_str_new_sz((char *)&buf[offset], ksz);
  133. offset += ksz;
  134. /* get the value */
  135. xs *v = xs_str_new_sz((char *)&buf[offset], vsz);
  136. offset += vsz;
  137. cgi_vars = xs_dict_append(cgi_vars, k, v);
  138. if (strcmp(k, "REQUEST_METHOD") == 0)
  139. req = xs_dict_append(req, "method", v);
  140. else
  141. if (strcmp(k, "REQUEST_URI") == 0) {
  142. req = xs_dict_append(req, "raw_path", v);
  143. xs *pnv = xs_split_n(v, "?", 1);
  144. /* store the path */
  145. req = xs_dict_append(req, "path", xs_list_get(pnv, 0));
  146. /* get the variables */
  147. q_vars = xs_url_vars(xs_list_get(pnv, 1));
  148. }
  149. else
  150. if (xs_match(k, "CONTENT_TYPE|CONTENT_LENGTH|HTTP_*")) {
  151. if (xs_startswith(k, "HTTP_"))
  152. k = xs_crop_i(k, 5, 0);
  153. k = xs_tolower_i(k);
  154. k = xs_replace_i(k, "_", "-");
  155. req = xs_dict_append(req, k, v);
  156. }
  157. }
  158. req = xs_dict_append(req, "cgi_vars", cgi_vars);
  159. buf = xs_free(buf);
  160. b_size = 0;
  161. }
  162. break;
  163. case FCGI_STDIN:
  164. /* unknown id? fail */
  165. if (hdr.id != *fcgi_id) {
  166. p_status = FCGI_CANT_MPX_CONN;
  167. goto end;
  168. }
  169. if (psz) {
  170. /* add to the buffer */
  171. buf = xs_realloc(buf, b_size + psz);
  172. memcpy(buf + b_size, p_buf, psz);
  173. b_size += psz;
  174. }
  175. else {
  176. /* add an asciiz to be able to treat it as a string */
  177. buf = xs_realloc(buf, _xs_blk_size(b_size + 1));
  178. buf[b_size] = '\0';
  179. /* fill the payload info and finish */
  180. *payload = (xs_str *)buf;
  181. *p_size = b_size;
  182. const char *ct = xs_dict_get(req, "content-type");
  183. if (*payload && ct && strcmp(ct, "application/x-www-form-urlencoded") == 0) {
  184. p_vars = xs_url_vars(*payload);
  185. }
  186. else
  187. if (*payload && ct && xs_startswith(ct, "multipart/form-data")) {
  188. p_vars = xs_multipart_form_data(*payload, *p_size, ct);
  189. }
  190. else
  191. p_vars = xs_dict_new();
  192. if (q_vars == NULL)
  193. q_vars = xs_dict_new();
  194. req = xs_dict_append(req, "q_vars", q_vars);
  195. req = xs_dict_append(req, "p_vars", p_vars);
  196. /* disconnect the payload from the buf variable */
  197. buf = NULL;
  198. goto end;
  199. }
  200. break;
  201. }
  202. }
  203. end:
  204. /* any kind of error? notify and cleanup */
  205. if (p_status != FCGI_REQUEST_COMPLETE) {
  206. struct fcgi_end_request ereq = {0};
  207. /* complete the connection */
  208. ereq.app_status = 0;
  209. ereq.protocol_status = p_status;
  210. /* reuse header */
  211. hdr.type = FCGI_ABORT_REQUEST;
  212. hdr.content_len = htons(sizeof(ereq));
  213. fwrite(&hdr, sizeof(hdr), 1, f);
  214. fwrite(&ereq, sizeof(ereq), 1, f);
  215. /* session closed */
  216. *fcgi_id = -1;
  217. /* request dict is not valid */
  218. req = xs_free(req);
  219. }
  220. xs_free(buf);
  221. return req;
  222. }
  223. void xs_fcgi_response(FILE *f, int status, xs_dict *headers, xs_str *body, int b_size, int fcgi_id)
  224. /* writes an FCGI response */
  225. {
  226. struct fcgi_record_header hdr = {0};
  227. struct fcgi_end_request ereq = {0};
  228. xs *out = xs_str_new(NULL);
  229. const xs_str *k;
  230. const xs_str *v;
  231. /* no previous id? it's an error */
  232. if (fcgi_id == -1)
  233. return;
  234. /* create the headers */
  235. {
  236. xs *s1 = xs_fmt("status: %d\r\n", status);
  237. out = xs_str_cat(out, s1);
  238. }
  239. xs_dict_foreach(headers, k, v) {
  240. xs *s1 = xs_fmt("%s: %s\r\n", k, v);
  241. out = xs_str_cat(out, s1);
  242. }
  243. if (b_size > 0) {
  244. xs *s1 = xs_fmt("content-length: %d\r\n", b_size);
  245. out = xs_str_cat(out, s1);
  246. }
  247. out = xs_str_cat(out, "\r\n");
  248. /* everything is text by now */
  249. int size = strlen(out);
  250. /* add the body */
  251. if (body != NULL && b_size > 0) {
  252. out = xs_append_m(out, body, b_size);
  253. size += b_size;
  254. }
  255. /* now send all the STDOUT in packets */
  256. hdr.version = FCGI_VERSION_1;
  257. hdr.type = FCGI_STDOUT;
  258. hdr.id = fcgi_id;
  259. int offset = 0;
  260. while (offset < size) {
  261. size_t sz = size - offset;
  262. if (sz > 0xffff)
  263. sz = 0xffff;
  264. hdr.content_len = htons(sz);
  265. /* write or fail */
  266. if (!fwrite(&hdr, sizeof(hdr), 1, f) || fwrite(out + offset, 1, sz, f) != sz)
  267. return;
  268. offset += sz;
  269. }
  270. /* final STDOUT packet with 0 size */
  271. hdr.content_len = 0;
  272. if (!fwrite(&hdr, sizeof(hdr), 1, f))
  273. return;
  274. /* complete the connection */
  275. ereq.app_status = 0;
  276. ereq.protocol_status = FCGI_REQUEST_COMPLETE;
  277. hdr.type = FCGI_END_REQUEST;
  278. hdr.content_len = htons(sizeof(ereq));
  279. if (fwrite(&hdr, sizeof(hdr), 1, f))
  280. fwrite(&ereq, sizeof(ereq), 1, f);
  281. }
  282. #endif /* XS_IMPLEMENTATION */
  283. #endif /* XS_URL_H */