Parser.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. /*
  2. * Copyright (c) 2021, Kyle Pereira <hey@xylepereira.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/CharacterTypes.h>
  7. #include <LibIMAP/Parser.h>
  8. namespace IMAP {
  9. ParseStatus Parser::parse(ByteBuffer&& buffer, bool expecting_tag)
  10. {
  11. if (m_incomplete) {
  12. m_buffer += buffer;
  13. m_incomplete = false;
  14. } else {
  15. m_buffer = move(buffer);
  16. position = 0;
  17. m_response = SolidResponse();
  18. }
  19. if (try_consume("+")) {
  20. consume(" ");
  21. auto data = parse_while([](u8 x) { return x != '\r'; });
  22. consume("\r\n");
  23. return { true, { ContinueRequest { data } } };
  24. }
  25. while (try_consume("*")) {
  26. parse_untagged();
  27. }
  28. if (expecting_tag) {
  29. if (at_end()) {
  30. m_incomplete = true;
  31. return { true, {} };
  32. }
  33. parse_response_done();
  34. }
  35. if (m_parsing_failed) {
  36. return { false, {} };
  37. } else {
  38. return { true, { { move(m_response) } } };
  39. }
  40. }
  41. bool Parser::try_consume(StringView x)
  42. {
  43. size_t i = 0;
  44. auto previous_position = position;
  45. while (i < x.length() && !at_end() && to_ascii_lowercase(x[i]) == to_ascii_lowercase(m_buffer[position])) {
  46. i++;
  47. position++;
  48. }
  49. if (i != x.length()) {
  50. // We didn't match the full string.
  51. position = previous_position;
  52. return false;
  53. }
  54. return true;
  55. }
  56. void Parser::parse_response_done()
  57. {
  58. consume("A");
  59. auto tag = parse_number();
  60. consume(" ");
  61. ResponseStatus status = parse_status();
  62. consume(" ");
  63. m_response.m_tag = tag;
  64. m_response.m_status = status;
  65. StringBuilder response_data;
  66. while (!at_end() && m_buffer[position] != '\r') {
  67. response_data.append((char)m_buffer[position]);
  68. position += 1;
  69. }
  70. consume("\r\n");
  71. m_response.m_response_text = response_data.build();
  72. }
  73. void Parser::consume(StringView x)
  74. {
  75. if (!try_consume(x)) {
  76. dbgln("{} not matched at {}, buffer: {}", x, position, StringView(m_buffer.data(), m_buffer.size()));
  77. m_parsing_failed = true;
  78. }
  79. }
  80. Optional<unsigned> Parser::try_parse_number()
  81. {
  82. auto number_matched = 0;
  83. while (!at_end() && 0 <= m_buffer[position] - '0' && m_buffer[position] - '0' <= 9) {
  84. number_matched++;
  85. position++;
  86. }
  87. if (number_matched == 0)
  88. return {};
  89. auto number = StringView(m_buffer.data() + position - number_matched, number_matched);
  90. return number.to_uint();
  91. }
  92. unsigned Parser::parse_number()
  93. {
  94. auto number = try_parse_number();
  95. if (!number.has_value()) {
  96. m_parsing_failed = true;
  97. return -1;
  98. }
  99. return number.value();
  100. }
  101. void Parser::parse_untagged()
  102. {
  103. consume(" ");
  104. // Certain messages begin with a number like:
  105. // * 15 EXISTS
  106. auto number = try_parse_number();
  107. if (number.has_value()) {
  108. consume(" ");
  109. auto data_type = parse_atom().to_string();
  110. if (data_type.matches("EXISTS")) {
  111. m_response.data().set_exists(number.value());
  112. consume("\r\n");
  113. } else if (data_type.matches("RECENT")) {
  114. m_response.data().set_recent(number.value());
  115. consume("\r\n");
  116. } else if (data_type.matches("FETCH")) {
  117. auto fetch_response = parse_fetch_response();
  118. m_response.data().add_fetch_response(number.value(), move(fetch_response));
  119. } else if (data_type.matches("EXPUNGE")) {
  120. m_response.data().add_expunged(number.value());
  121. consume("\r\n");
  122. }
  123. return;
  124. }
  125. if (try_consume("CAPABILITY")) {
  126. parse_capability_response();
  127. } else if (try_consume("LIST")) {
  128. auto item = parse_list_item();
  129. m_response.data().add_list_item(move(item));
  130. } else if (try_consume("LSUB")) {
  131. auto item = parse_list_item();
  132. m_response.data().add_lsub_item(move(item));
  133. } else if (try_consume("FLAGS")) {
  134. consume(" ");
  135. auto flags = parse_list(+[](StringView x) { return String(x); });
  136. m_response.data().set_flags(move(flags));
  137. consume("\r\n");
  138. } else if (try_consume("OK")) {
  139. consume(" ");
  140. if (try_consume("[")) {
  141. auto actual_type = parse_atom();
  142. consume(" ");
  143. if (actual_type.matches("UIDNEXT")) {
  144. auto n = parse_number();
  145. m_response.data().set_uid_next(n);
  146. } else if (actual_type.matches("UIDVALIDITY")) {
  147. auto n = parse_number();
  148. m_response.data().set_uid_validity(n);
  149. } else if (actual_type.matches("UNSEEN")) {
  150. auto n = parse_number();
  151. m_response.data().set_unseen(n);
  152. } else if (actual_type.matches("PERMANENTFLAGS")) {
  153. auto flags = parse_list(+[](StringView x) { return String(x); });
  154. m_response.data().set_permanent_flags(move(flags));
  155. } else {
  156. dbgln("Unknown: {}", actual_type);
  157. parse_while([](u8 x) { return x != ']'; });
  158. }
  159. consume("]");
  160. parse_while([](u8 x) { return x != '\r'; });
  161. consume("\r\n");
  162. } else {
  163. parse_while([](u8 x) { return x != '\r'; });
  164. consume("\r\n");
  165. }
  166. } else if (try_consume("SEARCH")) {
  167. Vector<unsigned> ids;
  168. while (!try_consume("\r\n")) {
  169. consume(" ");
  170. auto id = parse_number();
  171. ids.append(id);
  172. }
  173. m_response.data().set_search_results(move(ids));
  174. } else if (try_consume("BYE")) {
  175. auto message = parse_while([](u8 x) { return x != '\r'; });
  176. consume("\r\n");
  177. m_response.data().set_bye(message.is_empty() ? Optional<String>() : Optional<String>(message));
  178. } else if (try_consume("STATUS")) {
  179. consume(" ");
  180. auto mailbox = parse_astring();
  181. consume(" (");
  182. auto status_item = StatusItem();
  183. status_item.set_mailbox(mailbox);
  184. while (!try_consume(")")) {
  185. auto status_att = parse_atom();
  186. consume(" ");
  187. auto value = parse_number();
  188. auto type = StatusItemType::Recent;
  189. if (status_att.matches("MESSAGES")) {
  190. type = StatusItemType::Messages;
  191. } else if (status_att.matches("UNSEEN")) {
  192. type = StatusItemType::Unseen;
  193. } else if (status_att.matches("UIDNEXT")) {
  194. type = StatusItemType::UIDNext;
  195. } else if (status_att.matches("UIDVALIDITY")) {
  196. type = StatusItemType::UIDValidity;
  197. } else if (status_att.matches("RECENT")) {
  198. type = StatusItemType::Recent;
  199. } else {
  200. dbgln("Unmatched status attribute: {}", status_att);
  201. m_parsing_failed = true;
  202. }
  203. status_item.set(type, value);
  204. if (!at_end() && m_buffer[position] != ')')
  205. consume(" ");
  206. }
  207. m_response.data().set_status(move(status_item));
  208. try_consume(" "); // Not in the spec but the Outlook server sends a space for some reason.
  209. consume("\r\n");
  210. } else {
  211. auto x = parse_while([](u8 x) { return x != '\r'; });
  212. consume("\r\n");
  213. dbgln("ignored {}", x);
  214. }
  215. }
  216. StringView Parser::parse_quoted_string()
  217. {
  218. auto str = parse_while([](u8 x) { return x != '"'; });
  219. consume("\"");
  220. return str;
  221. }
  222. StringView Parser::parse_string()
  223. {
  224. if (try_consume("\"")) {
  225. return parse_quoted_string();
  226. } else {
  227. return parse_literal_string();
  228. }
  229. }
  230. Optional<StringView> Parser::parse_nstring()
  231. {
  232. if (try_consume("NIL"))
  233. return {};
  234. else
  235. return { parse_string() };
  236. }
  237. FetchResponseData Parser::parse_fetch_response()
  238. {
  239. consume(" (");
  240. auto fetch_response = FetchResponseData();
  241. while (!try_consume(")")) {
  242. auto data_item = parse_fetch_data_item();
  243. switch (data_item.type) {
  244. case FetchCommand::DataItemType::BodyStructure: {
  245. consume(" (");
  246. auto structure = parse_body_structure();
  247. fetch_response.set_body_structure(move(structure));
  248. break;
  249. }
  250. case FetchCommand::DataItemType::Envelope: {
  251. fetch_response.set_envelope(parse_envelope());
  252. break;
  253. }
  254. case FetchCommand::DataItemType::Flags: {
  255. consume(" ");
  256. auto flags = parse_list(+[](StringView x) { return String(x); });
  257. fetch_response.set_flags(move(flags));
  258. break;
  259. }
  260. case FetchCommand::DataItemType::InternalDate: {
  261. consume(" \"");
  262. auto date_view = parse_while([](u8 x) { return x != '"'; });
  263. consume("\"");
  264. auto date = Core::DateTime::parse("%d-%b-%Y %H:%M:%S %z", date_view).value();
  265. fetch_response.set_internal_date(date);
  266. break;
  267. }
  268. case FetchCommand::DataItemType::UID: {
  269. consume(" ");
  270. fetch_response.set_uid(parse_number());
  271. break;
  272. }
  273. case FetchCommand::DataItemType::PeekBody:
  274. // Spec doesn't allow for this in a response.
  275. m_parsing_failed = true;
  276. break;
  277. case FetchCommand::DataItemType::BodySection: {
  278. auto body = parse_nstring();
  279. fetch_response.add_body_data(move(data_item), body.has_value() ? body.release_value() : Optional<String>());
  280. break;
  281. }
  282. }
  283. if (!at_end() && m_buffer[position] != ')')
  284. consume(" ");
  285. }
  286. consume("\r\n");
  287. return fetch_response;
  288. }
  289. Envelope Parser::parse_envelope()
  290. {
  291. consume(" (");
  292. auto date = parse_nstring();
  293. consume(" ");
  294. auto subject = parse_nstring();
  295. consume(" ");
  296. auto from = parse_address_list();
  297. consume(" ");
  298. auto sender = parse_address_list();
  299. consume(" ");
  300. auto reply_to = parse_address_list();
  301. consume(" ");
  302. auto to = parse_address_list();
  303. consume(" ");
  304. auto cc = parse_address_list();
  305. consume(" ");
  306. auto bcc = parse_address_list();
  307. consume(" ");
  308. auto in_reply_to = parse_nstring();
  309. consume(" ");
  310. auto message_id = parse_nstring();
  311. consume(")");
  312. Envelope envelope = {
  313. date.has_value() ? AK::Optional<String>(date.value()) : AK::Optional<String>(),
  314. subject.has_value() ? AK::Optional<String>(subject.value()) : AK::Optional<String>(),
  315. from,
  316. sender,
  317. reply_to,
  318. to,
  319. cc,
  320. bcc,
  321. in_reply_to.has_value() ? AK::Optional<String>(in_reply_to.value()) : AK::Optional<String>(),
  322. message_id.has_value() ? AK::Optional<String>(message_id.value()) : AK::Optional<String>(),
  323. };
  324. return envelope;
  325. }
  326. BodyStructure Parser::parse_body_structure()
  327. {
  328. if (!at_end() && m_buffer[position] == '(') {
  329. auto data = MultiPartBodyStructureData();
  330. while (try_consume("(")) {
  331. auto child = parse_body_structure();
  332. data.bodies.append(make<BodyStructure>(move(child)));
  333. }
  334. consume(" ");
  335. data.media_type = parse_string();
  336. if (!try_consume(")")) {
  337. consume(" ");
  338. data.params = try_consume("NIL") ? Optional<HashMap<String, String>>() : parse_body_fields_params();
  339. if (!try_consume(")")) {
  340. consume(" ");
  341. if (!try_consume("NIL")) {
  342. data.disposition = { parse_disposition() };
  343. }
  344. if (!try_consume(")")) {
  345. consume(" ");
  346. if (!try_consume("NIL")) {
  347. data.langs = { parse_langs() };
  348. }
  349. if (!try_consume(")")) {
  350. consume(" ");
  351. data.location = try_consume("NIL") ? Optional<String>() : Optional<String>(parse_string());
  352. if (!try_consume(")")) {
  353. consume(" ");
  354. Vector<BodyExtension> extensions;
  355. while (!try_consume(")")) {
  356. extensions.append(parse_body_extension());
  357. try_consume(" ");
  358. }
  359. data.extensions = { move(extensions) };
  360. }
  361. }
  362. }
  363. }
  364. }
  365. return BodyStructure(move(data));
  366. } else {
  367. return parse_one_part_body();
  368. }
  369. }
  370. BodyStructure Parser::parse_one_part_body()
  371. {
  372. auto type = parse_string();
  373. consume(" ");
  374. auto subtype = parse_string();
  375. consume(" ");
  376. if (type.equals_ignoring_case("TEXT")) {
  377. // body-type-text
  378. auto params = parse_body_fields_params();
  379. consume(" ");
  380. auto id = parse_nstring();
  381. consume(" ");
  382. auto description = parse_nstring();
  383. consume(" ");
  384. auto encoding = parse_string();
  385. consume(" ");
  386. auto num_octets = parse_number();
  387. consume(" ");
  388. auto num_lines = parse_number();
  389. auto data = BodyStructureData {
  390. type,
  391. subtype,
  392. id.has_value() ? Optional<String>(id.value()) : Optional<String>(),
  393. description.has_value() ? Optional<String>(description.value()) : Optional<String>(),
  394. encoding,
  395. params,
  396. num_octets,
  397. num_lines,
  398. {}
  399. };
  400. if (!try_consume(")")) {
  401. consume(" ");
  402. auto md5 = parse_nstring();
  403. if (md5.has_value())
  404. data.md5 = { md5.value() };
  405. if (!try_consume(")")) {
  406. consume(" ");
  407. if (!try_consume("NIL")) {
  408. auto disposition = parse_disposition();
  409. data.disposition = { disposition };
  410. }
  411. if (!try_consume(")")) {
  412. consume(" ");
  413. if (!try_consume("NIL")) {
  414. data.langs = { parse_langs() };
  415. }
  416. if (!try_consume(")")) {
  417. consume(" ");
  418. auto location = parse_nstring();
  419. if (location.has_value())
  420. data.location = { location.value() };
  421. Vector<BodyExtension> extensions;
  422. while (!try_consume(")")) {
  423. extensions.append(parse_body_extension());
  424. try_consume(" ");
  425. }
  426. data.extensions = { move(extensions) };
  427. }
  428. }
  429. }
  430. }
  431. return BodyStructure(move(data));
  432. } else if (type.equals_ignoring_case("MESSAGE") && subtype.equals_ignoring_case("RFC822")) {
  433. // body-type-message
  434. auto params = parse_body_fields_params();
  435. consume(" ");
  436. auto id = parse_nstring();
  437. consume(" ");
  438. auto description = parse_nstring();
  439. consume(" ");
  440. auto encoding = parse_string();
  441. consume(" ");
  442. auto num_octets = parse_number();
  443. consume(" ");
  444. auto envelope = parse_envelope();
  445. BodyStructureData data {
  446. type,
  447. subtype,
  448. id.has_value() ? Optional<String>(id.value()) : Optional<String>(),
  449. description.has_value() ? Optional<String>(description.value()) : Optional<String>(),
  450. encoding,
  451. params,
  452. num_octets,
  453. 0,
  454. envelope
  455. };
  456. return BodyStructure(move(data));
  457. } else {
  458. // body-type-basic
  459. auto params = parse_body_fields_params();
  460. consume(" ");
  461. auto id = parse_nstring();
  462. consume(" ");
  463. auto description = parse_nstring();
  464. consume(" ");
  465. auto encoding = parse_string();
  466. consume(" ");
  467. auto num_octets = parse_number();
  468. consume(" ");
  469. BodyStructureData data {
  470. type,
  471. subtype,
  472. id.has_value() ? Optional<String>(id.value()) : Optional<String>(),
  473. description.has_value() ? Optional<String>(description.value()) : Optional<String>(),
  474. encoding,
  475. params,
  476. num_octets,
  477. 0,
  478. {}
  479. };
  480. return BodyStructure(move(data));
  481. }
  482. }
  483. Vector<String> Parser::parse_langs()
  484. {
  485. AK::Vector<String> langs;
  486. if (!try_consume("(")) {
  487. langs.append(parse_string());
  488. } else {
  489. while (!try_consume(")")) {
  490. langs.append(parse_string());
  491. try_consume(" ");
  492. }
  493. }
  494. return langs;
  495. }
  496. Tuple<String, HashMap<String, String>> Parser::parse_disposition()
  497. {
  498. auto disposition_type = parse_string();
  499. consume(" ");
  500. auto disposition_vals = parse_body_fields_params();
  501. consume(")");
  502. return { move(disposition_type), move(disposition_vals) };
  503. }
  504. StringView Parser::parse_literal_string()
  505. {
  506. consume("{");
  507. auto num_bytes = parse_number();
  508. consume("}\r\n");
  509. if (m_buffer.size() < position + num_bytes) {
  510. m_parsing_failed = true;
  511. return "";
  512. }
  513. position += num_bytes;
  514. return StringView(m_buffer.data() + position - num_bytes, num_bytes);
  515. }
  516. ListItem Parser::parse_list_item()
  517. {
  518. consume(" ");
  519. auto flags_vec = parse_list(parse_mailbox_flag);
  520. unsigned flags = 0;
  521. for (auto flag : flags_vec) {
  522. flags |= static_cast<unsigned>(flag);
  523. }
  524. consume(" \"");
  525. auto reference = parse_while([](u8 x) { return x != '"'; });
  526. consume("\" ");
  527. auto mailbox = parse_astring();
  528. consume("\r\n");
  529. return ListItem { flags, String(reference), String(mailbox) };
  530. }
  531. void Parser::parse_capability_response()
  532. {
  533. auto capability = AK::Vector<String>();
  534. while (!try_consume("\r\n")) {
  535. consume(" ");
  536. auto x = String(parse_atom());
  537. capability.append(x);
  538. }
  539. m_response.data().add_capabilities(move(capability));
  540. }
  541. StringView Parser::parse_atom()
  542. {
  543. auto is_non_atom_char = [](u8 x) {
  544. auto non_atom_chars = { '(', ')', '{', ' ', '%', '*', '"', '\\', ']' };
  545. return AK::find(non_atom_chars.begin(), non_atom_chars.end(), x) != non_atom_chars.end();
  546. };
  547. auto start = position;
  548. auto count = 0;
  549. while (!at_end() && !is_ascii_control(m_buffer[position]) && !is_non_atom_char(m_buffer[position])) {
  550. count++;
  551. position++;
  552. }
  553. return StringView(m_buffer.data() + start, count);
  554. }
  555. ResponseStatus Parser::parse_status()
  556. {
  557. auto atom = parse_atom();
  558. if (atom.matches("OK")) {
  559. return ResponseStatus::OK;
  560. } else if (atom.matches("BAD")) {
  561. return ResponseStatus::Bad;
  562. } else if (atom.matches("NO")) {
  563. return ResponseStatus::No;
  564. }
  565. m_parsing_failed = true;
  566. return ResponseStatus::Bad;
  567. }
  568. template<typename T>
  569. Vector<T> Parser::parse_list(T converter(StringView))
  570. {
  571. consume("(");
  572. Vector<T> x;
  573. bool first = true;
  574. while (!try_consume(")")) {
  575. if (!first)
  576. consume(" ");
  577. auto item = parse_while([](u8 x) {
  578. return x != ' ' && x != ')';
  579. });
  580. x.append(converter(item));
  581. first = false;
  582. }
  583. return x;
  584. }
  585. MailboxFlag Parser::parse_mailbox_flag(StringView s)
  586. {
  587. if (s.matches("\\All"))
  588. return MailboxFlag::All;
  589. if (s.matches("\\Drafts"))
  590. return MailboxFlag::Drafts;
  591. if (s.matches("\\Flagged"))
  592. return MailboxFlag::Flagged;
  593. if (s.matches("\\HasChildren"))
  594. return MailboxFlag::HasChildren;
  595. if (s.matches("\\HasNoChildren"))
  596. return MailboxFlag::HasNoChildren;
  597. if (s.matches("\\Important"))
  598. return MailboxFlag::Important;
  599. if (s.matches("\\Junk"))
  600. return MailboxFlag::Junk;
  601. if (s.matches("\\Marked"))
  602. return MailboxFlag::Marked;
  603. if (s.matches("\\Noinferiors"))
  604. return MailboxFlag::NoInferiors;
  605. if (s.matches("\\Noselect"))
  606. return MailboxFlag::NoSelect;
  607. if (s.matches("\\Sent"))
  608. return MailboxFlag::Sent;
  609. if (s.matches("\\Trash"))
  610. return MailboxFlag::Trash;
  611. if (s.matches("\\Unmarked"))
  612. return MailboxFlag::Unmarked;
  613. dbgln("Unrecognized mailbox flag {}", s);
  614. return MailboxFlag::Unknown;
  615. }
  616. StringView Parser::parse_while(Function<bool(u8)> should_consume)
  617. {
  618. int chars = 0;
  619. while (!at_end() && should_consume(m_buffer[position])) {
  620. position++;
  621. chars++;
  622. }
  623. return StringView(m_buffer.data() + position - chars, chars);
  624. }
  625. FetchCommand::DataItem Parser::parse_fetch_data_item()
  626. {
  627. auto msg_attr = parse_while([](u8 x) { return is_ascii_alpha(x) != 0; });
  628. if (msg_attr.equals_ignoring_case("BODY") && try_consume("[")) {
  629. auto data_item = FetchCommand::DataItem {
  630. .type = FetchCommand::DataItemType::BodySection,
  631. .section = { {} }
  632. };
  633. auto section_type = parse_while([](u8 x) { return x != ']' && x != ' '; });
  634. if (section_type.equals_ignoring_case("HEADER.FIELDS")) {
  635. data_item.section->type = FetchCommand::DataItem::SectionType::HeaderFields;
  636. data_item.section->headers = Vector<String>();
  637. consume(" ");
  638. auto headers = parse_list(+[](StringView x) { return x; });
  639. for (auto& header : headers) {
  640. data_item.section->headers->append(header);
  641. }
  642. consume("]");
  643. } else if (section_type.equals_ignoring_case("HEADER.FIELDS.NOT")) {
  644. data_item.section->type = FetchCommand::DataItem::SectionType::HeaderFieldsNot;
  645. data_item.section->headers = Vector<String>();
  646. consume(" (");
  647. auto headers = parse_list(+[](StringView x) { return x; });
  648. for (auto& header : headers) {
  649. data_item.section->headers->append(header);
  650. }
  651. consume("]");
  652. } else if (is_ascii_digit(section_type[0])) {
  653. data_item.section->type = FetchCommand::DataItem::SectionType::Parts;
  654. data_item.section->parts = Vector<unsigned>();
  655. while (!try_consume("]")) {
  656. auto num = try_parse_number();
  657. if (num.has_value()) {
  658. data_item.section->parts->append(num.value());
  659. continue;
  660. }
  661. auto atom = parse_atom();
  662. if (atom.equals_ignoring_case("MIME")) {
  663. data_item.section->ends_with_mime = true;
  664. continue;
  665. }
  666. }
  667. } else if (section_type.equals_ignoring_case("TEXT")) {
  668. data_item.section->type = FetchCommand::DataItem::SectionType::Text;
  669. } else if (section_type.equals_ignoring_case("HEADER")) {
  670. data_item.section->type = FetchCommand::DataItem::SectionType::Header;
  671. } else {
  672. dbgln("Unmatched section type {}", section_type);
  673. m_parsing_failed = true;
  674. }
  675. if (try_consume("<")) {
  676. auto start = parse_number();
  677. data_item.partial_fetch = true;
  678. data_item.start = (int)start;
  679. consume(">");
  680. }
  681. try_consume(" ");
  682. return data_item;
  683. } else if (msg_attr.equals_ignoring_case("FLAGS")) {
  684. return FetchCommand::DataItem {
  685. .type = FetchCommand::DataItemType::Flags
  686. };
  687. } else if (msg_attr.equals_ignoring_case("UID")) {
  688. return FetchCommand::DataItem {
  689. .type = FetchCommand::DataItemType::UID
  690. };
  691. } else if (msg_attr.equals_ignoring_case("INTERNALDATE")) {
  692. return FetchCommand::DataItem {
  693. .type = FetchCommand::DataItemType::InternalDate
  694. };
  695. } else if (msg_attr.equals_ignoring_case("ENVELOPE")) {
  696. return FetchCommand::DataItem {
  697. .type = FetchCommand::DataItemType::Envelope
  698. };
  699. } else if (msg_attr.equals_ignoring_case("BODY") || msg_attr.equals_ignoring_case("BODYSTRUCTURE")) {
  700. return FetchCommand::DataItem {
  701. .type = FetchCommand::DataItemType::BodyStructure
  702. };
  703. } else {
  704. dbgln("msg_attr not matched: {}", msg_attr);
  705. m_parsing_failed = true;
  706. return FetchCommand::DataItem {};
  707. }
  708. }
  709. Optional<Vector<Address>> Parser::parse_address_list()
  710. {
  711. if (try_consume("NIL"))
  712. return {};
  713. auto addresses = Vector<Address>();
  714. consume("(");
  715. while (!try_consume(")")) {
  716. addresses.append(parse_address());
  717. if (!at_end() && m_buffer[position] != ')')
  718. consume(" ");
  719. }
  720. return { addresses };
  721. }
  722. Address Parser::parse_address()
  723. {
  724. consume("(");
  725. auto address = Address();
  726. // I hate this so much. Why is there no Optional.map??
  727. auto name = parse_nstring();
  728. address.name = name.has_value() ? Optional<String>(name.value()) : Optional<String>();
  729. consume(" ");
  730. auto source_route = parse_nstring();
  731. address.source_route = source_route.has_value() ? Optional<String>(source_route.value()) : Optional<String>();
  732. consume(" ");
  733. auto mailbox = parse_nstring();
  734. address.mailbox = mailbox.has_value() ? Optional<String>(mailbox.value()) : Optional<String>();
  735. consume(" ");
  736. auto host = parse_nstring();
  737. address.host = host.has_value() ? Optional<String>(host.value()) : Optional<String>();
  738. consume(")");
  739. return address;
  740. }
  741. StringView Parser::parse_astring()
  742. {
  743. if (!at_end() && (m_buffer[position] == '{' || m_buffer[position] == '"'))
  744. return parse_string();
  745. else
  746. return parse_atom();
  747. }
  748. HashMap<String, String> Parser::parse_body_fields_params()
  749. {
  750. if (try_consume("NIL"))
  751. return {};
  752. HashMap<String, String> fields;
  753. consume("(");
  754. while (!try_consume(")")) {
  755. auto key = parse_string();
  756. consume(" ");
  757. auto value = parse_string();
  758. fields.set(key, value);
  759. try_consume(" ");
  760. }
  761. return fields;
  762. }
  763. BodyExtension Parser::parse_body_extension()
  764. {
  765. if (try_consume("NIL")) {
  766. return BodyExtension { Optional<String> {} };
  767. } else if (try_consume("(")) {
  768. Vector<OwnPtr<BodyExtension>> extensions;
  769. while (!try_consume(")")) {
  770. extensions.append(make<BodyExtension>(parse_body_extension()));
  771. try_consume(" ");
  772. }
  773. return BodyExtension { move(extensions) };
  774. } else if (!at_end() && (m_buffer[position] == '"' || m_buffer[position] == '{')) {
  775. return BodyExtension { { parse_string() } };
  776. } else {
  777. return BodyExtension { parse_number() };
  778. }
  779. }
  780. }