You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

html.cxx 55KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318
  1. /*-
  2. * Copyright 2021 Vsevolod Stakhov
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "config.h"
  17. #include "util.h"
  18. #include "message.h"
  19. #include "html.h"
  20. #include "html_tags.h"
  21. #include "html_block.hxx"
  22. #include "html.hxx"
  23. #include "libserver/css/css_value.hxx"
  24. #include "libserver/css/css.hxx"
  25. #include "url.h"
  26. #include "contrib/libucl/khash.h"
  27. #include "libmime/images.h"
  28. #include "libutil/cxx/utf8_util.h"
  29. #include "html_tag_defs.hxx"
  30. #include "html_entities.hxx"
  31. #include "html_tag.hxx"
  32. #include "html_url.hxx"
  33. #include <frozen/unordered_map.h>
  34. #include <frozen/string.h>
  35. #include <fmt/core.h>
  36. #include <unicode/uversion.h>
  37. namespace rspamd::html {
  38. static const guint max_tags = 8192; /* Ignore tags if this maximum is reached */
  39. static const html_tags_storage html_tags_defs;
  40. auto html_components_map = frozen::make_unordered_map<frozen::string, html_component_type>(
  41. {
  42. {"name", html_component_type::RSPAMD_HTML_COMPONENT_NAME},
  43. {"href", html_component_type::RSPAMD_HTML_COMPONENT_HREF},
  44. {"src", html_component_type::RSPAMD_HTML_COMPONENT_HREF},
  45. {"action", html_component_type::RSPAMD_HTML_COMPONENT_HREF},
  46. {"color", html_component_type::RSPAMD_HTML_COMPONENT_COLOR},
  47. {"bgcolor", html_component_type::RSPAMD_HTML_COMPONENT_BGCOLOR},
  48. {"style", html_component_type::RSPAMD_HTML_COMPONENT_STYLE},
  49. {"class", html_component_type::RSPAMD_HTML_COMPONENT_CLASS},
  50. {"width", html_component_type::RSPAMD_HTML_COMPONENT_WIDTH},
  51. {"height", html_component_type::RSPAMD_HTML_COMPONENT_HEIGHT},
  52. {"size", html_component_type::RSPAMD_HTML_COMPONENT_SIZE},
  53. {"rel", html_component_type::RSPAMD_HTML_COMPONENT_REL},
  54. {"alt", html_component_type::RSPAMD_HTML_COMPONENT_ALT},
  55. {"id", html_component_type::RSPAMD_HTML_COMPONENT_ID},
  56. {"hidden", html_component_type::RSPAMD_HTML_COMPONENT_HIDDEN},
  57. });
  58. #define msg_debug_html(...) rspamd_conditional_debug_fast (NULL, NULL, \
  59. rspamd_html_log_id, "html", pool->tag.uid, \
  60. __FUNCTION__, \
  61. __VA_ARGS__)
  62. INIT_LOG_MODULE(html)
  63. /*
  64. * This function is expected to be called on a closing tag to fill up all tags
  65. * and return the current parent (meaning unclosed) tag
  66. */
  67. static auto
  68. html_check_balance(struct html_content *hc,
  69. struct html_tag *tag,
  70. goffset tag_start_offset,
  71. goffset tag_end_offset) -> html_tag *
  72. {
  73. /* As agreed, the closing tag has the last opening at the parent ptr */
  74. auto *opening_tag = tag->parent;
  75. auto calculate_content_length = [tag_start_offset, tag_end_offset](html_tag *t) {
  76. auto opening_content_offset = t->content_offset;
  77. if (t->flags & (CM_EMPTY)) {
  78. /* Attach closing tag just at the opening tag */
  79. t->closing.start = t->tag_start;
  80. t->closing.end = t->content_offset;
  81. }
  82. else {
  83. if (opening_content_offset <= tag_start_offset) {
  84. t->closing.start = tag_start_offset;
  85. t->closing.end = tag_end_offset;
  86. }
  87. else {
  88. t->closing.start = t->content_offset;
  89. t->closing.end = tag_end_offset;
  90. }
  91. }
  92. };
  93. auto balance_tag = [&]() -> html_tag * {
  94. auto it = tag->parent;
  95. auto found_pair = false;
  96. for (; it != nullptr; it = it->parent) {
  97. if (it->id == tag->id && !(it->flags & FL_CLOSED)) {
  98. found_pair = true;
  99. break;
  100. }
  101. }
  102. /*
  103. * If we have found a closing pair, then we need to close all tags and
  104. * return the top-most tag
  105. */
  106. if (found_pair) {
  107. for (it = tag->parent; it != nullptr; it = it->parent) {
  108. it->flags |= FL_CLOSED;
  109. /* Insert a virtual closing tag for all tags that are not closed */
  110. calculate_content_length(it);
  111. if (it->id == tag->id && !(it->flags & FL_CLOSED)) {
  112. break;
  113. }
  114. }
  115. return it;
  116. }
  117. else {
  118. /*
  119. * We have not found a pair, so this closing tag is bogus and should
  120. * be ignored completely.
  121. * Unfortunately, it also means that we need to insert another tag,
  122. * as the current closing tag is unusable for that purposes.
  123. *
  124. * We assume that callee will recognise that and reconstruct the
  125. * tag at the tag_end_closing state, so we return nullptr...
  126. */
  127. }
  128. /* Tag must be ignored and reconstructed */
  129. return nullptr;
  130. };
  131. if (opening_tag) {
  132. if (opening_tag->id == tag->id) {
  133. opening_tag->flags |= FL_CLOSED;
  134. calculate_content_length(opening_tag);
  135. /* All good */
  136. return opening_tag->parent;
  137. }
  138. else {
  139. return balance_tag();
  140. }
  141. }
  142. else {
  143. /*
  144. * We have no opening tag
  145. * There are two possibilities:
  146. *
  147. * 1) We have some block tag in hc->all_tags;
  148. * 2) We have no tags
  149. */
  150. if (hc->all_tags.empty()) {
  151. hc->all_tags.push_back(std::make_unique<html_tag>());
  152. auto *vtag = hc->all_tags.back().get();
  153. vtag->id = Tag_HTML;
  154. vtag->flags = FL_VIRTUAL;
  155. vtag->tag_start = 0;
  156. vtag->content_offset = 0;
  157. calculate_content_length(vtag);
  158. if (!hc->root_tag) {
  159. hc->root_tag = vtag;
  160. }
  161. else {
  162. vtag->parent = hc->root_tag;
  163. }
  164. tag->parent = vtag;
  165. /* Recursively call with a virtual <html> tag inserted */
  166. return html_check_balance(hc, tag, tag_start_offset, tag_end_offset);
  167. }
  168. }
  169. return nullptr;
  170. }
  171. auto
  172. html_component_from_string(const std::string_view &st) -> std::optional<html_component_type>
  173. {
  174. auto known_component_it = html_components_map.find(st);
  175. if (known_component_it != html_components_map.end()) {
  176. return known_component_it->second;
  177. }
  178. else {
  179. return std::nullopt;
  180. }
  181. }
  182. struct tag_content_parser_state {
  183. int cur_state = 0;
  184. std::string buf;
  185. std::optional<html_component_type> cur_component;
  186. void reset()
  187. {
  188. cur_state = 0;
  189. buf.clear();
  190. cur_component = std::nullopt;
  191. }
  192. };
  193. static inline void
  194. html_parse_tag_content(rspamd_mempool_t *pool,
  195. struct html_content *hc,
  196. struct html_tag *tag,
  197. const char *in,
  198. struct tag_content_parser_state &parser_env)
  199. {
  200. enum tag_parser_state {
  201. parse_start = 0,
  202. parse_name,
  203. parse_attr_name,
  204. parse_equal,
  205. parse_start_dquote,
  206. parse_dqvalue,
  207. parse_end_dquote,
  208. parse_start_squote,
  209. parse_sqvalue,
  210. parse_end_squote,
  211. parse_value,
  212. spaces_before_eq,
  213. spaces_after_eq,
  214. spaces_after_param,
  215. ignore_bad_tag,
  216. tag_end,
  217. slash_after_value,
  218. slash_in_unqouted_value,
  219. } state;
  220. state = static_cast<enum tag_parser_state>(parser_env.cur_state);
  221. /*
  222. * Stores tag component if it doesn't exist, performing copy of the
  223. * value + decoding of the entities
  224. * Parser env is set to clear the current html attribute fields (saved_p and
  225. * cur_component)
  226. */
  227. auto store_component_value = [&]() -> void {
  228. if (parser_env.cur_component) {
  229. if (parser_env.buf.empty()) {
  230. tag->components.emplace_back(parser_env.cur_component.value(),
  231. std::string_view{});
  232. }
  233. else {
  234. /* We need to copy buf to a persistent storage */
  235. auto *s = rspamd_mempool_alloc_buffer(pool, parser_env.buf.size());
  236. if (parser_env.cur_component.value() == html_component_type::RSPAMD_HTML_COMPONENT_ID ||
  237. parser_env.cur_component.value() == html_component_type::RSPAMD_HTML_COMPONENT_CLASS) {
  238. /* Lowercase */
  239. rspamd_str_copy_lc(parser_env.buf.data(), s, parser_env.buf.size());
  240. }
  241. else {
  242. memcpy(s, parser_env.buf.data(), parser_env.buf.size());
  243. }
  244. auto sz = rspamd_html_decode_entitles_inplace(s, parser_env.buf.size());
  245. tag->components.emplace_back(parser_env.cur_component.value(),
  246. std::string_view{s, sz});
  247. }
  248. }
  249. parser_env.buf.clear();
  250. parser_env.cur_component = std::nullopt;
  251. };
  252. auto store_component_name = [&]() -> bool {
  253. decode_html_entitles_inplace(parser_env.buf);
  254. auto known_component_it = html_components_map.find(std::string_view{parser_env.buf});
  255. parser_env.buf.clear();
  256. if (known_component_it != html_components_map.end()) {
  257. parser_env.cur_component = known_component_it->second;
  258. return true;
  259. }
  260. else {
  261. parser_env.cur_component = std::nullopt;
  262. }
  263. return false;
  264. };
  265. auto store_value_character = [&](bool lc) -> void {
  266. auto c = lc ? g_ascii_tolower(*in) : *in;
  267. if (c == '\0') {
  268. /* Replace with u0FFD */
  269. parser_env.buf.append(u8"\uFFFD");
  270. }
  271. else {
  272. parser_env.buf.push_back(c);
  273. }
  274. };
  275. switch (state) {
  276. case parse_start:
  277. if (!g_ascii_isalpha (*in) && !g_ascii_isspace (*in)) {
  278. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  279. state = ignore_bad_tag;
  280. tag->id = N_TAGS;
  281. tag->flags |= FL_BROKEN;
  282. }
  283. else if (g_ascii_isalpha (*in)) {
  284. state = parse_name;
  285. store_value_character(true);
  286. }
  287. break;
  288. case parse_name:
  289. if ((g_ascii_isspace (*in) || *in == '>' || *in == '/')) {
  290. if (*in == '/') {
  291. tag->flags |= FL_CLOSED;
  292. }
  293. if (parser_env.buf.empty()) {
  294. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  295. tag->id = N_TAGS;
  296. tag->flags |= FL_BROKEN;
  297. state = ignore_bad_tag;
  298. }
  299. else {
  300. decode_html_entitles_inplace(parser_env.buf);
  301. const auto *tag_def = rspamd::html::html_tags_defs.by_name(parser_env.buf);
  302. if (tag_def == nullptr) {
  303. hc->flags |= RSPAMD_HTML_FLAG_UNKNOWN_ELEMENTS;
  304. /* Assign -hash to match closing tag if needed */
  305. auto nhash = static_cast<std::int32_t>(std::hash<std::string>{}(parser_env.buf));
  306. /* Always negative */
  307. tag->id = static_cast<tag_id_t>(nhash | G_MININT32);
  308. }
  309. else {
  310. tag->id = tag_def->id;
  311. tag->flags = tag_def->flags;
  312. }
  313. parser_env.buf.clear();
  314. state = spaces_after_param;
  315. }
  316. }
  317. else {
  318. store_value_character(true);
  319. }
  320. break;
  321. case parse_attr_name:
  322. if (*in == '=') {
  323. if (!parser_env.buf.empty()) {
  324. store_component_name();
  325. }
  326. state = parse_equal;
  327. }
  328. else if (g_ascii_isspace(*in)) {
  329. store_component_name();
  330. state = spaces_before_eq;
  331. }
  332. else if (*in == '/') {
  333. store_component_name();
  334. store_component_value();
  335. state = slash_after_value;
  336. }
  337. else if (*in == '>') {
  338. store_component_name();
  339. store_component_value();
  340. state = tag_end;
  341. }
  342. else {
  343. if (*in == '"' || *in == '\'' || *in == '<') {
  344. /* Should never be in attribute names but ignored */
  345. tag->flags |= FL_BROKEN;
  346. }
  347. store_value_character(true);
  348. }
  349. break;
  350. case spaces_before_eq:
  351. if (*in == '=') {
  352. state = parse_equal;
  353. }
  354. else if (!g_ascii_isspace (*in)) {
  355. /*
  356. * HTML defines that crap could still be restored and
  357. * calculated somehow... So we have to follow this stupid behaviour
  358. */
  359. /*
  360. * TODO: estimate what insane things do email clients in each case
  361. */
  362. if (*in == '>') {
  363. /*
  364. * Attribtute name followed by end of tag
  365. * Should be okay (empty attribute). The rest is handled outside
  366. * this automata.
  367. */
  368. store_component_value();
  369. state = tag_end;
  370. }
  371. else if (*in == '"' || *in == '\'' || *in == '<') {
  372. /* Attribute followed by quote... Missing '=' ? Dunno, need to test */
  373. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  374. tag->flags |= FL_BROKEN;
  375. store_component_value();
  376. store_value_character(true);
  377. state = spaces_after_param;
  378. }
  379. else {
  380. /* Empty attribute */
  381. store_component_value();
  382. store_value_character(true);
  383. state = spaces_after_param;
  384. }
  385. }
  386. break;
  387. case spaces_after_eq:
  388. if (*in == '"') {
  389. state = parse_start_dquote;
  390. }
  391. else if (*in == '\'') {
  392. state = parse_start_squote;
  393. }
  394. else if (!g_ascii_isspace (*in)) {
  395. store_value_character(true);
  396. state = parse_value;
  397. }
  398. break;
  399. case parse_equal:
  400. if (g_ascii_isspace (*in)) {
  401. state = spaces_after_eq;
  402. }
  403. else if (*in == '"') {
  404. state = parse_start_dquote;
  405. }
  406. else if (*in == '\'') {
  407. state = parse_start_squote;
  408. }
  409. else {
  410. store_value_character(true);
  411. state = parse_value;
  412. }
  413. break;
  414. case parse_start_dquote:
  415. if (*in == '"') {
  416. state = spaces_after_param;
  417. }
  418. else {
  419. store_value_character(false);
  420. state = parse_dqvalue;
  421. }
  422. break;
  423. case parse_start_squote:
  424. if (*in == '\'') {
  425. state = spaces_after_param;
  426. }
  427. else {
  428. store_value_character(false);
  429. state = parse_sqvalue;
  430. }
  431. break;
  432. case parse_dqvalue:
  433. if (*in == '"') {
  434. store_component_value();
  435. state = parse_end_dquote;
  436. }
  437. else {
  438. store_value_character(false);
  439. }
  440. break;
  441. case parse_sqvalue:
  442. if (*in == '\'') {
  443. store_component_value();
  444. state = parse_end_squote;
  445. }
  446. else {
  447. store_value_character(false);
  448. }
  449. break;
  450. case parse_value:
  451. if (*in == '/') {
  452. state = slash_in_unqouted_value;
  453. }
  454. else if (g_ascii_isspace (*in) || *in == '>' || *in == '"') {
  455. store_component_value();
  456. state = spaces_after_param;
  457. }
  458. else {
  459. store_value_character(false);
  460. }
  461. break;
  462. case parse_end_dquote:
  463. case parse_end_squote:
  464. if (g_ascii_isspace (*in)) {
  465. state = spaces_after_param;
  466. }
  467. else if (*in == '/') {
  468. store_component_value();
  469. store_value_character(true);
  470. state = slash_after_value;
  471. }
  472. else {
  473. /* No space, proceed immediately to the attribute name */
  474. state = parse_attr_name;
  475. store_component_value();
  476. store_value_character(true);
  477. }
  478. break;
  479. case spaces_after_param:
  480. if (!g_ascii_isspace (*in)) {
  481. if (*in == '/') {
  482. state = slash_after_value;
  483. }
  484. else if (*in == '=') {
  485. /* Attributes cannot start with '=' */
  486. tag->flags |= FL_BROKEN;
  487. store_value_character(true);
  488. state = parse_attr_name;
  489. }
  490. else {
  491. store_value_character(true);
  492. state = parse_attr_name;
  493. }
  494. }
  495. break;
  496. case slash_after_value:
  497. if (*in == '>') {
  498. tag->flags |= FL_CLOSED;
  499. state = tag_end;
  500. }
  501. else if (!g_ascii_isspace(*in)) {
  502. tag->flags |= FL_BROKEN;
  503. state = parse_attr_name;
  504. }
  505. break;
  506. case slash_in_unqouted_value:
  507. if (*in == '>') {
  508. /* That slash was in fact closing tag slash, wohoo */
  509. tag->flags |= FL_CLOSED;
  510. state = tag_end;
  511. store_component_value();
  512. }
  513. else {
  514. /* Welcome to the world of html, revert state and save missing / */
  515. parser_env.buf.push_back('/');
  516. store_value_character(false);
  517. state = parse_value;
  518. }
  519. break;
  520. case ignore_bad_tag:
  521. case tag_end:
  522. break;
  523. }
  524. parser_env.cur_state = state;
  525. }
  526. static inline auto
  527. html_is_absolute_url(std::string_view st) -> bool
  528. {
  529. auto alnum_pos = std::find_if(std::begin(st), std::end(st),
  530. [](auto c) {return !g_ascii_isalnum(c);});
  531. if (alnum_pos != std::end(st) && alnum_pos != std::begin(st)) {
  532. if (*alnum_pos == ':') {
  533. if (st.substr(0, std::distance(std::begin(st), alnum_pos)) == "mailto") {
  534. return true;
  535. }
  536. std::advance(alnum_pos, 1);
  537. if (alnum_pos != std::end(st)) {
  538. /* Include even malformed urls */
  539. if (*alnum_pos == '/' || *alnum_pos == '\\') {
  540. return true;
  541. }
  542. }
  543. }
  544. }
  545. return false;
  546. }
  547. static auto
  548. html_process_url_tag(rspamd_mempool_t *pool,
  549. struct html_tag *tag,
  550. struct html_content *hc) -> std::optional<struct rspamd_url *>
  551. {
  552. auto found_href_maybe = tag->find_component(html_component_type::RSPAMD_HTML_COMPONENT_HREF);
  553. if (found_href_maybe) {
  554. /* Check base url */
  555. auto &href_value = found_href_maybe.value();
  556. if (hc && hc->base_url) {
  557. /*
  558. * Relative url cannot start from the following:
  559. * schema://
  560. * data:
  561. * slash
  562. */
  563. if (!html_is_absolute_url(href_value)) {
  564. if (href_value.size() >= sizeof("data:") &&
  565. g_ascii_strncasecmp(href_value.data(), "data:", sizeof("data:") - 1) == 0) {
  566. /* Image data url, never insert as url */
  567. return std::nullopt;
  568. }
  569. /* Assume relative url */
  570. auto need_slash = false;
  571. auto orig_len = href_value.size();
  572. auto len = orig_len + hc->base_url->urllen;
  573. if (hc->base_url->datalen == 0) {
  574. need_slash = true;
  575. len++;
  576. }
  577. auto *buf = rspamd_mempool_alloc_buffer(pool, len + 1);
  578. auto nlen = (std::size_t) rspamd_snprintf(buf, len + 1,
  579. "%*s%s%*s",
  580. (int) hc->base_url->urllen, hc->base_url->string,
  581. need_slash ? "/" : "",
  582. (gint) orig_len, href_value.data());
  583. href_value = {buf, nlen};
  584. }
  585. else if (href_value.size() > 2 && href_value[0] == '/' && href_value[1] != '/') {
  586. /* Relative to the hostname */
  587. auto orig_len = href_value.size();
  588. auto len = orig_len + hc->base_url->hostlen + hc->base_url->protocollen +
  589. 3 /* for :// */;
  590. auto *buf = rspamd_mempool_alloc_buffer(pool, len + 1);
  591. auto nlen = (std::size_t) rspamd_snprintf(buf, len + 1, "%*s://%*s/%*s",
  592. (int) hc->base_url->protocollen, hc->base_url->string,
  593. (int) hc->base_url->hostlen, rspamd_url_host_unsafe (hc->base_url),
  594. (gint) orig_len, href_value.data());
  595. href_value = {buf, nlen};
  596. }
  597. }
  598. auto url = html_process_url(pool, href_value);
  599. if (url && std::holds_alternative<std::monostate>(tag->extra)) {
  600. tag->extra = url.value();
  601. }
  602. return url;
  603. }
  604. return std::nullopt;
  605. }
  606. struct rspamd_html_url_query_cbd {
  607. rspamd_mempool_t *pool;
  608. khash_t (rspamd_url_hash) *url_set;
  609. struct rspamd_url *url;
  610. GPtrArray *part_urls;
  611. };
  612. static gboolean
  613. html_url_query_callback(struct rspamd_url *url, gsize start_offset,
  614. gsize end_offset, gpointer ud)
  615. {
  616. struct rspamd_html_url_query_cbd *cbd =
  617. (struct rspamd_html_url_query_cbd *) ud;
  618. rspamd_mempool_t *pool;
  619. pool = cbd->pool;
  620. if (url->protocol == PROTOCOL_MAILTO) {
  621. if (url->userlen == 0) {
  622. return FALSE;
  623. }
  624. }
  625. msg_debug_html ("found url %s in query of url"
  626. " %*s", url->string,
  627. cbd->url->querylen, rspamd_url_query_unsafe(cbd->url));
  628. url->flags |= RSPAMD_URL_FLAG_QUERY;
  629. if (rspamd_url_set_add_or_increase(cbd->url_set, url, false)
  630. && cbd->part_urls) {
  631. g_ptr_array_add(cbd->part_urls, url);
  632. }
  633. return TRUE;
  634. }
  635. static void
  636. html_process_query_url(rspamd_mempool_t *pool, struct rspamd_url *url,
  637. khash_t (rspamd_url_hash) *url_set,
  638. GPtrArray *part_urls)
  639. {
  640. if (url->querylen > 0) {
  641. struct rspamd_html_url_query_cbd qcbd;
  642. qcbd.pool = pool;
  643. qcbd.url_set = url_set;
  644. qcbd.url = url;
  645. qcbd.part_urls = part_urls;
  646. rspamd_url_find_multiple(pool,
  647. rspamd_url_query_unsafe (url), url->querylen,
  648. RSPAMD_URL_FIND_ALL, NULL,
  649. html_url_query_callback, &qcbd);
  650. }
  651. if (part_urls) {
  652. g_ptr_array_add(part_urls, url);
  653. }
  654. }
  655. static auto
  656. html_process_data_image(rspamd_mempool_t *pool,
  657. struct html_image *img,
  658. std::string_view input) -> void
  659. {
  660. /*
  661. * Here, we do very basic processing of the data:
  662. * detect if we have something like: `data:image/xxx;base64,yyyzzz==`
  663. * We only parse base64 encoded data.
  664. * We ignore content type so far
  665. */
  666. struct rspamd_image *parsed_image;
  667. const gchar *semicolon_pos = input.data(),
  668. *end = input.data() + input.size();
  669. if ((semicolon_pos = (const gchar *) memchr(semicolon_pos, ';', end - semicolon_pos)) != NULL) {
  670. if (end - semicolon_pos > sizeof("base64,")) {
  671. if (memcmp(semicolon_pos + 1, "base64,", sizeof("base64,") - 1) == 0) {
  672. const gchar *data_pos = semicolon_pos + sizeof("base64,");
  673. gchar *decoded;
  674. gsize encoded_len = end - data_pos, decoded_len;
  675. rspamd_ftok_t inp;
  676. decoded_len = (encoded_len / 4 * 3) + 12;
  677. decoded = rspamd_mempool_alloc_buffer(pool, decoded_len);
  678. rspamd_cryptobox_base64_decode(data_pos, encoded_len,
  679. reinterpret_cast<guchar *>(decoded), &decoded_len);
  680. inp.begin = decoded;
  681. inp.len = decoded_len;
  682. parsed_image = rspamd_maybe_process_image(pool, &inp);
  683. if (parsed_image) {
  684. msg_debug_html ("detected %s image of size %ud x %ud in data url",
  685. rspamd_image_type_str(parsed_image->type),
  686. parsed_image->width, parsed_image->height);
  687. img->embedded_image = parsed_image;
  688. }
  689. }
  690. }
  691. else {
  692. /* Nothing useful */
  693. return;
  694. }
  695. }
  696. }
  697. static void
  698. html_process_img_tag(rspamd_mempool_t *pool,
  699. struct html_tag *tag,
  700. struct html_content *hc,
  701. khash_t (rspamd_url_hash) *url_set,
  702. GPtrArray *part_urls)
  703. {
  704. struct html_image *img;
  705. img = rspamd_mempool_alloc0_type (pool, struct html_image);
  706. img->tag = tag;
  707. for (const auto &param : tag->components) {
  708. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_HREF) {
  709. /* Check base url */
  710. const auto &href_value = param.value;
  711. if (href_value.size() > 0) {
  712. rspamd_ftok_t fstr;
  713. fstr.begin = href_value.data();
  714. fstr.len = href_value.size();
  715. img->src = rspamd_mempool_ftokdup (pool, &fstr);
  716. if (href_value.size() > sizeof("cid:") - 1 && memcmp(href_value.data(),
  717. "cid:", sizeof("cid:") - 1) == 0) {
  718. /* We have an embedded image */
  719. img->src += sizeof("cid:") - 1;
  720. img->flags |= RSPAMD_HTML_FLAG_IMAGE_EMBEDDED;
  721. }
  722. else {
  723. if (href_value.size() > sizeof("data:") - 1 && memcmp(href_value.data(),
  724. "data:", sizeof("data:") - 1) == 0) {
  725. /* We have an embedded image in HTML tag */
  726. img->flags |=
  727. (RSPAMD_HTML_FLAG_IMAGE_EMBEDDED | RSPAMD_HTML_FLAG_IMAGE_DATA);
  728. html_process_data_image(pool, img, href_value);
  729. hc->flags |= RSPAMD_HTML_FLAG_HAS_DATA_URLS;
  730. }
  731. else {
  732. img->flags |= RSPAMD_HTML_FLAG_IMAGE_EXTERNAL;
  733. if (img->src) {
  734. std::string_view cpy{href_value};
  735. auto maybe_url = html_process_url(pool, cpy);
  736. if (maybe_url) {
  737. img->url = maybe_url.value();
  738. struct rspamd_url *existing;
  739. img->url->flags |= RSPAMD_URL_FLAG_IMAGE;
  740. existing = rspamd_url_set_add_or_return(url_set,
  741. img->url);
  742. if (existing && existing != img->url) {
  743. /*
  744. * We have some other URL that could be
  745. * found, e.g. from another part. However,
  746. * we still want to set an image flag on it
  747. */
  748. existing->flags |= img->url->flags;
  749. existing->count++;
  750. }
  751. else if (part_urls) {
  752. /* New url */
  753. g_ptr_array_add(part_urls, img->url);
  754. }
  755. }
  756. }
  757. }
  758. }
  759. }
  760. }
  761. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_HEIGHT) {
  762. unsigned long val;
  763. rspamd_strtoul(param.value.data(), param.value.size(), &val);
  764. img->height = val;
  765. }
  766. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_WIDTH) {
  767. unsigned long val;
  768. rspamd_strtoul(param.value.data(), param.value.size(), &val);
  769. img->width = val;
  770. }
  771. /* TODO: rework to css at some time */
  772. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_STYLE) {
  773. if (img->height == 0) {
  774. auto style_st = param.value;
  775. auto pos = rspamd_substring_search_caseless(style_st.data(),
  776. style_st.size(),
  777. "height", sizeof("height") - 1);
  778. if (pos != -1) {
  779. auto substr = style_st.substr(pos + sizeof("height") - 1);
  780. for (auto i = 0; i < substr.size(); i++) {
  781. auto t = substr[i];
  782. if (g_ascii_isdigit (t)) {
  783. unsigned long val;
  784. rspamd_strtoul(substr.data(),
  785. substr.size(), &val);
  786. img->height = val;
  787. break;
  788. }
  789. else if (!g_ascii_isspace (t) && t != '=' && t != ':') {
  790. /* Fallback */
  791. break;
  792. }
  793. }
  794. }
  795. }
  796. if (img->width == 0) {
  797. auto style_st = param.value;
  798. auto pos = rspamd_substring_search_caseless(style_st.data(),
  799. style_st.size(),
  800. "width", sizeof("width") - 1);
  801. if (pos != -1) {
  802. auto substr = style_st.substr(pos + sizeof("width") - 1);
  803. for (auto i = 0; i < substr.size(); i++) {
  804. auto t = substr[i];
  805. if (g_ascii_isdigit (t)) {
  806. unsigned long val;
  807. rspamd_strtoul(substr.data(),
  808. substr.size(), &val);
  809. img->width = val;
  810. break;
  811. }
  812. else if (!g_ascii_isspace (t) && t != '=' && t != ':') {
  813. /* Fallback */
  814. break;
  815. }
  816. }
  817. }
  818. }
  819. }
  820. }
  821. if (img->embedded_image) {
  822. if (img->height == 0) {
  823. img->height = img->embedded_image->height;
  824. }
  825. if (img->width == 0) {
  826. img->width = img->embedded_image->width;
  827. }
  828. }
  829. hc->images.push_back(img);
  830. tag->extra = img;
  831. }
  832. static auto
  833. html_process_link_tag(rspamd_mempool_t *pool, struct html_tag *tag,
  834. struct html_content *hc,
  835. khash_t (rspamd_url_hash) *url_set,
  836. GPtrArray *part_urls) -> void
  837. {
  838. auto found_rel_maybe = tag->find_component(html_component_type::RSPAMD_HTML_COMPONENT_REL);
  839. if (found_rel_maybe) {
  840. if (found_rel_maybe.value() == "icon") {
  841. html_process_img_tag(pool, tag, hc, url_set, part_urls);
  842. }
  843. }
  844. }
  845. static auto
  846. html_process_block_tag(rspamd_mempool_t *pool, struct html_tag *tag,
  847. struct html_content *hc) -> void
  848. {
  849. std::optional<css::css_value> maybe_fgcolor, maybe_bgcolor;
  850. bool hidden = false;
  851. for (const auto &param : tag->components) {
  852. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_COLOR) {
  853. maybe_fgcolor = css::css_value::maybe_color_from_string(param.value);
  854. }
  855. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_BGCOLOR) {
  856. maybe_bgcolor = css::css_value::maybe_color_from_string(param.value);
  857. }
  858. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_STYLE) {
  859. tag->block = rspamd::css::parse_css_declaration(pool, param.value);
  860. }
  861. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_HIDDEN) {
  862. hidden = true;
  863. }
  864. }
  865. if (!tag->block) {
  866. tag->block = html_block::undefined_html_block_pool(pool);
  867. }
  868. if (hidden) {
  869. tag->block->set_display(false);
  870. }
  871. if (maybe_fgcolor) {
  872. tag->block->set_fgcolor(maybe_fgcolor->to_color().value());
  873. }
  874. if (maybe_bgcolor) {
  875. tag->block->set_bgcolor(maybe_bgcolor->to_color().value());
  876. }
  877. }
  878. static inline auto
  879. html_append_parsed(struct html_content *hc,
  880. std::string_view data,
  881. bool transparent,
  882. std::size_t input_len,
  883. std::string &dest) -> std::size_t
  884. {
  885. auto cur_offset = dest.size();
  886. if (dest.size() > input_len) {
  887. /* Impossible case, refuse to append */
  888. return 0;
  889. }
  890. if (data.size() > 0) {
  891. /* Handle multiple spaces at the begin */
  892. if (cur_offset > 0) {
  893. auto last = dest.back();
  894. if (!g_ascii_isspace(last) && g_ascii_isspace(data.front())) {
  895. dest.append(" ");
  896. data = {data.data() + 1, data.size() - 1};
  897. cur_offset++;
  898. }
  899. }
  900. if (data.find('\0') != std::string_view::npos) {
  901. auto replace_zero_func = [](const auto &input, auto &output) {
  902. const auto last = input.cend();
  903. for (auto it = input.cbegin(); it != last; ++it) {
  904. if (*it == '\0') {
  905. output.append(u8"\uFFFD");
  906. }
  907. else {
  908. output.push_back(*it);
  909. }
  910. }
  911. };
  912. dest.reserve(dest.size() + data.size() + sizeof(u8"\uFFFD"));
  913. replace_zero_func(data, dest);
  914. hc->flags |= RSPAMD_HTML_FLAG_HAS_ZEROS;
  915. }
  916. else {
  917. dest.append(data);
  918. }
  919. }
  920. auto nlen = decode_html_entitles_inplace(dest.data() + cur_offset,
  921. dest.size() - cur_offset, true);
  922. dest.resize(nlen + cur_offset);
  923. if (transparent) {
  924. /* Replace all visible characters with spaces */
  925. auto start = std::next(dest.begin(), cur_offset);
  926. std::replace_if(start, std::end(dest), [](const auto c) {
  927. return !g_ascii_isspace(c);
  928. }, ' ');
  929. }
  930. return nlen;
  931. }
  932. static auto
  933. html_process_displayed_href_tag(rspamd_mempool_t *pool,
  934. struct html_content *hc,
  935. std::string_view data,
  936. const struct html_tag *cur_tag,
  937. GList **exceptions,
  938. khash_t (rspamd_url_hash) *url_set,
  939. goffset dest_offset) -> void
  940. {
  941. if (std::holds_alternative<rspamd_url *>(cur_tag->extra)) {
  942. auto *url = std::get<rspamd_url *>(cur_tag->extra);
  943. html_check_displayed_url(pool,
  944. exceptions, url_set,
  945. data,
  946. dest_offset,
  947. url);
  948. }
  949. }
  950. static auto
  951. html_append_tag_content(rspamd_mempool_t *pool,
  952. const gchar *start, gsize len,
  953. struct html_content *hc,
  954. html_tag *tag,
  955. GList **exceptions,
  956. khash_t (rspamd_url_hash) *url_set) -> goffset
  957. {
  958. auto is_visible = true, is_block = false, is_spaces = false, is_transparent = false;
  959. goffset next_tag_offset = tag->closing.end,
  960. initial_parsed_offset = hc->parsed.size(),
  961. initial_invisible_offset = hc->invisible.size();
  962. auto calculate_final_tag_offsets = [&]() -> void {
  963. if (is_visible) {
  964. tag->content_offset = initial_parsed_offset;
  965. tag->closing.start = hc->parsed.size();
  966. }
  967. else {
  968. tag->content_offset = initial_invisible_offset;
  969. tag->closing.start = hc->invisible.size();
  970. }
  971. };
  972. if (tag->closing.end == -1) {
  973. if (tag->closing.start != -1) {
  974. next_tag_offset = tag->closing.start;
  975. tag->closing.end = tag->closing.start;
  976. }
  977. else {
  978. next_tag_offset = tag->content_offset;
  979. tag->closing.end = tag->content_offset;
  980. }
  981. }
  982. if (tag->closing.start == -1) {
  983. tag->closing.start = tag->closing.end;
  984. }
  985. auto append_margin = [&](char c) -> void {
  986. /* We do care about visible margins only */
  987. if (is_visible) {
  988. if (!hc->parsed.empty() && hc->parsed.back() != c && hc->parsed.back() != '\n') {
  989. if (hc->parsed.back() == ' ') {
  990. /* We also strip extra spaces at the end, but limiting the start */
  991. auto last = std::make_reverse_iterator(hc->parsed.begin() + initial_parsed_offset);
  992. auto first = std::find_if(hc->parsed.rbegin(), last,
  993. [](auto ch) -> auto {
  994. return ch != ' ';
  995. });
  996. hc->parsed.erase(first.base(), hc->parsed.end());
  997. g_assert(hc->parsed.size() >= initial_parsed_offset);
  998. }
  999. hc->parsed.push_back(c);
  1000. }
  1001. }
  1002. };
  1003. if (tag->id == Tag_BR || tag->id == Tag_HR) {
  1004. if (!(tag->flags & FL_IGNORE)) {
  1005. hc->parsed.append("\n");
  1006. }
  1007. auto ret = tag->content_offset;
  1008. calculate_final_tag_offsets();
  1009. return ret;
  1010. }
  1011. else if ((tag->id == Tag_HEAD && (tag->flags & FL_IGNORE)) || (tag->flags & CM_HEAD)) {
  1012. auto ret = tag->closing.end;
  1013. calculate_final_tag_offsets();
  1014. return ret;
  1015. }
  1016. if ((tag->flags & (FL_COMMENT | FL_XML | FL_IGNORE | CM_HEAD))) {
  1017. is_visible = false;
  1018. }
  1019. else {
  1020. if (!tag->block) {
  1021. is_visible = true;
  1022. }
  1023. else if (!tag->block->is_visible()) {
  1024. if (!tag->block->is_transparent()) {
  1025. is_visible = false;
  1026. }
  1027. else {
  1028. if (tag->block->has_display() &&
  1029. tag->block->display == css::css_display_value::DISPLAY_HIDDEN) {
  1030. is_visible = false;
  1031. }
  1032. else {
  1033. is_transparent = true;
  1034. }
  1035. }
  1036. }
  1037. else {
  1038. if (tag->block->display == css::css_display_value::DISPLAY_BLOCK) {
  1039. is_block = true;
  1040. }
  1041. else if (tag->block->display == css::css_display_value::DISPLAY_TABLE_ROW) {
  1042. is_spaces = true;
  1043. }
  1044. }
  1045. }
  1046. if (is_block) {
  1047. append_margin('\n');
  1048. }
  1049. else if (is_spaces) {
  1050. append_margin(' ');
  1051. }
  1052. goffset cur_offset = tag->content_offset;
  1053. for (auto *cld : tag->children) {
  1054. auto enclosed_start = cld->tag_start;
  1055. goffset initial_part_len = enclosed_start - cur_offset;
  1056. if (initial_part_len > 0) {
  1057. if (is_visible) {
  1058. html_append_parsed(hc,
  1059. {start + cur_offset, std::size_t(initial_part_len)},
  1060. is_transparent, len, hc->parsed);
  1061. }
  1062. else {
  1063. html_append_parsed(hc,
  1064. {start + cur_offset, std::size_t(initial_part_len)},
  1065. is_transparent, len, hc->invisible);
  1066. }
  1067. }
  1068. auto next_offset = html_append_tag_content(pool, start, len,
  1069. hc, cld, exceptions, url_set);
  1070. /* Do not allow shifting back */
  1071. if (next_offset > cur_offset) {
  1072. cur_offset = next_offset;
  1073. }
  1074. }
  1075. if (cur_offset < tag->closing.start) {
  1076. goffset final_part_len = tag->closing.start - cur_offset;
  1077. if (final_part_len > 0) {
  1078. if (is_visible) {
  1079. html_append_parsed(hc,
  1080. {start + cur_offset, std::size_t(final_part_len)},
  1081. is_transparent,
  1082. len,
  1083. hc->parsed);
  1084. }
  1085. else {
  1086. html_append_parsed(hc,
  1087. {start + cur_offset, std::size_t(final_part_len)},
  1088. is_transparent,
  1089. len,
  1090. hc->invisible);
  1091. }
  1092. }
  1093. }
  1094. if (is_block) {
  1095. append_margin('\n');
  1096. }
  1097. else if (is_spaces) {
  1098. append_margin(' ');
  1099. }
  1100. if (is_visible) {
  1101. if (tag->id == Tag_A) {
  1102. auto written_len = hc->parsed.size() - initial_parsed_offset;
  1103. html_process_displayed_href_tag(pool, hc,
  1104. {hc->parsed.data() + initial_parsed_offset, std::size_t(written_len)},
  1105. tag, exceptions,
  1106. url_set, initial_parsed_offset);
  1107. }
  1108. else if (tag->id == Tag_IMG) {
  1109. /* Process ALT if presented */
  1110. auto maybe_alt = tag->find_component(html_component_type::RSPAMD_HTML_COMPONENT_ALT);
  1111. if (maybe_alt) {
  1112. if (!hc->parsed.empty() && !g_ascii_isspace (hc->parsed.back())) {
  1113. /* Add a space */
  1114. hc->parsed += ' ';
  1115. }
  1116. hc->parsed.append(maybe_alt.value());
  1117. if (!hc->parsed.empty() && !g_ascii_isspace (hc->parsed.back())) {
  1118. /* Add a space */
  1119. hc->parsed += ' ';
  1120. }
  1121. }
  1122. }
  1123. }
  1124. else {
  1125. /* Invisible stuff */
  1126. if (std::holds_alternative<rspamd_url *>(tag->extra)) {
  1127. auto *url_enclosed = std::get<rspamd_url *>(tag->extra);
  1128. /*
  1129. * TODO: when hash is fixed to include flags we need to remove and add
  1130. * url to the hash set
  1131. */
  1132. if (url_enclosed) {
  1133. url_enclosed->flags |= RSPAMD_URL_FLAG_INVISIBLE;
  1134. }
  1135. }
  1136. }
  1137. calculate_final_tag_offsets();
  1138. return next_tag_offset;
  1139. }
  1140. auto
  1141. html_process_input(rspamd_mempool_t *pool,
  1142. GByteArray *in,
  1143. GList **exceptions,
  1144. khash_t (rspamd_url_hash) *url_set,
  1145. GPtrArray *part_urls,
  1146. bool allow_css) -> html_content *
  1147. {
  1148. const gchar *p, *c, *end, *start;
  1149. guchar t;
  1150. auto closing = false;
  1151. guint obrace = 0, ebrace = 0;
  1152. struct rspamd_url *url = nullptr;
  1153. gint href_offset = -1;
  1154. struct html_tag *cur_tag = nullptr, *parent_tag = nullptr, cur_closing_tag;
  1155. struct tag_content_parser_state content_parser_env;
  1156. enum {
  1157. parse_start = 0,
  1158. content_before_start,
  1159. tag_begin,
  1160. sgml_tag,
  1161. xml_tag,
  1162. compound_tag,
  1163. comment_tag,
  1164. comment_content,
  1165. sgml_content,
  1166. tag_content,
  1167. tag_end_opening,
  1168. tag_end_closing,
  1169. html_text_content,
  1170. xml_tag_end,
  1171. tag_raw_text,
  1172. tag_raw_text_less_than,
  1173. tags_limit_overflow,
  1174. } state = parse_start;
  1175. enum class html_document_state {
  1176. doctype,
  1177. head,
  1178. body
  1179. } html_document_state = html_document_state::doctype;
  1180. g_assert (in != NULL);
  1181. g_assert (pool != NULL);
  1182. struct html_content *hc = new html_content;
  1183. rspamd_mempool_add_destructor(pool, html_content::html_content_dtor, hc);
  1184. auto new_tag = [&](int flags = 0) -> struct html_tag * {
  1185. if (hc->all_tags.size() > rspamd::html::max_tags) {
  1186. hc->flags |= RSPAMD_HTML_FLAG_TOO_MANY_TAGS;
  1187. return nullptr;
  1188. }
  1189. hc->all_tags.emplace_back(std::make_unique<html_tag>());
  1190. auto *ntag = hc->all_tags.back().get();
  1191. ntag->tag_start = c - start;
  1192. ntag->flags = flags;
  1193. if (cur_tag && !(cur_tag->flags & (CM_EMPTY | FL_CLOSED)) && cur_tag != &cur_closing_tag) {
  1194. parent_tag = cur_tag;
  1195. }
  1196. if (flags & FL_XML) {
  1197. return ntag;
  1198. }
  1199. return ntag;
  1200. };
  1201. auto process_opening_tag = [&]() {
  1202. if (cur_tag->id > Tag_UNKNOWN) {
  1203. if (cur_tag->flags & CM_UNIQUE) {
  1204. if (!hc->tags_seen[cur_tag->id]) {
  1205. /* Duplicate tag has been found */
  1206. hc->flags |= RSPAMD_HTML_FLAG_DUPLICATE_ELEMENTS;
  1207. }
  1208. }
  1209. hc->tags_seen[cur_tag->id] = true;
  1210. }
  1211. /* Shift to the first unclosed tag */
  1212. auto *pt = parent_tag;
  1213. while (pt && (pt->flags & FL_CLOSED)) {
  1214. pt = pt->parent;
  1215. }
  1216. if (pt) {
  1217. cur_tag->parent = pt;
  1218. g_assert(cur_tag->parent != cur_tag);
  1219. g_assert(cur_tag->parent != &cur_closing_tag);
  1220. parent_tag = pt;
  1221. parent_tag->children.push_back(cur_tag);
  1222. }
  1223. else {
  1224. if (hc->root_tag) {
  1225. cur_tag->parent = hc->root_tag;
  1226. g_assert(cur_tag->parent != cur_tag);
  1227. hc->root_tag->children.push_back(cur_tag);
  1228. parent_tag = hc->root_tag;
  1229. }
  1230. else {
  1231. if (cur_tag->id == Tag_HTML) {
  1232. hc->root_tag = cur_tag;
  1233. }
  1234. else {
  1235. /* Insert a fake html tag */
  1236. hc->all_tags.emplace_back(std::make_unique<html_tag>());
  1237. auto *top_tag = hc->all_tags.back().get();
  1238. top_tag->tag_start = 0;
  1239. top_tag->flags = FL_VIRTUAL;
  1240. top_tag->id = Tag_HTML;
  1241. top_tag->content_offset = 0;
  1242. top_tag->children.push_back(cur_tag);
  1243. cur_tag->parent = top_tag;
  1244. g_assert(cur_tag->parent != cur_tag);
  1245. hc->root_tag = top_tag;
  1246. parent_tag = top_tag;
  1247. }
  1248. }
  1249. }
  1250. if (cur_tag->flags & FL_HREF && html_document_state == html_document_state::body) {
  1251. auto maybe_url = html_process_url_tag(pool, cur_tag, hc);
  1252. if (maybe_url) {
  1253. url = maybe_url.value();
  1254. if (url_set != NULL) {
  1255. struct rspamd_url *maybe_existing =
  1256. rspamd_url_set_add_or_return(url_set, maybe_url.value());
  1257. if (maybe_existing == maybe_url.value()) {
  1258. html_process_query_url(pool, url, url_set,
  1259. part_urls);
  1260. }
  1261. else {
  1262. url = maybe_existing;
  1263. /* Replace extra as well */
  1264. cur_tag->extra = maybe_existing;
  1265. /* Increase count to avoid odd checks failure */
  1266. url->count++;
  1267. }
  1268. }
  1269. if (part_urls) {
  1270. g_ptr_array_add(part_urls, url);
  1271. }
  1272. href_offset = hc->parsed.size();
  1273. }
  1274. }
  1275. else if (cur_tag->id == Tag_BASE) {
  1276. /*
  1277. * Base is allowed only within head tag but HTML is retarded
  1278. */
  1279. auto maybe_url = html_process_url_tag(pool, cur_tag, hc);
  1280. if (maybe_url) {
  1281. msg_debug_html ("got valid base tag");
  1282. cur_tag->extra = maybe_url.value();
  1283. cur_tag->flags |= FL_HREF;
  1284. if (hc->base_url == nullptr) {
  1285. hc->base_url = maybe_url.value();
  1286. }
  1287. else {
  1288. msg_debug_html ("ignore redundant base tag");
  1289. }
  1290. }
  1291. else {
  1292. msg_debug_html ("got invalid base tag!");
  1293. }
  1294. }
  1295. if (cur_tag->id == Tag_IMG) {
  1296. html_process_img_tag(pool, cur_tag, hc, url_set,
  1297. part_urls);
  1298. }
  1299. else if (cur_tag->id == Tag_LINK) {
  1300. html_process_link_tag(pool, cur_tag, hc, url_set,
  1301. part_urls);
  1302. }
  1303. if (!(cur_tag->flags & CM_EMPTY)) {
  1304. html_process_block_tag(pool, cur_tag, hc);
  1305. }
  1306. else {
  1307. /* Implicitly close */
  1308. cur_tag->flags |= FL_CLOSED;
  1309. }
  1310. if (cur_tag->flags & FL_CLOSED) {
  1311. cur_tag->closing.end = cur_tag->content_offset;
  1312. cur_tag->closing.start = cur_tag->tag_start;
  1313. cur_tag = parent_tag;
  1314. }
  1315. };
  1316. p = (const char *) in->data;
  1317. c = p;
  1318. end = p + in->len;
  1319. start = c;
  1320. while (p < end) {
  1321. t = *p;
  1322. switch (state) {
  1323. case parse_start:
  1324. if (t == '<') {
  1325. state = tag_begin;
  1326. }
  1327. else {
  1328. /* We have no starting tag, so assume that it's content */
  1329. hc->flags |= RSPAMD_HTML_FLAG_BAD_START;
  1330. cur_tag = new_tag();
  1331. html_document_state = html_document_state::body;
  1332. if (cur_tag) {
  1333. cur_tag->id = Tag_HTML;
  1334. hc->root_tag = cur_tag;
  1335. state = content_before_start;
  1336. }
  1337. else {
  1338. state = tags_limit_overflow;
  1339. }
  1340. }
  1341. break;
  1342. case content_before_start:
  1343. if (t == '<') {
  1344. state = tag_begin;
  1345. }
  1346. else {
  1347. p++;
  1348. }
  1349. break;
  1350. case tag_begin:
  1351. switch (t) {
  1352. case '<':
  1353. c = p;
  1354. p++;
  1355. closing = FALSE;
  1356. break;
  1357. case '!':
  1358. cur_tag = new_tag(FL_XML | FL_CLOSED);
  1359. if (cur_tag) {
  1360. state = sgml_tag;
  1361. }
  1362. else {
  1363. state = tags_limit_overflow;
  1364. }
  1365. p++;
  1366. break;
  1367. case '?':
  1368. cur_tag = new_tag(FL_XML | FL_CLOSED);
  1369. if (cur_tag) {
  1370. state = xml_tag;
  1371. }
  1372. else {
  1373. state = tags_limit_overflow;
  1374. }
  1375. hc->flags |= RSPAMD_HTML_FLAG_XML;
  1376. p++;
  1377. break;
  1378. case '/':
  1379. closing = TRUE;
  1380. /* We fill fake closing tag to fill it with the content parser */
  1381. cur_closing_tag.clear();
  1382. /*
  1383. * For closing tags, we need to find some corresponding opening tag.
  1384. * However, at this point we have not even parsed a name, so we
  1385. * can not assume anything about balancing, etc.
  1386. *
  1387. * So we need to ensure that:
  1388. * 1) We have some opening tag in the chain cur_tag->parent...
  1389. * 2) cur_tag is nullptr - okay, html is just brain damaged
  1390. * 3) cur_tag must NOT be equal to cur_closing tag. It means that
  1391. * we had some poor closing tag but we still need to find an opening
  1392. * tag... Somewhere...
  1393. */
  1394. if (cur_tag == &cur_closing_tag) {
  1395. if (parent_tag != &cur_closing_tag) {
  1396. cur_closing_tag.parent = parent_tag;
  1397. }
  1398. else {
  1399. cur_closing_tag.parent = nullptr;
  1400. }
  1401. }
  1402. else if (cur_tag && cur_tag->flags & FL_CLOSED) {
  1403. /* Cur tag is already closed, we should find something else */
  1404. auto *tmp = cur_tag;
  1405. while (tmp) {
  1406. tmp = tmp->parent;
  1407. if (tmp == nullptr || !(tmp->flags & FL_CLOSED)) {
  1408. break;
  1409. }
  1410. }
  1411. cur_closing_tag.parent = tmp;
  1412. }
  1413. else {
  1414. cur_closing_tag.parent = cur_tag;
  1415. }
  1416. cur_tag = &cur_closing_tag;
  1417. p++;
  1418. break;
  1419. case '>':
  1420. /* Empty tag */
  1421. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  1422. state = html_text_content;
  1423. continue;
  1424. default:
  1425. if (g_ascii_isalpha(t)) {
  1426. state = tag_content;
  1427. content_parser_env.reset();
  1428. if (!closing) {
  1429. cur_tag = new_tag();
  1430. }
  1431. if (cur_tag) {
  1432. state = tag_content;
  1433. }
  1434. else {
  1435. state = tags_limit_overflow;
  1436. }
  1437. }
  1438. else {
  1439. /* Wrong bad tag */
  1440. state = html_text_content;
  1441. }
  1442. break;
  1443. }
  1444. break;
  1445. case sgml_tag:
  1446. switch (t) {
  1447. case '[':
  1448. state = compound_tag;
  1449. obrace = 1;
  1450. ebrace = 0;
  1451. p++;
  1452. break;
  1453. case '-':
  1454. cur_tag->flags |= FL_COMMENT;
  1455. state = comment_tag;
  1456. p++;
  1457. break;
  1458. default:
  1459. state = sgml_content;
  1460. break;
  1461. }
  1462. break;
  1463. case xml_tag:
  1464. if (t == '?') {
  1465. state = xml_tag_end;
  1466. }
  1467. else if (t == '>') {
  1468. /* Misformed xml tag */
  1469. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  1470. state = tag_end_opening;
  1471. continue;
  1472. }
  1473. /* We efficiently ignore xml tags */
  1474. p++;
  1475. break;
  1476. case xml_tag_end:
  1477. if (t == '>') {
  1478. state = tag_end_opening;
  1479. cur_tag->content_offset = p - start + 1;
  1480. continue;
  1481. }
  1482. else {
  1483. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  1484. }
  1485. p++;
  1486. break;
  1487. case compound_tag:
  1488. if (t == '[') {
  1489. obrace++;
  1490. }
  1491. else if (t == ']') {
  1492. ebrace++;
  1493. }
  1494. else if (t == '>' && obrace == ebrace) {
  1495. state = tag_end_opening;
  1496. cur_tag->content_offset = p - start + 1;
  1497. continue;
  1498. }
  1499. p++;
  1500. break;
  1501. case comment_tag:
  1502. if (t != '-') {
  1503. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  1504. state = tag_end_opening;
  1505. }
  1506. else {
  1507. p++;
  1508. ebrace = 0;
  1509. /*
  1510. * https://www.w3.org/TR/2012/WD-html5-20120329/syntax.html#syntax-comments
  1511. * ... the text must not start with a single
  1512. * U+003E GREATER-THAN SIGN character (>),
  1513. * nor start with a "-" (U+002D) character followed by
  1514. * a U+003E GREATER-THAN SIGN (>) character,
  1515. * nor contain two consecutive U+002D HYPHEN-MINUS
  1516. * characters (--), nor end with a "-" (U+002D) character.
  1517. */
  1518. if (p[0] == '-' && p + 1 < end && p[1] == '>') {
  1519. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  1520. p++;
  1521. state = tag_end_opening;
  1522. }
  1523. else if (*p == '>') {
  1524. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  1525. state = tag_end_opening;
  1526. }
  1527. else {
  1528. state = comment_content;
  1529. }
  1530. }
  1531. break;
  1532. case comment_content:
  1533. if (t == '-') {
  1534. ebrace++;
  1535. }
  1536. else if (t == '>' && ebrace >= 2) {
  1537. cur_tag->content_offset = p - start + 1;
  1538. state = tag_end_opening;
  1539. continue;
  1540. }
  1541. else {
  1542. ebrace = 0;
  1543. }
  1544. p++;
  1545. break;
  1546. case html_text_content:
  1547. if (t != '<') {
  1548. p++;
  1549. }
  1550. else {
  1551. state = tag_begin;
  1552. }
  1553. break;
  1554. case tag_raw_text:
  1555. if (t == '<') {
  1556. c = p;
  1557. state = tag_raw_text_less_than;
  1558. }
  1559. p ++;
  1560. break;
  1561. case tag_raw_text_less_than:
  1562. if (t == '/') {
  1563. /* Here are special things: we look for obrace and then ensure
  1564. * that if there is any closing brace nearby
  1565. * (we look maximum at 30 characters). We also need to ensure
  1566. * that we have no special characters, such as punctuation marks and
  1567. * so on.
  1568. * Basically, we validate the input to be sane.
  1569. * Since closing tags must not have attributes, these assumptions
  1570. * seems to be reasonable enough for our toy parser.
  1571. */
  1572. gint cur_lookahead = 1;
  1573. gint max_lookahead = MIN (end - p, 30);
  1574. bool valid_closing_tag = true;
  1575. if (p + 1 < end && !g_ascii_isalpha (p[1])) {
  1576. valid_closing_tag = false;
  1577. }
  1578. else {
  1579. while (cur_lookahead < max_lookahead) {
  1580. gchar tt = p[cur_lookahead];
  1581. if (tt == '>') {
  1582. break;
  1583. }
  1584. else if (tt < '\n' || tt == ',') {
  1585. valid_closing_tag = false;
  1586. break;
  1587. }
  1588. cur_lookahead ++;
  1589. }
  1590. if (cur_lookahead == max_lookahead) {
  1591. valid_closing_tag = false;
  1592. }
  1593. }
  1594. if (valid_closing_tag) {
  1595. /* Shift back */
  1596. p = c;
  1597. state = tag_begin;
  1598. }
  1599. else {
  1600. p ++;
  1601. state = tag_raw_text;
  1602. }
  1603. }
  1604. else {
  1605. p ++;
  1606. state = tag_raw_text;
  1607. }
  1608. break;
  1609. case sgml_content:
  1610. /* TODO: parse DOCTYPE here */
  1611. if (t == '>') {
  1612. cur_tag->content_offset = p - start + 1;
  1613. state = tag_end_opening;
  1614. }
  1615. else {
  1616. p++;
  1617. }
  1618. break;
  1619. case tag_content:
  1620. html_parse_tag_content(pool, hc, cur_tag, p, content_parser_env);
  1621. if (t == '>') {
  1622. if (closing) {
  1623. cur_tag->closing.start = c - start;
  1624. cur_tag->closing.end = p - start + 1;
  1625. closing = FALSE;
  1626. state = tag_end_closing;
  1627. }
  1628. else {
  1629. cur_tag->content_offset = p - start + 1;
  1630. state = tag_end_opening;
  1631. }
  1632. continue;
  1633. }
  1634. p++;
  1635. break;
  1636. case tag_end_opening:
  1637. content_parser_env.reset();
  1638. state = html_text_content;
  1639. if (cur_tag) {
  1640. if (cur_tag->id == Tag_STYLE || cur_tag->id == Tag_NOSCRIPT || cur_tag->id == Tag_SCRIPT) {
  1641. state = tag_raw_text;
  1642. }
  1643. if (html_document_state == html_document_state::doctype) {
  1644. if (cur_tag->id == Tag_HEAD || (cur_tag->flags & CM_HEAD)) {
  1645. html_document_state = html_document_state::head;
  1646. cur_tag->flags |= FL_IGNORE;
  1647. }
  1648. else if (cur_tag->id != Tag_HTML) {
  1649. html_document_state = html_document_state::body;
  1650. }
  1651. }
  1652. else if (html_document_state == html_document_state::head) {
  1653. if (!(cur_tag->flags & (CM_EMPTY | CM_HEAD))) {
  1654. if (parent_tag && (parent_tag->id == Tag_HEAD || !(parent_tag->flags & CM_HEAD))) {
  1655. /*
  1656. * As by standard, we have to close the HEAD tag
  1657. * and switch to the body state
  1658. */
  1659. parent_tag->flags |= FL_CLOSED;
  1660. parent_tag->closing.start = cur_tag->tag_start;
  1661. parent_tag->closing.end = cur_tag->content_offset;
  1662. html_document_state = html_document_state::body;
  1663. }
  1664. else if (cur_tag->id == Tag_BODY) {
  1665. html_document_state = html_document_state::body;
  1666. }
  1667. else {
  1668. /*
  1669. * For propagation in something like
  1670. * <title><p><a>ololo</a></p></title> - should be unprocessed
  1671. */
  1672. cur_tag->flags |= CM_HEAD;
  1673. }
  1674. }
  1675. }
  1676. process_opening_tag();
  1677. }
  1678. p++;
  1679. c = p;
  1680. break;
  1681. case tag_end_closing: {
  1682. if (cur_tag) {
  1683. if (cur_tag->flags & CM_EMPTY) {
  1684. /* Ignore closing empty tags */
  1685. cur_tag->flags |= FL_IGNORE;
  1686. }
  1687. if (html_document_state == html_document_state::doctype) {
  1688. }
  1689. else if (html_document_state == html_document_state::head) {
  1690. if (cur_tag->id == Tag_HEAD) {
  1691. html_document_state = html_document_state::body;
  1692. }
  1693. }
  1694. /* cur_tag here is a closing tag */
  1695. auto *next_cur_tag = html_check_balance(hc, cur_tag,
  1696. c - start, p - start + 1);
  1697. if (cur_tag->id == Tag_STYLE && allow_css) {
  1698. auto *opening_tag = cur_tag->parent;
  1699. if (opening_tag && opening_tag->id == Tag_STYLE &&
  1700. (int)opening_tag->content_offset < opening_tag->closing.start) {
  1701. auto ret_maybe = rspamd::css::parse_css(pool,
  1702. {start + opening_tag->content_offset,
  1703. opening_tag->closing.start - opening_tag->content_offset},
  1704. std::move(hc->css_style));
  1705. if (!ret_maybe.has_value()) {
  1706. if (ret_maybe.error().is_fatal()) {
  1707. auto err_str = fmt::format(
  1708. "cannot parse css (error code: {}): {}",
  1709. static_cast<int>(ret_maybe.error().type),
  1710. ret_maybe.error().description.value_or("unknown error"));
  1711. msg_info_pool ("%*s", (int) err_str.size(), err_str.data());
  1712. }
  1713. }
  1714. else {
  1715. hc->css_style = ret_maybe.value();
  1716. }
  1717. }
  1718. }
  1719. if (next_cur_tag != nullptr) {
  1720. cur_tag = next_cur_tag;
  1721. }
  1722. else {
  1723. /*
  1724. * Here, we handle cases like <p>lala</b>...
  1725. * So the tag </b> is bogus and unpaired
  1726. * However, we need to exclude it from the output of <p> tag
  1727. * To do that, we create a fake opening tag and insert that to
  1728. * the current opening tag
  1729. */
  1730. auto *cur_opening_tag = cur_tag->parent;
  1731. while (cur_opening_tag && (cur_opening_tag->flags & FL_CLOSED)) {
  1732. cur_opening_tag = cur_opening_tag->parent;
  1733. }
  1734. if (!cur_opening_tag) {
  1735. cur_opening_tag = hc->root_tag;
  1736. }
  1737. auto &&vtag = std::make_unique<html_tag>();
  1738. vtag->id = cur_tag->id;
  1739. vtag->flags = FL_VIRTUAL | FL_CLOSED | cur_tag->flags;
  1740. vtag->tag_start = cur_tag->closing.start;
  1741. vtag->content_offset = p - start + 1;
  1742. vtag->closing = cur_tag->closing;
  1743. vtag->parent = cur_opening_tag;
  1744. g_assert(vtag->parent != &cur_closing_tag);
  1745. cur_opening_tag->children.push_back(vtag.get());
  1746. hc->all_tags.emplace_back(std::move(vtag));
  1747. cur_tag = cur_opening_tag;
  1748. parent_tag = cur_tag->parent;
  1749. g_assert(cur_tag->parent != &cur_closing_tag);
  1750. }
  1751. } /* if cur_tag != nullptr */
  1752. state = html_text_content;
  1753. p++;
  1754. c = p;
  1755. break;
  1756. }
  1757. case tags_limit_overflow:
  1758. msg_warn_pool("tags limit of %d tags is reached at the position %d;"
  1759. " ignoring the rest of the HTML content",
  1760. (int) hc->all_tags.size(), (int) (p - start));
  1761. c = p;
  1762. p = end;
  1763. break;
  1764. }
  1765. }
  1766. if (cur_tag && !(cur_tag->flags & FL_CLOSED) && cur_tag != &cur_closing_tag) {
  1767. cur_closing_tag.parent = cur_tag;
  1768. cur_closing_tag.id = cur_tag->id;
  1769. cur_tag = &cur_closing_tag;
  1770. html_check_balance(hc, cur_tag,
  1771. end - start, end - start);
  1772. }
  1773. /* Propagate styles */
  1774. hc->traverse_block_tags([&hc, &pool](const html_tag *tag) -> bool {
  1775. if (hc->css_style) {
  1776. auto *css_block = hc->css_style->check_tag_block(tag);
  1777. if (css_block) {
  1778. if (tag->block) {
  1779. tag->block->set_block(*css_block);
  1780. }
  1781. else {
  1782. tag->block = css_block;
  1783. }
  1784. }
  1785. }
  1786. if (tag->block) {
  1787. if (!tag->block->has_display()) {
  1788. /* If we have no display field, we can check it by tag */
  1789. if (tag->flags & CM_HEAD) {
  1790. tag->block->set_display(css::css_display_value::DISPLAY_HIDDEN,
  1791. html_block::set);
  1792. }
  1793. else if (tag->flags & (CM_BLOCK | CM_TABLE)) {
  1794. tag->block->set_display(css::css_display_value::DISPLAY_BLOCK,
  1795. html_block::implicit);
  1796. }
  1797. else if (tag->flags & CM_ROW) {
  1798. tag->block->set_display(css::css_display_value::DISPLAY_TABLE_ROW,
  1799. html_block::implicit);
  1800. }
  1801. else {
  1802. tag->block->set_display(css::css_display_value::DISPLAY_INLINE,
  1803. html_block::implicit);
  1804. }
  1805. }
  1806. tag->block->compute_visibility();
  1807. for (const auto *cld_tag : tag->children) {
  1808. if (cld_tag->block) {
  1809. cld_tag->block->propagate_block(*tag->block);
  1810. }
  1811. else {
  1812. cld_tag->block = rspamd_mempool_alloc0_type(pool, html_block);
  1813. *cld_tag->block = *tag->block;
  1814. }
  1815. }
  1816. }
  1817. return true;
  1818. }, html_content::traverse_type::PRE_ORDER);
  1819. /* Leftover before content */
  1820. switch (state) {
  1821. case tag_end_opening:
  1822. if (cur_tag != nullptr) {
  1823. process_opening_tag();
  1824. }
  1825. break;
  1826. default:
  1827. /* Do nothing */
  1828. break;
  1829. }
  1830. if (!hc->all_tags.empty() && hc->root_tag) {
  1831. html_append_tag_content(pool, start, end - start, hc, hc->root_tag,
  1832. exceptions, url_set);
  1833. }
  1834. /* Leftover after content */
  1835. switch (state) {
  1836. case tag_end_opening:
  1837. if (cur_tag != nullptr) {
  1838. process_opening_tag();
  1839. }
  1840. break;
  1841. case tags_limit_overflow:
  1842. html_append_parsed(hc, {c, (std::size_t) (end - c)},
  1843. false, end - start, hc->parsed);
  1844. break;
  1845. default:
  1846. /* Do nothing */
  1847. break;
  1848. }
  1849. if (!hc->parsed.empty()) {
  1850. /* Trim extra spaces at the at the end if needed */
  1851. if (g_ascii_isspace(hc->parsed.back())) {
  1852. auto last_it = std::end(hc->parsed);
  1853. /* Allow last newline */
  1854. if (hc->parsed.back() == '\n') {
  1855. --last_it;
  1856. }
  1857. hc->parsed.erase(std::find_if(hc->parsed.rbegin(), hc->parsed.rend(),
  1858. [](auto ch) -> auto {
  1859. return !g_ascii_isspace(ch);
  1860. }).base(),
  1861. last_it);
  1862. }
  1863. }
  1864. return hc;
  1865. }
  1866. static auto
  1867. html_find_image_by_cid(const html_content &hc, std::string_view cid)
  1868. -> std::optional<const html_image *>
  1869. {
  1870. for (const auto *html_image : hc.images) {
  1871. /* Filter embedded images */
  1872. if (html_image->flags & RSPAMD_HTML_FLAG_IMAGE_EMBEDDED &&
  1873. html_image->src != nullptr) {
  1874. if (cid == html_image->src) {
  1875. return html_image;
  1876. }
  1877. }
  1878. }
  1879. return std::nullopt;
  1880. }
  1881. auto
  1882. html_debug_structure(const html_content &hc) -> std::string
  1883. {
  1884. std::string output;
  1885. if (hc.root_tag) {
  1886. auto rec_functor = [&](const html_tag *t, int level, auto rec_functor) -> void {
  1887. std::string pluses(level, '+');
  1888. if (!(t->flags & (FL_VIRTUAL | FL_IGNORE))) {
  1889. if (t->flags & FL_XML) {
  1890. output += fmt::format("{}xml;", pluses);
  1891. }
  1892. else {
  1893. output += fmt::format("{}{};", pluses,
  1894. html_tags_defs.name_by_id_safe(t->id));
  1895. }
  1896. level++;
  1897. }
  1898. for (const auto *cld : t->children) {
  1899. rec_functor(cld, level, rec_functor);
  1900. }
  1901. };
  1902. rec_functor(hc.root_tag, 1, rec_functor);
  1903. }
  1904. return output;
  1905. }
  1906. auto html_tag_by_name(const std::string_view &name)
  1907. -> std::optional<tag_id_t>
  1908. {
  1909. const auto *td = rspamd::html::html_tags_defs.by_name(name);
  1910. if (td != nullptr) {
  1911. return td->id;
  1912. }
  1913. return std::nullopt;
  1914. }
  1915. auto
  1916. html_tag::get_content(const struct html_content *hc) const -> std::string_view
  1917. {
  1918. const std::string *dest = &hc->parsed;
  1919. if (block && !block->is_visible()) {
  1920. dest = &hc->invisible;
  1921. }
  1922. const auto clen = get_content_length();
  1923. if (content_offset < dest->size()) {
  1924. if (dest->size() - content_offset >= clen) {
  1925. return std::string_view{*dest}.substr(content_offset, clen);
  1926. }
  1927. else {
  1928. return std::string_view{*dest}.substr(content_offset, dest->size() - content_offset);
  1929. }
  1930. }
  1931. return std::string_view{};
  1932. }
  1933. }
  1934. void *
  1935. rspamd_html_process_part_full(rspamd_mempool_t *pool,
  1936. GByteArray *in, GList **exceptions,
  1937. khash_t (rspamd_url_hash) *url_set,
  1938. GPtrArray *part_urls,
  1939. bool allow_css)
  1940. {
  1941. return rspamd::html::html_process_input(pool, in, exceptions, url_set,
  1942. part_urls, allow_css);
  1943. }
  1944. void *
  1945. rspamd_html_process_part(rspamd_mempool_t *pool,
  1946. GByteArray *in)
  1947. {
  1948. return rspamd_html_process_part_full (pool, in, NULL,
  1949. NULL, NULL, FALSE);
  1950. }
  1951. guint
  1952. rspamd_html_decode_entitles_inplace (gchar *s, gsize len)
  1953. {
  1954. return rspamd::html::decode_html_entitles_inplace(s, len);
  1955. }
  1956. gint
  1957. rspamd_html_tag_by_name(const gchar *name)
  1958. {
  1959. const auto *td = rspamd::html::html_tags_defs.by_name(name);
  1960. if (td != nullptr) {
  1961. return td->id;
  1962. }
  1963. return -1;
  1964. }
  1965. gboolean
  1966. rspamd_html_tag_seen(void *ptr, const gchar *tagname)
  1967. {
  1968. gint id;
  1969. auto *hc = rspamd::html::html_content::from_ptr(ptr);
  1970. g_assert (hc != NULL);
  1971. id = rspamd_html_tag_by_name(tagname);
  1972. if (id != -1) {
  1973. return hc->tags_seen[id];
  1974. }
  1975. return FALSE;
  1976. }
  1977. const gchar *
  1978. rspamd_html_tag_by_id(gint id)
  1979. {
  1980. const auto *td = rspamd::html::html_tags_defs.by_id(id);
  1981. if (td != nullptr) {
  1982. return td->name.c_str();
  1983. }
  1984. return nullptr;
  1985. }
  1986. const gchar *
  1987. rspamd_html_tag_name(void *p, gsize *len)
  1988. {
  1989. auto *tag = reinterpret_cast<rspamd::html::html_tag *>(p);
  1990. auto tname = rspamd::html::html_tags_defs.name_by_id_safe(tag->id);
  1991. if (len) {
  1992. *len = tname.size();
  1993. }
  1994. return tname.data();
  1995. }
  1996. struct html_image*
  1997. rspamd_html_find_embedded_image(void *html_content,
  1998. const char *cid, gsize cid_len)
  1999. {
  2000. auto *hc = rspamd::html::html_content::from_ptr(html_content);
  2001. auto maybe_img = rspamd::html::html_find_image_by_cid(*hc, {cid, cid_len});
  2002. if (maybe_img) {
  2003. return (html_image *)maybe_img.value();
  2004. }
  2005. return nullptr;
  2006. }
  2007. bool
  2008. rspamd_html_get_parsed_content(void *html_content, rspamd_ftok_t *dest)
  2009. {
  2010. auto *hc = rspamd::html::html_content::from_ptr(html_content);
  2011. dest->begin = hc->parsed.data();
  2012. dest->len = hc->parsed.size();
  2013. return true;
  2014. }
  2015. gsize
  2016. rspamd_html_get_tags_count(void *html_content)
  2017. {
  2018. auto *hc = rspamd::html::html_content::from_ptr(html_content);
  2019. if (!hc) {
  2020. return 0;
  2021. }
  2022. return hc->all_tags.size();
  2023. }