ucmd_websrv.c 35 KB

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