ucmd_websrv.c 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725
  1. /* websrv: a minimal HTTP/1.1 + WebDAV server.
  2. *
  3. * The TCP stack and the NIC stay in the kernel (see tcp.c/sys_net.c); this
  4. * command owns the receiver, parses one request per connection (always
  5. * "Connection: close") and maps WebDAV onto the VFS:
  6. *
  7. * / the mounted filesystems (collections)
  8. * /ramfs/... read-only (the command pack)
  9. * /floppy1/... FAT, writable with 8.3 names only
  10. * /share/... writable RAM store with long names
  11. *
  12. * Methods: OPTIONS, GET, HEAD, PUT, DELETE, MKCOL, PROPFIND, PROPPATCH,
  13. * MOVE, LOCK, UNLOCK. No authentication: this is a trusted-LAN service.
  14. *
  15. * A file body is buffered whole (4 MB, or 1 MB when the heap is small)
  16. * because the VFS has no open/read/write-at interface.
  17. */
  18. #include "ucmd_lib.h"
  19. #define REQ_MAX 4096u
  20. #define BODY_MAX (4u * 1024u * 1024u)
  21. #define BODY_FALLBACK (1024u * 1024u)
  22. #define PATH_MAX 192u
  23. #define XML_MAX 3072u
  24. #define CHUNK_MAX 8224u
  25. #define SOCK_MS 1000u
  26. #define HDR_TIMEOUT_MS 10000u
  27. #define REQ_TIMEOUT_MS 60000u
  28. #define MAX_MOUNTS 24u
  29. static char hdr[REQ_MAX];
  30. static unsigned int hdr_len;
  31. static char rbuf[REQ_MAX];
  32. static unsigned char *body;
  33. static unsigned int body_max;
  34. static char resp[1024];
  35. static unsigned int resp_len;
  36. static char xml[XML_MAX];
  37. static unsigned int xml_len;
  38. static char cbuf[CHUNK_MAX];
  39. static char batch[8192];
  40. static unsigned int batch_len;
  41. static struct sys_mount mounts[MAX_MOUNTS];
  42. static unsigned int mount_count;
  43. static unsigned int req_start;
  44. static int status;
  45. static const char *extra_hdrs;
  46. struct req {
  47. char method[12];
  48. char target[PATH_MAX];
  49. char path[PATH_MAX];
  50. char dest[PATH_MAX];
  51. int http11;
  52. int have_len;
  53. unsigned int content_len;
  54. int chunked;
  55. int depth;
  56. int expect_continue;
  57. int overwrite;
  58. int have_dest;
  59. int keep_alive;
  60. };
  61. static struct req rq;
  62. /* ---- small string helpers ---- */
  63. static unsigned int s_len(const char *s)
  64. {
  65. unsigned int n = 0;
  66. while (s[n])
  67. n++;
  68. return n;
  69. }
  70. static int s_eq(const char *a, const char *b)
  71. {
  72. unsigned int i = 0;
  73. while (a[i] && b[i] && a[i] == b[i])
  74. i++;
  75. return a[i] == '\0' && b[i] == '\0';
  76. }
  77. static int s_ieq(const char *a, const char *b)
  78. {
  79. unsigned int i = 0;
  80. for (;;) {
  81. char ca = a[i], cb = b[i];
  82. if (ca >= 'A' && ca <= 'Z')
  83. ca = (char)(ca - 'A' + 'a');
  84. if (cb >= 'A' && cb <= 'Z')
  85. cb = (char)(cb - 'A' + 'a');
  86. if (ca != cb)
  87. return 0;
  88. if (!ca)
  89. return 1;
  90. i++;
  91. }
  92. }
  93. static int s_contains_ci(const char *hay, const char *needle)
  94. {
  95. unsigned int i, j, n = s_len(needle);
  96. if (!n)
  97. return 1;
  98. for (i = 0; hay[i]; i++) {
  99. for (j = 0; j < n; j++) {
  100. char a = hay[i + j], b = needle[j];
  101. if (!a)
  102. return 0;
  103. if (a >= 'A' && a <= 'Z')
  104. a = (char)(a - 'A' + 'a');
  105. if (b >= 'A' && b <= 'Z')
  106. b = (char)(b - 'A' + 'a');
  107. if (a != b)
  108. break;
  109. }
  110. if (j == n)
  111. return 1;
  112. }
  113. return 0;
  114. }
  115. static void s_copy(char *d, const char *s, unsigned int cap)
  116. {
  117. unsigned int i = 0;
  118. while (i + 1 < cap && s[i]) {
  119. d[i] = s[i];
  120. i++;
  121. }
  122. d[i] = '\0';
  123. }
  124. static void mem_copy(void *d, const void *s, unsigned int n)
  125. {
  126. unsigned char *dd = d;
  127. const unsigned char *ss = s;
  128. while (n--)
  129. *dd++ = *ss++;
  130. }
  131. static int hexval(int c)
  132. {
  133. if (c >= '0' && c <= '9')
  134. return c - '0';
  135. if (c >= 'a' && c <= 'f')
  136. return c - 'a' + 10;
  137. if (c >= 'A' && c <= 'F')
  138. return c - 'A' + 10;
  139. return -1;
  140. }
  141. /* ---- response buffer ---- */
  142. static void ra(const char *s)
  143. {
  144. while (*s && resp_len + 1 < sizeof(resp))
  145. resp[resp_len++] = *s++;
  146. resp[resp_len] = '\0';
  147. }
  148. static void rad(unsigned int v)
  149. {
  150. char tmp[12];
  151. unsigned int i = sizeof(tmp) - 1;
  152. tmp[i] = '\0';
  153. if (!v) {
  154. ra("0");
  155. return;
  156. }
  157. while (v && i > 0) {
  158. tmp[--i] = (char)('0' + (v % 10));
  159. v /= 10;
  160. }
  161. ra(tmp + i);
  162. }
  163. static const char *reason_phrase(int code)
  164. {
  165. switch (code) {
  166. case 100: return "Continue";
  167. case 200: return "OK";
  168. case 201: return "Created";
  169. case 204: return "No Content";
  170. case 207: return "Multi-Status";
  171. case 301: return "Moved Permanently";
  172. case 400: return "Bad Request";
  173. case 403: return "Forbidden";
  174. case 404: return "Not Found";
  175. case 405: return "Method Not Allowed";
  176. case 408: return "Request Timeout";
  177. case 409: return "Conflict";
  178. case 411: return "Length Required";
  179. case 412: return "Precondition Failed";
  180. case 413: return "Payload Too Large";
  181. case 414: return "URI Too Long";
  182. case 431: return "Request Header Fields Too Large";
  183. case 500: return "Internal Server Error";
  184. case 501: return "Not Implemented";
  185. case 507: return "Insufficient Storage";
  186. default: return "Error";
  187. }
  188. }
  189. /* Send the status line + headers. `extra` is appended verbatim (or NULL). */
  190. static int send_headers(int code, const char *reason, const char *ctype,
  191. unsigned int len)
  192. {
  193. resp_len = 0;
  194. ra("HTTP/1.1 ");
  195. rad((unsigned int)code);
  196. ra(" ");
  197. ra(reason);
  198. ra("\r\nServer: NebOS/0.2.0\r\n");
  199. ra((rq.keep_alive && code < 400) ? "Connection: keep-alive\r\n"
  200. : "Connection: close\r\n");
  201. ra("Cache-Control: no-store\r\n");
  202. if (extra_hdrs) {
  203. ra(extra_hdrs);
  204. ra("\r\n");
  205. }
  206. if (ctype) {
  207. ra("Content-Type: ");
  208. ra(ctype);
  209. ra("\r\n");
  210. }
  211. ra("Content-Length: ");
  212. rad(len);
  213. ra("\r\n\r\n");
  214. status = code;
  215. return u_tcp_srv_send(resp, resp_len);
  216. }
  217. /* Small response with an optional body. */
  218. static int send_body(int code, const char *reason, const char *ctype,
  219. const void *data, unsigned int len)
  220. {
  221. if (send_headers(code, reason, ctype, len) != 0)
  222. return -1;
  223. if (len && u_tcp_srv_send(data, len) != 0)
  224. return -1;
  225. return 0;
  226. }
  227. static int send_error(int code)
  228. {
  229. char msg[64];
  230. unsigned int n = 0;
  231. const char *reason = reason_phrase(code);
  232. msg[n++] = (char)('0' + (code / 100) % 10);
  233. msg[n++] = (char)('0' + (code / 10) % 10);
  234. msg[n++] = (char)('0' + code % 10);
  235. msg[n++] = ' ';
  236. while (*reason && n + 2 < sizeof(msg))
  237. msg[n++] = *reason++;
  238. msg[n++] = '\n';
  239. return send_body(code, reason_phrase(code), "text/plain", msg, n);
  240. }
  241. static int send_empty(int code)
  242. {
  243. return send_headers(code, reason_phrase(code), 0, 0);
  244. }
  245. /* Refuse a request and leave a human-readable reason in the terminal log
  246. * (the WebDAV client only sees the status code). */
  247. static int send_refuse(int code, const char *why)
  248. {
  249. u_puts("websrv: refused: ");
  250. u_puts(why);
  251. u_putc('\n');
  252. return send_error(code);
  253. }
  254. /* ---- chunked response (PROPFIND) ---- */
  255. static int chunk_send(const char *p, unsigned int n)
  256. {
  257. static const char hex[] = "0123456789abcdef";
  258. unsigned int l = 0, shift = 0, started = 0;
  259. if (n + 24 > sizeof(cbuf))
  260. return -1;
  261. if (!n) {
  262. mem_copy(cbuf, "0\r\n\r\n", 5);
  263. return u_tcp_srv_send(cbuf, 5);
  264. }
  265. /* hex size, most significant nibble first */
  266. for (shift = 28; ; shift -= 4) {
  267. unsigned int d = (n >> shift) & 0xF;
  268. if (d || started || shift == 0) {
  269. cbuf[l++] = hex[d];
  270. started = 1;
  271. }
  272. if (shift == 0)
  273. break;
  274. }
  275. cbuf[l++] = '\r';
  276. cbuf[l++] = '\n';
  277. mem_copy(cbuf + l, p, n);
  278. l += n;
  279. cbuf[l++] = '\r';
  280. cbuf[l++] = '\n';
  281. return u_tcp_srv_send(cbuf, l);
  282. }
  283. static const char multistatus_open[] =
  284. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  285. "<D:multistatus xmlns:D=\"DAV:\">";
  286. static int flush_batch(void)
  287. {
  288. if (!batch_len)
  289. return 0;
  290. if (chunk_send(batch, batch_len) != 0)
  291. return -1;
  292. batch_len = 0;
  293. return 0;
  294. }
  295. static int send_multistatus_begin(void)
  296. {
  297. resp_len = 0;
  298. ra("HTTP/1.1 207 Multi-Status\r\n");
  299. ra("Server: NebOS/0.2.0\r\n");
  300. ra("Content-Type: text/xml; charset=\"utf-8\"\r\n");
  301. ra("Transfer-Encoding: chunked\r\n");
  302. ra(rq.keep_alive ? "Connection: keep-alive\r\n"
  303. : "Connection: close\r\n");
  304. ra("Cache-Control: no-store\r\n\r\n");
  305. status = 207;
  306. if (u_tcp_srv_send(resp, resp_len) != 0)
  307. return -1;
  308. batch_len = 0;
  309. if (s_len(multistatus_open) > sizeof(batch))
  310. return -1;
  311. mem_copy(batch, multistatus_open, s_len(multistatus_open));
  312. batch_len = s_len(multistatus_open);
  313. return 0;
  314. }
  315. static int end_multistatus(void)
  316. {
  317. static const char close_tag[] = "</D:multistatus>";
  318. unsigned int n = s_len(close_tag);
  319. if (batch_len + n > sizeof(batch) && flush_batch() != 0)
  320. return -1;
  321. mem_copy(batch + batch_len, close_tag, n);
  322. batch_len += n;
  323. if (flush_batch() != 0)
  324. return -1;
  325. return chunk_send("", 0);
  326. }
  327. /* ---- XML building ---- */
  328. static void xa(const char *s)
  329. {
  330. while (*s && xml_len + 1 < sizeof(xml))
  331. xml[xml_len++] = *s++;
  332. xml[xml_len] = '\0';
  333. }
  334. static void xa_esc(const char *s)
  335. {
  336. while (*s && xml_len + 6 < sizeof(xml)) {
  337. char c = *s++;
  338. switch (c) {
  339. case '&': xa("&amp;"); break;
  340. case '<': xa("&lt;"); break;
  341. case '>': xa("&gt;"); break;
  342. case '"': xa("&quot;"); break;
  343. case '\'': xa("&apos;"); break;
  344. default: xml[xml_len++] = c; break;
  345. }
  346. }
  347. xml[xml_len] = '\0';
  348. }
  349. static void xa_dec(unsigned int v)
  350. {
  351. char tmp[12];
  352. unsigned int i = sizeof(tmp) - 1;
  353. tmp[i] = '\0';
  354. if (!v) {
  355. xa("0");
  356. return;
  357. }
  358. while (v && i > 0) {
  359. tmp[--i] = (char)('0' + (v % 10));
  360. v /= 10;
  361. }
  362. xa(tmp + i);
  363. }
  364. /* Percent-encode a path for an href (keep '/' and unreserved characters). */
  365. static void url_escape(const char *src, char *dst, unsigned int cap)
  366. {
  367. static const char hex[] = "0123456789ABCDEF";
  368. unsigned int n = 0;
  369. while (*src && n + 4 < cap) {
  370. unsigned char c = (unsigned char)*src++;
  371. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  372. (c >= '0' && c <= '9') || c == '/' || c == '-' ||
  373. c == '_' || c == '.' || c == '~') {
  374. dst[n++] = (char)c;
  375. } else {
  376. dst[n++] = '%';
  377. dst[n++] = hex[c >> 4];
  378. dst[n++] = hex[c & 0xF];
  379. }
  380. }
  381. dst[n] = '\0';
  382. }
  383. /* ---- request reader ---- */
  384. static unsigned char *rptr;
  385. static unsigned int rlen, rpos;
  386. static void rb_init(unsigned int off)
  387. {
  388. rptr = (unsigned char *)hdr + off;
  389. rlen = hdr_len - off;
  390. rpos = 0;
  391. }
  392. static int rb_read(unsigned char *dst, unsigned int n)
  393. {
  394. while (n) {
  395. unsigned int avail = rlen - rpos;
  396. if (!avail) {
  397. int r = u_tcp_srv_recv(rbuf, sizeof(rbuf), SOCK_MS);
  398. if (r <= 0)
  399. return -1;
  400. rptr = (unsigned char *)rbuf;
  401. rlen = (unsigned int)r;
  402. rpos = 0;
  403. continue;
  404. }
  405. {
  406. unsigned int k = avail < n ? avail : n;
  407. mem_copy(dst, rptr + rpos, k);
  408. rpos += k;
  409. dst += k;
  410. n -= k;
  411. }
  412. if (u_ticks_ms() - req_start > REQ_TIMEOUT_MS)
  413. return -1;
  414. }
  415. return 0;
  416. }
  417. static int rb_line(char *out, unsigned int cap)
  418. {
  419. unsigned int n = 0;
  420. for (;;) {
  421. unsigned char c;
  422. int r = rb_read(&c, 1);
  423. if (r != 0)
  424. return -1;
  425. if (c == '\n')
  426. break;
  427. if (n + 1 < cap)
  428. out[n++] = (char)c;
  429. else
  430. return -1;
  431. }
  432. if (n && out[n - 1] == '\r')
  433. n--;
  434. out[n] = '\0';
  435. return (int)n;
  436. }
  437. static int find_hdr_end(void)
  438. {
  439. unsigned int i;
  440. if (hdr_len < 4)
  441. return -1;
  442. for (i = 0; i + 3 < hdr_len; i++)
  443. if (hdr[i] == '\r' && hdr[i + 1] == '\n' &&
  444. hdr[i + 2] == '\r' && hdr[i + 3] == '\n')
  445. return (int)i;
  446. return -1;
  447. }
  448. /* A URL/file target -> absolute VFS path, no trailing slash, "" for root.
  449. * Accepts a path or an absolute URI (MOVE's Destination). */
  450. static int decode_path(const char *src, char *out, unsigned int cap)
  451. {
  452. const char *p = src;
  453. unsigned int o = 0;
  454. out[0] = '\0';
  455. if (p[0] != '/') {
  456. const char *q = p;
  457. while (*q && *q != ':' && *q != '/')
  458. q++;
  459. if (*q != ':')
  460. return -1;
  461. q++;
  462. while (*q == '/')
  463. q++;
  464. while (*q && *q != '/')
  465. q++;
  466. if (!*q) {
  467. out[0] = '\0';
  468. return 0;
  469. }
  470. p = q;
  471. }
  472. while (*p && *p != '?' && *p != '#') {
  473. char comp[PATH_MAX];
  474. unsigned int cl = 0;
  475. while (*p == '/')
  476. p++;
  477. while (*p && *p != '/' && *p != '?' && *p != '#') {
  478. int c = (unsigned char)*p++;
  479. if (c == '%') {
  480. int hi = p[0] ? hexval(p[0]) : -1;
  481. int lo = p[1] ? hexval(p[1]) : -1;
  482. if (hi < 0 || lo < 0)
  483. return -1;
  484. c = hi * 16 + lo;
  485. p += 2;
  486. if (c == 0 || c == '/')
  487. return -1;
  488. }
  489. if (cl + 1 >= sizeof(comp))
  490. return -1;
  491. comp[cl++] = (char)c;
  492. }
  493. comp[cl] = '\0';
  494. if (cl == 0 || (cl == 1 && comp[0] == '.'))
  495. continue;
  496. if (cl == 2 && comp[0] == '.' && comp[1] == '.') {
  497. while (o > 0 && out[o - 1] != '/')
  498. o--;
  499. if (o > 0)
  500. o--;
  501. out[o] = '\0';
  502. continue;
  503. }
  504. if (o + 1 + cl + 1 >= cap)
  505. return -1;
  506. out[o++] = '/';
  507. mem_copy(out + o, comp, cl);
  508. o += cl;
  509. out[o] = '\0';
  510. }
  511. return 0;
  512. }
  513. static void trim(char **s)
  514. {
  515. char *p = *s;
  516. unsigned int n;
  517. while (*p == ' ' || *p == '\t')
  518. p++;
  519. n = s_len(p);
  520. while (n && (p[n - 1] == ' ' || p[n - 1] == '\t'))
  521. p[--n] = '\0';
  522. *s = p;
  523. }
  524. /* Parse the request line and headers. Returns 0 or an HTTP error code. */
  525. static int parse_request(void)
  526. {
  527. char *line = hdr, *next;
  528. char *sp1, *sp2;
  529. /* request line */
  530. next = line;
  531. while (*next && *next != '\n')
  532. next++;
  533. if (*next == '\n')
  534. *next++ = '\0';
  535. if (s_len(line) && line[s_len(line) - 1] == '\r')
  536. line[s_len(line) - 1] = '\0';
  537. sp1 = line;
  538. while (*sp1 && *sp1 != ' ')
  539. sp1++;
  540. if (!*sp1)
  541. return 400;
  542. *sp1++ = '\0';
  543. sp2 = sp1;
  544. while (*sp2 && *sp2 != ' ')
  545. sp2++;
  546. if (!*sp2)
  547. return 400;
  548. *sp2++ = '\0';
  549. if (s_len(line) >= sizeof(rq.method))
  550. return 414;
  551. s_copy(rq.method, line, sizeof(rq.method));
  552. if (s_len(sp1) >= sizeof(rq.target))
  553. return 414;
  554. s_copy(rq.target, sp1, sizeof(rq.target));
  555. rq.http11 = s_eq(sp2, "HTTP/1.1");
  556. rq.keep_alive = rq.http11 ? 1 : 0;
  557. if (s_eq(sp1, "*")) {
  558. rq.path[0] = '\0';
  559. } else if (decode_path(sp1, rq.path, sizeof(rq.path)) != 0) {
  560. return 400;
  561. }
  562. /* headers */
  563. rq.depth = 1;
  564. rq.overwrite = 1;
  565. for (line = next; *line; ) {
  566. char *end = line;
  567. char *colon, *value;
  568. while (*end && *end != '\n')
  569. end++;
  570. if (*end == '\n')
  571. *end++ = '\0';
  572. if (s_len(line) && line[s_len(line) - 1] == '\r')
  573. line[s_len(line) - 1] = '\0';
  574. if (!line[0])
  575. break;
  576. colon = line;
  577. while (*colon && *colon != ':')
  578. colon++;
  579. if (!*colon) {
  580. line = end;
  581. continue;
  582. }
  583. *colon++ = '\0';
  584. value = colon;
  585. trim(&value);
  586. if (s_ieq(line, "Content-Length")) {
  587. unsigned int v = 0;
  588. char *q = value;
  589. if (!*q)
  590. return 400;
  591. while (*q) {
  592. if (*q < '0' || *q > '9')
  593. return 400;
  594. if (v > 0xFFFFFFFFu / 10)
  595. return 413;
  596. v = v * 10 + (unsigned int)(*q - '0');
  597. q++;
  598. }
  599. rq.have_len = 1;
  600. rq.content_len = v;
  601. } else if (s_ieq(line, "Transfer-Encoding")) {
  602. if (s_contains_ci(value, "chunked"))
  603. rq.chunked = 1;
  604. } else if (s_ieq(line, "Depth")) {
  605. if (value[0] == '0')
  606. rq.depth = 0;
  607. else if (value[0] == '1')
  608. rq.depth = 1;
  609. else
  610. rq.depth = 1; /* infinity: serve one level */
  611. } else if (s_ieq(line, "Destination")) {
  612. if (decode_path(value, rq.dest, sizeof(rq.dest)) == 0)
  613. rq.have_dest = 1;
  614. } else if (s_ieq(line, "Overwrite")) {
  615. rq.overwrite = !(value[0] == 'F' || value[0] == 'f');
  616. } else if (s_ieq(line, "Expect")) {
  617. if (s_contains_ci(value, "100-continue"))
  618. rq.expect_continue = 1;
  619. } else if (s_ieq(line, "Connection")) {
  620. if (s_contains_ci(value, "close"))
  621. rq.keep_alive = 0;
  622. else if (s_contains_ci(value, "keep-alive"))
  623. rq.keep_alive = 1;
  624. }
  625. line = end;
  626. }
  627. return 0;
  628. }
  629. static int read_request(void)
  630. {
  631. unsigned int start = u_ticks_ms();
  632. req_start = start;
  633. hdr_len = 0;
  634. rq.method[0] = '\0';
  635. rq.target[0] = '\0';
  636. rq.path[0] = '\0';
  637. rq.dest[0] = '\0';
  638. rq.http11 = 0;
  639. rq.have_len = 0;
  640. rq.content_len = 0;
  641. rq.chunked = 0;
  642. rq.depth = 1;
  643. rq.expect_continue = 0;
  644. rq.overwrite = 1;
  645. rq.have_dest = 0;
  646. rq.keep_alive = 0;
  647. for (;;) {
  648. int end = find_hdr_end();
  649. if (end >= 0) {
  650. hdr[end] = '\0';
  651. {
  652. int r = parse_request();
  653. if (r != 0)
  654. return r;
  655. }
  656. /* One active TCP connection: gvfs/Nautilus open
  657. * parallel ones, and an idle keep-alive connection
  658. * would block their SYNs. Close after each response. */
  659. rq.keep_alive = 0;
  660. rb_init((unsigned int)end + 4);
  661. return 0;
  662. }
  663. if (hdr_len >= REQ_MAX)
  664. return 431;
  665. if (u_ticks_ms() - start > HDR_TIMEOUT_MS)
  666. return 408;
  667. {
  668. int n = u_tcp_srv_recv(hdr + hdr_len,
  669. REQ_MAX - hdr_len, SOCK_MS);
  670. if (n > 0) {
  671. hdr_len += (unsigned int)n;
  672. } else if (n == 0 || n == -2) {
  673. return hdr_len ? 400 : -2;
  674. } else if (hdr_len == 0 &&
  675. u_ticks_ms() - start > 2000u) {
  676. /* Speculative connection with no request. */
  677. return -2;
  678. }
  679. }
  680. }
  681. }
  682. /* ---- body reader ---- */
  683. /* 0 ok, -1 I/O/timeout, -2 larger than max. Handles Content-Length and
  684. * chunked transfer encoding. */
  685. static int read_content(unsigned char *dst, unsigned int max,
  686. unsigned int *out_len)
  687. {
  688. unsigned int off = 0;
  689. *out_len = 0;
  690. if (rq.chunked) {
  691. for (;;) {
  692. char line[32];
  693. unsigned int sz = 0, i;
  694. int ln = rb_line(line, sizeof(line));
  695. if (ln <= 0)
  696. return -1;
  697. for (i = 0; line[i] && line[i] != ';'; i++) {
  698. int v = hexval(line[i]);
  699. if (v < 0)
  700. return -1;
  701. if (sz > (0xFFFFFFFFu >> 4))
  702. return -2;
  703. sz = (sz << 4) | (unsigned int)v;
  704. }
  705. if (sz == 0) {
  706. for (;;) {
  707. char t[32];
  708. int tl = rb_line(t, sizeof(t));
  709. if (tl < 0)
  710. return -1;
  711. if (tl == 0)
  712. break;
  713. }
  714. break;
  715. }
  716. if (off > max || sz > max - off)
  717. return -2;
  718. if (rb_read(dst + off, sz) != 0)
  719. return -1;
  720. off += sz;
  721. {
  722. unsigned char crlf[2];
  723. if (rb_read(crlf, 2) != 0)
  724. return -1;
  725. if (crlf[0] != '\r' || crlf[1] != '\n')
  726. return -1;
  727. }
  728. }
  729. } else if (rq.have_len) {
  730. if (rq.content_len > max)
  731. return -2;
  732. if (rq.content_len && rb_read(dst, rq.content_len) != 0)
  733. return -1;
  734. off = rq.content_len;
  735. }
  736. *out_len = off;
  737. return 0;
  738. }
  739. /* Read and discard a (small) request body so the response does not leave
  740. * unread data behind on the connection. */
  741. static int drain_body(void)
  742. {
  743. unsigned int n;
  744. int r = read_content(body, body_max < 65536u ? body_max : 65536u, &n);
  745. if (r == -2)
  746. return send_error(413), -1;
  747. if (r != 0)
  748. return send_error(400), -1;
  749. return 0;
  750. }
  751. /* Read and discard n bytes (a refused Content-Length body). Responding 413
  752. * while the client is still writing would make it see a reset, which some
  753. * gvfs versions treat as a dead mount. */
  754. static void discard_body(unsigned int n)
  755. {
  756. unsigned char tmp[512];
  757. while (n) {
  758. unsigned int k = n > sizeof(tmp) ? sizeof(tmp) : n;
  759. if (rb_read(tmp, k) != 0)
  760. return;
  761. n -= k;
  762. }
  763. }
  764. /* ---- mounts and paths ---- */
  765. static void load_mounts(void)
  766. {
  767. mount_count = 0;
  768. while (mount_count < MAX_MOUNTS &&
  769. u_syscall2(SYS_LIST_MOUNTS, (int)mount_count,
  770. (int)&mounts[mount_count]) == 1)
  771. mount_count++;
  772. }
  773. static const char *vpath(const char *p)
  774. {
  775. return p[0] ? p : "/";
  776. }
  777. /* Split "/mount/rel" into the mount name and the relative path. Returns 0
  778. * for the root, 1 for a mount path, -1 for a malformed path. */
  779. static int split_mount(const char *p, char *mount, unsigned int cap,
  780. const char **rel)
  781. {
  782. unsigned int i = 1, n = 0;
  783. if (p[0] != '/')
  784. return -1;
  785. if (!p[1])
  786. return 0;
  787. while (p[i] && p[i] != '/') {
  788. if (n + 1 >= cap)
  789. return -1;
  790. mount[n++] = p[i++];
  791. }
  792. mount[n] = '\0';
  793. *rel = p[i] ? p + i + 1 : p + i;
  794. return 1;
  795. }
  796. static struct sys_mount *mount_by_name(const char *name)
  797. {
  798. unsigned int i;
  799. for (i = 0; i < mount_count; i++)
  800. if (s_eq(mounts[i].name, name))
  801. return &mounts[i];
  802. return 0;
  803. }
  804. static struct sys_mount *mount_of(const char *p)
  805. {
  806. char name[16];
  807. const char *rel;
  808. if (split_mount(p, name, sizeof(name), &rel) != 1)
  809. return 0;
  810. return mount_by_name(name);
  811. }
  812. static int path_ro(const char *p)
  813. {
  814. struct sys_mount *m = mount_of(p);
  815. return !m || m->ro;
  816. }
  817. static int path_on_fat(const char *p)
  818. {
  819. struct sys_mount *m = mount_of(p);
  820. return m && (s_ieq(m->type, "FAT12") || s_ieq(m->type, "FAT16") ||
  821. s_ieq(m->type, "FAT32"));
  822. }
  823. /* "/share", "/ramfs", "/floppy1": the mount itself, not a file in it. */
  824. static int is_mount_root(const char *p)
  825. {
  826. char name[16];
  827. const char *rel;
  828. return split_mount(p, name, sizeof(name), &rel) == 1 && rel[0] == '\0';
  829. }
  830. static const char *base_name(const char *p)
  831. {
  832. const char *b = p, *q = p;
  833. while (*q) {
  834. if (*q == '/')
  835. b = q + 1;
  836. q++;
  837. }
  838. return b;
  839. }
  840. static int join_path(const char *dir, const char *name, char *out,
  841. unsigned int cap)
  842. {
  843. unsigned int n = 0;
  844. if (dir[0]) {
  845. while (dir[n] && n + 1 < cap) {
  846. out[n] = dir[n];
  847. n++;
  848. }
  849. }
  850. if (n + 1 >= cap)
  851. return -1;
  852. out[n++] = '/';
  853. {
  854. unsigned int i = 0;
  855. while (name[i] && n + 1 < cap)
  856. out[n++] = name[i++];
  857. }
  858. out[n] = '\0';
  859. return 0;
  860. }
  861. static void parent_path(const char *p, char *out, unsigned int cap)
  862. {
  863. int i = (int)s_len(p) - 1;
  864. while (i >= 0 && p[i] != '/')
  865. i--;
  866. if (i <= 0) {
  867. out[0] = '\0';
  868. return;
  869. }
  870. if ((unsigned int)i >= cap)
  871. i = (int)cap - 1;
  872. {
  873. int j;
  874. for (j = 0; j < i; j++)
  875. out[j] = p[j];
  876. out[i] = '\0';
  877. }
  878. }
  879. /* FAT accepts names that fat_name_to_8_3() can represent without silently
  880. * truncating: 1..8 base chars, optional 0..3 extension chars. */
  881. static int fat_char_ok(char c)
  882. {
  883. if (c >= 'A' && c <= 'Z')
  884. return 1;
  885. if (c >= 'a' && c <= 'z')
  886. return 1;
  887. if (c >= '0' && c <= '9')
  888. return 1;
  889. switch (c) {
  890. case '!': case '#': case '$': case '%': case '&': case '\'':
  891. case '(': case ')': case '-': case '@': case '^': case '_':
  892. case '`': case '{': case '}': case '~':
  893. return 1;
  894. }
  895. return 0;
  896. }
  897. static int fat_name_ok(const char *name)
  898. {
  899. unsigned int i, base = 0, ext = 0;
  900. int dot = 0;
  901. for (i = 0; name[i]; i++) {
  902. if (name[i] == '.') {
  903. if (dot)
  904. return 0;
  905. dot = 1;
  906. continue;
  907. }
  908. if (!fat_char_ok(name[i]))
  909. return 0;
  910. if (dot)
  911. ext++;
  912. else
  913. base++;
  914. }
  915. if (base == 0 || base > 8 || ext > 3)
  916. return 0;
  917. return 1;
  918. }
  919. /* The last component must be representable when creating a FAT name. */
  920. static int fat_path_ok(const char *p)
  921. {
  922. const char *b = base_name(p);
  923. return *b && fat_name_ok(b);
  924. }
  925. static const char *content_type(const char *p)
  926. {
  927. const char *d = p, *q = p;
  928. while (*q) {
  929. if (*q == '.')
  930. d = q;
  931. q++;
  932. }
  933. if (!*d)
  934. return "application/octet-stream";
  935. if (s_ieq(d, ".txt") || s_ieq(d, ".md") || s_ieq(d, ".c") ||
  936. s_ieq(d, ".h") || s_ieq(d, ".log") || s_ieq(d, ".ini"))
  937. return "text/plain; charset=utf-8";
  938. if (s_ieq(d, ".html") || s_ieq(d, ".htm"))
  939. return "text/html; charset=utf-8";
  940. if (s_ieq(d, ".png"))
  941. return "image/png";
  942. if (s_ieq(d, ".jpg") || s_ieq(d, ".jpeg"))
  943. return "image/jpeg";
  944. if (s_ieq(d, ".gif"))
  945. return "image/gif";
  946. if (s_ieq(d, ".bmp"))
  947. return "image/bmp";
  948. if (s_ieq(d, ".tga"))
  949. return "image/x-tga";
  950. if (s_ieq(d, ".pnm") || s_ieq(d, ".ppm") || s_ieq(d, ".pgm"))
  951. return "image/x-portable-anymap";
  952. return "application/octet-stream";
  953. }
  954. static int http_from_vfs(int r)
  955. {
  956. switch (r) {
  957. case SYS_EROFS: return 403;
  958. case SYS_ENOENT: return 404;
  959. case SYS_ENODEV: return 404;
  960. case SYS_ENOFS: return 404;
  961. case SYS_EINVAL: return 409;
  962. case SYS_ENOSPC: return 507;
  963. case SYS_EWRITE: return 507;
  964. default: return 500;
  965. }
  966. }
  967. /* ---- WebDAV helpers ---- */
  968. static int emit_prop(const char *p, int is_dir, unsigned int size,
  969. const char *display)
  970. {
  971. char href[PATH_MAX * 3];
  972. url_escape(p[0] ? p : "/", href, sizeof(href));
  973. if (is_dir && href[s_len(href) - 1] != '/') {
  974. unsigned int n = s_len(href);
  975. if (n + 1 < sizeof(href)) {
  976. href[n++] = '/';
  977. href[n] = '\0';
  978. }
  979. }
  980. xml_len = 0;
  981. xa("<D:response><D:href>");
  982. xa_esc(href);
  983. xa("</D:href><D:propstat><D:prop><D:resourcetype>");
  984. if (is_dir)
  985. xa("<D:collection/>");
  986. xa("</D:resourcetype>");
  987. if (!is_dir) {
  988. xa("<D:getcontentlength>");
  989. xa_dec(size);
  990. xa("</D:getcontentlength><D:getcontenttype>");
  991. xa_esc(content_type(p));
  992. xa("</D:getcontenttype>");
  993. }
  994. xa("<D:displayname>");
  995. xa_esc(display);
  996. xa("</D:displayname>");
  997. xa("<D:getlastmodified>Thu, 01 Jan 2026 00:00:00 GMT</D:getlastmodified>");
  998. xa("</D:prop><D:status>HTTP/1.1 200 OK</D:status></D:propstat>");
  999. xa("</D:response>");
  1000. if (xml_len > sizeof(batch))
  1001. return -1;
  1002. if (batch_len + xml_len > sizeof(batch) && flush_batch() != 0)
  1003. return -1;
  1004. mem_copy(batch + batch_len, xml, xml_len);
  1005. batch_len += xml_len;
  1006. return 0;
  1007. }
  1008. static int list_child(unsigned int index, const char *dir, char *out,
  1009. int *is_dir, unsigned int *size)
  1010. {
  1011. struct sys_dirent d;
  1012. char disp[64];
  1013. if (u_syscall3(SYS_LIST_DIR, (int)vpath(dir), (int)index,
  1014. (int)&d) != 1)
  1015. return 0;
  1016. if (d.raw_83)
  1017. u_fat_name(d.name, disp, sizeof(disp));
  1018. else
  1019. s_copy(disp, d.name, sizeof(disp));
  1020. if (!disp[0])
  1021. return 0;
  1022. if (join_path(dir, disp, out, PATH_MAX) != 0)
  1023. return 0;
  1024. *is_dir = (int)d.is_dir;
  1025. *size = d.size;
  1026. return 1;
  1027. }
  1028. /* ---- method handlers ---- */
  1029. static void do_options2(void)
  1030. {
  1031. resp_len = 0;
  1032. ra("HTTP/1.1 200 OK\r\nServer: NebOS/0.2.0\r\n");
  1033. ra("DAV: 1, 2\r\nMS-Author-Via: DAV\r\n");
  1034. ra("Allow: OPTIONS, GET, HEAD, PUT, DELETE, MKCOL, PROPFIND, "
  1035. "PROPPATCH, MOVE, LOCK, UNLOCK\r\n");
  1036. ra(rq.keep_alive ? "Connection: keep-alive\r\n"
  1037. : "Connection: close\r\n");
  1038. ra("Cache-Control: no-store\r\n");
  1039. ra("Content-Length: 0\r\n\r\n");
  1040. status = 200;
  1041. u_tcp_srv_send(resp, resp_len);
  1042. }
  1043. static void do_get(int head)
  1044. {
  1045. struct sys_stat st;
  1046. unsigned int off;
  1047. if (!rq.path[0]) {
  1048. send_error(405);
  1049. return;
  1050. }
  1051. if (u_stat(vpath(rq.path), &st) != 0) {
  1052. send_error(404);
  1053. return;
  1054. }
  1055. if (st.is_dir) {
  1056. send_error(405);
  1057. return;
  1058. }
  1059. if (st.size > body_max) {
  1060. send_error(413);
  1061. return;
  1062. }
  1063. {
  1064. int n = u_syscall3(SYS_READ_FILE, (int)rq.path, (int)body,
  1065. (int)body_max);
  1066. if (n < 0) {
  1067. send_error(http_from_vfs(n));
  1068. return;
  1069. }
  1070. if (send_headers(200, "OK", content_type(rq.path),
  1071. (unsigned int)n) != 0)
  1072. return;
  1073. if (head)
  1074. return;
  1075. for (off = 0; off < (unsigned int)n; ) {
  1076. unsigned int k = (unsigned int)n - off;
  1077. if (k > 65536u)
  1078. k = 65536u;
  1079. if (u_tcp_srv_send(body + off, k) != 0)
  1080. return;
  1081. off += k;
  1082. }
  1083. }
  1084. }
  1085. static void do_put(void)
  1086. {
  1087. struct sys_stat st;
  1088. char parent[PATH_MAX];
  1089. unsigned int len;
  1090. int existed = 0, r;
  1091. if (!rq.path[0]) {
  1092. send_error(403);
  1093. return;
  1094. }
  1095. if (!rq.have_len && !rq.chunked) {
  1096. send_error(411);
  1097. return;
  1098. }
  1099. if (rq.have_len && rq.content_len > body_max) {
  1100. /* Drain a body that is already on the wire (not when the client
  1101. * is still waiting for 100 Continue), then refuse cleanly. */
  1102. if (!rq.expect_continue &&
  1103. rq.content_len <= 64u * 1024u * 1024u)
  1104. discard_body(rq.content_len);
  1105. send_error(413);
  1106. return;
  1107. }
  1108. if (path_ro(rq.path)) {
  1109. send_error(403);
  1110. return;
  1111. }
  1112. if (path_on_fat(rq.path) && !fat_path_ok(rq.path)) {
  1113. send_refuse(409, "FAT name is not 8.3 (use /share)");
  1114. return;
  1115. }
  1116. parent_path(rq.path, parent, sizeof(parent));
  1117. if (parent[0]) {
  1118. if (u_stat(vpath(parent), &st) != 0 || !st.is_dir) {
  1119. send_refuse(409, "PUT parent directory is missing");
  1120. return;
  1121. }
  1122. }
  1123. if (u_stat(vpath(rq.path), &st) == 0) {
  1124. if (st.is_dir) {
  1125. send_refuse(409, "PUT target is a directory");
  1126. return;
  1127. }
  1128. existed = 1;
  1129. }
  1130. if (rq.expect_continue && rq.http11)
  1131. u_tcp_srv_send("HTTP/1.1 100 Continue\r\n\r\n", 25);
  1132. r = read_content(body, body_max, &len);
  1133. if (r == -2) {
  1134. send_error(413);
  1135. return;
  1136. }
  1137. if (r != 0) {
  1138. send_error(400);
  1139. return;
  1140. }
  1141. r = u_syscall3(SYS_WRITE_FILE, (int)rq.path, (int)body, (int)len);
  1142. if (r != 0) {
  1143. u_puts("websrv: write failed code ");
  1144. u_putdec((unsigned int)-r);
  1145. u_putc('\n');
  1146. send_error(http_from_vfs(r));
  1147. return;
  1148. }
  1149. send_empty(existed ? 204 : 201);
  1150. }
  1151. static void do_mkcol(void)
  1152. {
  1153. struct sys_stat st;
  1154. char parent[PATH_MAX];
  1155. int r;
  1156. if (!rq.path[0] || path_ro(rq.path)) {
  1157. send_error(403);
  1158. return;
  1159. }
  1160. if (path_on_fat(rq.path) && !fat_path_ok(rq.path)) {
  1161. send_refuse(409, "MKCOL FAT name is not 8.3 (use /share)");
  1162. return;
  1163. }
  1164. if (u_stat(vpath(rq.path), &st) == 0) {
  1165. send_error(405);
  1166. return;
  1167. }
  1168. parent_path(rq.path, parent, sizeof(parent));
  1169. if (parent[0]) {
  1170. if (u_stat(vpath(parent), &st) != 0 || !st.is_dir) {
  1171. send_refuse(409, "MKCOL parent directory is missing");
  1172. return;
  1173. }
  1174. }
  1175. r = u_syscall1(SYS_MKDIR, (int)rq.path);
  1176. if (r != 0) {
  1177. u_puts("websrv: mkdir failed code ");
  1178. u_putdec((unsigned int)-r);
  1179. u_putc('\n');
  1180. send_error(http_from_vfs(r));
  1181. return;
  1182. }
  1183. send_empty(201);
  1184. }
  1185. static int delete_tree(const char *p, unsigned int depth)
  1186. {
  1187. struct sys_stat st;
  1188. unsigned int i;
  1189. int r;
  1190. if (depth > 8)
  1191. return SYS_EINVAL;
  1192. if (u_stat(vpath(p), &st) != 0)
  1193. return SYS_ENOENT;
  1194. if (st.is_dir) {
  1195. for (i = 0; ; i++) {
  1196. char child[PATH_MAX];
  1197. int is_dir;
  1198. unsigned int size;
  1199. if (!list_child(i, p, child, &is_dir, &size))
  1200. break;
  1201. r = delete_tree(child, depth + 1);
  1202. if (r != 0)
  1203. return r;
  1204. }
  1205. return u_syscall1(SYS_RMDIR, (int)p);
  1206. }
  1207. return u_syscall1(SYS_UNLINK, (int)p);
  1208. }
  1209. static void do_delete(void)
  1210. {
  1211. int r;
  1212. if (!rq.path[0] || is_mount_root(rq.path) || path_ro(rq.path)) {
  1213. send_error(403);
  1214. return;
  1215. }
  1216. r = delete_tree(rq.path, 0);
  1217. if (r != 0) {
  1218. send_error(http_from_vfs(r));
  1219. return;
  1220. }
  1221. send_empty(204);
  1222. }
  1223. static void do_move(void)
  1224. {
  1225. struct sys_stat st, dst;
  1226. unsigned int len;
  1227. int existed = 0, r;
  1228. if (!rq.path[0] || path_ro(rq.path)) {
  1229. send_error(403);
  1230. return;
  1231. }
  1232. if (!rq.have_dest || !rq.dest[0]) {
  1233. send_error(400);
  1234. return;
  1235. }
  1236. if (s_eq(rq.path, rq.dest)) {
  1237. send_empty(204);
  1238. return;
  1239. }
  1240. if (path_ro(rq.dest)) {
  1241. send_error(403);
  1242. return;
  1243. }
  1244. if (path_on_fat(rq.dest) && !fat_path_ok(rq.dest)) {
  1245. send_refuse(409, "MOVE destination FAT name is not 8.3");
  1246. return;
  1247. }
  1248. if (u_stat(vpath(rq.path), &st) != 0) {
  1249. send_error(404);
  1250. return;
  1251. }
  1252. if (st.is_dir) {
  1253. send_error(501); /* directory renames are not supported */
  1254. return;
  1255. }
  1256. if (st.size > body_max) {
  1257. send_error(413);
  1258. return;
  1259. }
  1260. {
  1261. char parent[PATH_MAX];
  1262. parent_path(rq.dest, parent, sizeof(parent));
  1263. if (parent[0] &&
  1264. (u_stat(vpath(parent), &dst) != 0 || !dst.is_dir)) {
  1265. send_refuse(409, "MOVE destination parent is missing");
  1266. return;
  1267. }
  1268. }
  1269. if (u_stat(vpath(rq.dest), &dst) == 0) {
  1270. if (dst.is_dir) {
  1271. send_refuse(409, "MOVE destination is a directory");
  1272. return;
  1273. }
  1274. if (!rq.overwrite) {
  1275. send_error(412);
  1276. return;
  1277. }
  1278. existed = 1;
  1279. }
  1280. r = u_syscall3(SYS_READ_FILE, (int)rq.path, (int)body,
  1281. (int)body_max);
  1282. if (r < 0) {
  1283. send_error(http_from_vfs(r));
  1284. return;
  1285. }
  1286. len = (unsigned int)r;
  1287. r = u_syscall3(SYS_WRITE_FILE, (int)rq.dest, (int)body, (int)len);
  1288. if (r != 0) {
  1289. send_error(http_from_vfs(r));
  1290. return;
  1291. }
  1292. r = u_syscall1(SYS_UNLINK, (int)rq.path);
  1293. if (r != 0 && r != SYS_ENOENT) {
  1294. send_error(http_from_vfs(r));
  1295. return;
  1296. }
  1297. send_empty(existed ? 204 : 201);
  1298. }
  1299. static void do_propfind(void)
  1300. {
  1301. struct sys_stat st;
  1302. unsigned int i;
  1303. if (drain_body() != 0)
  1304. return;
  1305. if (!rq.path[0]) {
  1306. if (send_multistatus_begin() != 0)
  1307. return;
  1308. if (emit_prop("", 1, 0, "/") != 0) {
  1309. end_multistatus();
  1310. return;
  1311. }
  1312. if (rq.depth) {
  1313. for (i = 0; i < mount_count; i++) {
  1314. char mpath[32];
  1315. if (join_path("", mounts[i].name, mpath,
  1316. sizeof(mpath)) != 0)
  1317. continue;
  1318. if (emit_prop(mpath, 1, 0, mounts[i].name) != 0)
  1319. break;
  1320. }
  1321. }
  1322. end_multistatus();
  1323. return;
  1324. }
  1325. if (u_stat(vpath(rq.path), &st) != 0) {
  1326. send_error(404);
  1327. return;
  1328. }
  1329. if (send_multistatus_begin() != 0)
  1330. return;
  1331. if (emit_prop(rq.path, st.is_dir, st.size, base_name(rq.path)) != 0) {
  1332. end_multistatus();
  1333. return;
  1334. }
  1335. if (st.is_dir && rq.depth) {
  1336. for (i = 0; ; i++) {
  1337. char child[PATH_MAX];
  1338. int is_dir;
  1339. unsigned int size;
  1340. if (!list_child(i, rq.path, child, &is_dir, &size))
  1341. break;
  1342. if (emit_prop(child, is_dir, size,
  1343. base_name(child)) != 0)
  1344. break;
  1345. }
  1346. }
  1347. end_multistatus();
  1348. }
  1349. static void do_proppatch(void)
  1350. {
  1351. char href[PATH_MAX * 3];
  1352. unsigned int n = 0;
  1353. if (drain_body() != 0)
  1354. return;
  1355. url_escape(rq.path[0] ? rq.path : "/", href, sizeof(href));
  1356. xml_len = 0;
  1357. xa("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
  1358. xa("<D:multistatus xmlns:D=\"DAV:\"><D:response><D:href>");
  1359. xa_esc(href);
  1360. xa("</D:href><D:propstat><D:prop/>"
  1361. "<D:status>HTTP/1.1 200 OK</D:status></D:propstat>"
  1362. "</D:response></D:multistatus>");
  1363. n = xml_len;
  1364. send_body(207, "Multi-Status", "text/xml; charset=\"utf-8\"",
  1365. xml, n);
  1366. }
  1367. static void do_lock(void)
  1368. {
  1369. static const char lockbody[] =
  1370. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  1371. "<D:prop xmlns:D=\"DAV:\"><D:lockdiscovery><D:activelock>"
  1372. "<D:locktype><D:write/></D:locktype>"
  1373. "<D:depth>infinity</D:depth>"
  1374. "<D:timeout>Second-3600</D:timeout>"
  1375. "<D:locktoken><D:href>opaquelocktoken:nebs</D:href>"
  1376. "</D:locktoken></D:activelock></D:lockdiscovery></D:prop>";
  1377. (void)drain_body();
  1378. extra_hdrs = "Lock-Token: <opaquelocktoken:nebs>";
  1379. send_body(200, "OK", "text/xml; charset=\"utf-8\"",
  1380. lockbody, sizeof(lockbody) - 1);
  1381. }
  1382. /* ---- request dispatch ---- */
  1383. /* Serve one request. Returns 1 when the connection should stay open for the
  1384. * next request (HTTP keep-alive), 0 to close. */
  1385. static int serve(void)
  1386. {
  1387. int r = read_request();
  1388. status = 0;
  1389. extra_hdrs = 0;
  1390. if (r == -2)
  1391. return 0;
  1392. if (r != 0) {
  1393. send_error(r);
  1394. u_puts("websrv: bad request (");
  1395. u_putdec((unsigned int)r);
  1396. u_puts(")\n");
  1397. return 0;
  1398. }
  1399. load_mounts();
  1400. /* Methods with no body of their own: consume one if a client sent it,
  1401. * otherwise it would be parsed as the next request. */
  1402. if ((s_eq(rq.method, "GET") || s_eq(rq.method, "HEAD") ||
  1403. s_eq(rq.method, "OPTIONS") || s_eq(rq.method, "DELETE") ||
  1404. s_eq(rq.method, "MKCOL") || s_eq(rq.method, "MOVE")) &&
  1405. (rq.have_len || rq.chunked)) {
  1406. if (drain_body() != 0)
  1407. return 0;
  1408. }
  1409. if (s_eq(rq.method, "OPTIONS"))
  1410. do_options2();
  1411. else if (s_eq(rq.method, "GET"))
  1412. do_get(0);
  1413. else if (s_eq(rq.method, "HEAD"))
  1414. do_get(1);
  1415. else if (s_eq(rq.method, "PUT"))
  1416. do_put();
  1417. else if (s_eq(rq.method, "DELETE"))
  1418. do_delete();
  1419. else if (s_eq(rq.method, "MKCOL"))
  1420. do_mkcol();
  1421. else if (s_eq(rq.method, "PROPFIND"))
  1422. do_propfind();
  1423. else if (s_eq(rq.method, "PROPPATCH"))
  1424. do_proppatch();
  1425. else if (s_eq(rq.method, "MOVE"))
  1426. do_move();
  1427. else if (s_eq(rq.method, "LOCK"))
  1428. do_lock();
  1429. else if (s_eq(rq.method, "UNLOCK")) {
  1430. (void)drain_body();
  1431. send_empty(204);
  1432. } else {
  1433. (void)drain_body();
  1434. send_error(405);
  1435. }
  1436. if (status) {
  1437. u_puts("websrv: ");
  1438. u_puts(rq.method);
  1439. u_putc(' ');
  1440. u_puts(rq.path[0] ? rq.path : "/");
  1441. u_puts(" -> ");
  1442. u_putdec((unsigned int)status);
  1443. u_putc('\n');
  1444. }
  1445. if (!status || status >= 400)
  1446. return 0;
  1447. /* Unconsumed bytes (HTTP pipelining, or a body we did not read) would
  1448. * be lost on the next read: close rather than desynchronise. */
  1449. if (rlen > rpos)
  1450. return 0;
  1451. return rq.keep_alive ? 1 : 0;
  1452. }
  1453. static unsigned int parse_port(const char *arg)
  1454. {
  1455. unsigned int p = 0;
  1456. if (!arg)
  1457. return 0;
  1458. while (*arg) {
  1459. if (*arg < '0' || *arg > '9')
  1460. return 0;
  1461. p = p * 10 + (unsigned int)(*arg - '0');
  1462. if (p > 65535)
  1463. return 0;
  1464. arg++;
  1465. }
  1466. return p;
  1467. }
  1468. void _start(const char *arg)
  1469. {
  1470. unsigned int port = parse_port(arg);
  1471. unsigned char ip[4];
  1472. if (!port)
  1473. port = 8080;
  1474. if (u_syscall0(SYS_NET_ACQUIRE) != 0) {
  1475. u_puts("websrv: network busy (another command owns the NIC)\n");
  1476. u_exit(1);
  1477. }
  1478. u_syscall1(SYS_NET_GET_IP, (int)ip);
  1479. body = u_mem_alloc(BODY_MAX);
  1480. body_max = BODY_MAX;
  1481. if (!body) {
  1482. body = u_mem_alloc(BODY_FALLBACK);
  1483. body_max = BODY_FALLBACK;
  1484. }
  1485. if (!body) {
  1486. u_puts("websrv: no memory for the transfer buffer\n");
  1487. u_syscall0(SYS_NET_RELEASE);
  1488. u_exit(1);
  1489. }
  1490. load_mounts();
  1491. if (u_tcp_listen(port) != 0) {
  1492. u_puts("websrv: cannot listen\n");
  1493. u_syscall0(SYS_NET_RELEASE);
  1494. u_exit(1);
  1495. }
  1496. u_puts("websrv: transfer buffer ");
  1497. u_putdec(body_max / 1024u);
  1498. u_puts(" KB\n");
  1499. u_puts("websrv: serving http://");
  1500. u_put_ip(ip);
  1501. u_putc(':');
  1502. u_putdec(port);
  1503. u_puts("/ (WebDAV: dav://");
  1504. u_put_ip(ip);
  1505. u_putc(':');
  1506. u_putdec(port);
  1507. u_puts("/)\n");
  1508. for (;;) {
  1509. int r = u_tcp_accept();
  1510. if (r == 1) {
  1511. unsigned char peer[4];
  1512. unsigned int pport = 0;
  1513. if (u_tcp_peer(peer, &pport) == 0) {
  1514. u_puts("websrv: connection from ");
  1515. u_put_ip(peer);
  1516. u_putc(':');
  1517. u_putdec(pport);
  1518. u_putc('\n');
  1519. }
  1520. while (serve())
  1521. ;
  1522. u_tcp_srv_close();
  1523. continue;
  1524. }
  1525. if (r == -3) {
  1526. u_puts("websrv: netkexec requested, stopping\n");
  1527. break;
  1528. }
  1529. if (r == -2)
  1530. break;
  1531. u_sleep_ms(2);
  1532. }
  1533. u_tcp_srv_close();
  1534. u_syscall0(SYS_NET_RELEASE);
  1535. u_puts("websrv: stopped\n");
  1536. u_exit(0);
  1537. }