您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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