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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329
  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_unquoted_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((const char *)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. * Attribute 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_unquoted_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_unquoted_value:
  507. if (*in == '>') {
  508. /* That slash was in fact closing tag slash, woohoo */
  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).value_or(nullptr);
  599. if (url) {
  600. if (tag->id != Tag_A) {
  601. /* Mark special tags special */
  602. url->flags |= RSPAMD_URL_FLAG_SPECIAL;
  603. }
  604. if (std::holds_alternative<std::monostate>(tag->extra)) {
  605. tag->extra = url;
  606. }
  607. return url;
  608. }
  609. return std::nullopt;
  610. }
  611. return std::nullopt;
  612. }
  613. struct rspamd_html_url_query_cbd {
  614. rspamd_mempool_t *pool;
  615. khash_t (rspamd_url_hash) *url_set;
  616. struct rspamd_url *url;
  617. GPtrArray *part_urls;
  618. };
  619. static gboolean
  620. html_url_query_callback(struct rspamd_url *url, gsize start_offset,
  621. gsize end_offset, gpointer ud)
  622. {
  623. struct rspamd_html_url_query_cbd *cbd =
  624. (struct rspamd_html_url_query_cbd *) ud;
  625. rspamd_mempool_t *pool;
  626. pool = cbd->pool;
  627. if (url->protocol == PROTOCOL_MAILTO) {
  628. if (url->userlen == 0) {
  629. return FALSE;
  630. }
  631. }
  632. msg_debug_html ("found url %s in query of url"
  633. " %*s", url->string,
  634. cbd->url->querylen, rspamd_url_query_unsafe(cbd->url));
  635. url->flags |= RSPAMD_URL_FLAG_QUERY;
  636. if (rspamd_url_set_add_or_increase(cbd->url_set, url, false)
  637. && cbd->part_urls) {
  638. g_ptr_array_add(cbd->part_urls, url);
  639. }
  640. return TRUE;
  641. }
  642. static void
  643. html_process_query_url(rspamd_mempool_t *pool, struct rspamd_url *url,
  644. khash_t (rspamd_url_hash) *url_set,
  645. GPtrArray *part_urls)
  646. {
  647. if (url->querylen > 0) {
  648. struct rspamd_html_url_query_cbd qcbd;
  649. qcbd.pool = pool;
  650. qcbd.url_set = url_set;
  651. qcbd.url = url;
  652. qcbd.part_urls = part_urls;
  653. rspamd_url_find_multiple(pool,
  654. rspamd_url_query_unsafe (url), url->querylen,
  655. RSPAMD_URL_FIND_ALL, NULL,
  656. html_url_query_callback, &qcbd);
  657. }
  658. if (part_urls) {
  659. g_ptr_array_add(part_urls, url);
  660. }
  661. }
  662. static auto
  663. html_process_data_image(rspamd_mempool_t *pool,
  664. struct html_image *img,
  665. std::string_view input) -> void
  666. {
  667. /*
  668. * Here, we do very basic processing of the data:
  669. * detect if we have something like: `data:image/xxx;base64,yyyzzz==`
  670. * We only parse base64 encoded data.
  671. * We ignore content type so far
  672. */
  673. struct rspamd_image *parsed_image;
  674. const gchar *semicolon_pos = input.data(),
  675. *end = input.data() + input.size();
  676. if ((semicolon_pos = (const gchar *) memchr(semicolon_pos, ';', end - semicolon_pos)) != NULL) {
  677. if (end - semicolon_pos > sizeof("base64,")) {
  678. if (memcmp(semicolon_pos + 1, "base64,", sizeof("base64,") - 1) == 0) {
  679. const gchar *data_pos = semicolon_pos + sizeof("base64,");
  680. gchar *decoded;
  681. gsize encoded_len = end - data_pos, decoded_len;
  682. rspamd_ftok_t inp;
  683. decoded_len = (encoded_len / 4 * 3) + 12;
  684. decoded = rspamd_mempool_alloc_buffer(pool, decoded_len);
  685. rspamd_cryptobox_base64_decode(data_pos, encoded_len,
  686. reinterpret_cast<guchar *>(decoded), &decoded_len);
  687. inp.begin = decoded;
  688. inp.len = decoded_len;
  689. parsed_image = rspamd_maybe_process_image(pool, &inp);
  690. if (parsed_image) {
  691. msg_debug_html ("detected %s image of size %ud x %ud in data url",
  692. rspamd_image_type_str(parsed_image->type),
  693. parsed_image->width, parsed_image->height);
  694. img->embedded_image = parsed_image;
  695. }
  696. }
  697. }
  698. else {
  699. /* Nothing useful */
  700. return;
  701. }
  702. }
  703. }
  704. static void
  705. html_process_img_tag(rspamd_mempool_t *pool,
  706. struct html_tag *tag,
  707. struct html_content *hc,
  708. khash_t (rspamd_url_hash) *url_set,
  709. GPtrArray *part_urls)
  710. {
  711. struct html_image *img;
  712. img = rspamd_mempool_alloc0_type (pool, struct html_image);
  713. img->tag = tag;
  714. for (const auto &param : tag->components) {
  715. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_HREF) {
  716. /* Check base url */
  717. const auto &href_value = param.value;
  718. if (href_value.size() > 0) {
  719. rspamd_ftok_t fstr;
  720. fstr.begin = href_value.data();
  721. fstr.len = href_value.size();
  722. img->src = rspamd_mempool_ftokdup (pool, &fstr);
  723. if (href_value.size() > sizeof("cid:") - 1 && memcmp(href_value.data(),
  724. "cid:", sizeof("cid:") - 1) == 0) {
  725. /* We have an embedded image */
  726. img->src += sizeof("cid:") - 1;
  727. img->flags |= RSPAMD_HTML_FLAG_IMAGE_EMBEDDED;
  728. }
  729. else {
  730. if (href_value.size() > sizeof("data:") - 1 && memcmp(href_value.data(),
  731. "data:", sizeof("data:") - 1) == 0) {
  732. /* We have an embedded image in HTML tag */
  733. img->flags |=
  734. (RSPAMD_HTML_FLAG_IMAGE_EMBEDDED | RSPAMD_HTML_FLAG_IMAGE_DATA);
  735. html_process_data_image(pool, img, href_value);
  736. hc->flags |= RSPAMD_HTML_FLAG_HAS_DATA_URLS;
  737. }
  738. else {
  739. img->flags |= RSPAMD_HTML_FLAG_IMAGE_EXTERNAL;
  740. if (img->src) {
  741. std::string_view cpy{href_value};
  742. auto maybe_url = html_process_url(pool, cpy);
  743. if (maybe_url) {
  744. img->url = maybe_url.value();
  745. struct rspamd_url *existing;
  746. img->url->flags |= RSPAMD_URL_FLAG_IMAGE;
  747. existing = rspamd_url_set_add_or_return(url_set,
  748. img->url);
  749. if (existing && existing != img->url) {
  750. /*
  751. * We have some other URL that could be
  752. * found, e.g. from another part. However,
  753. * we still want to set an image flag on it
  754. */
  755. existing->flags |= img->url->flags;
  756. existing->count++;
  757. }
  758. else if (part_urls) {
  759. /* New url */
  760. g_ptr_array_add(part_urls, img->url);
  761. }
  762. }
  763. }
  764. }
  765. }
  766. }
  767. }
  768. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_HEIGHT) {
  769. unsigned long val;
  770. rspamd_strtoul(param.value.data(), param.value.size(), &val);
  771. img->height = val;
  772. }
  773. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_WIDTH) {
  774. unsigned long val;
  775. rspamd_strtoul(param.value.data(), param.value.size(), &val);
  776. img->width = val;
  777. }
  778. /* TODO: rework to css at some time */
  779. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_STYLE) {
  780. if (img->height == 0) {
  781. auto style_st = param.value;
  782. auto pos = rspamd_substring_search_caseless(style_st.data(),
  783. style_st.size(),
  784. "height", sizeof("height") - 1);
  785. if (pos != -1) {
  786. auto substr = style_st.substr(pos + sizeof("height") - 1);
  787. for (auto i = 0; i < substr.size(); i++) {
  788. auto t = substr[i];
  789. if (g_ascii_isdigit (t)) {
  790. unsigned long val;
  791. rspamd_strtoul(substr.data(),
  792. substr.size(), &val);
  793. img->height = val;
  794. break;
  795. }
  796. else if (!g_ascii_isspace (t) && t != '=' && t != ':') {
  797. /* Fallback */
  798. break;
  799. }
  800. }
  801. }
  802. }
  803. if (img->width == 0) {
  804. auto style_st = param.value;
  805. auto pos = rspamd_substring_search_caseless(style_st.data(),
  806. style_st.size(),
  807. "width", sizeof("width") - 1);
  808. if (pos != -1) {
  809. auto substr = style_st.substr(pos + sizeof("width") - 1);
  810. for (auto i = 0; i < substr.size(); i++) {
  811. auto t = substr[i];
  812. if (g_ascii_isdigit (t)) {
  813. unsigned long val;
  814. rspamd_strtoul(substr.data(),
  815. substr.size(), &val);
  816. img->width = val;
  817. break;
  818. }
  819. else if (!g_ascii_isspace (t) && t != '=' && t != ':') {
  820. /* Fallback */
  821. break;
  822. }
  823. }
  824. }
  825. }
  826. }
  827. }
  828. if (img->embedded_image) {
  829. if (img->height == 0) {
  830. img->height = img->embedded_image->height;
  831. }
  832. if (img->width == 0) {
  833. img->width = img->embedded_image->width;
  834. }
  835. }
  836. hc->images.push_back(img);
  837. if (std::holds_alternative<std::monostate>(tag->extra)) {
  838. tag->extra = img;
  839. }
  840. }
  841. static auto
  842. html_process_link_tag(rspamd_mempool_t *pool, struct html_tag *tag,
  843. struct html_content *hc,
  844. khash_t (rspamd_url_hash) *url_set,
  845. GPtrArray *part_urls) -> void
  846. {
  847. auto found_rel_maybe = tag->find_component(html_component_type::RSPAMD_HTML_COMPONENT_REL);
  848. if (found_rel_maybe) {
  849. if (found_rel_maybe.value() == "icon") {
  850. html_process_img_tag(pool, tag, hc, url_set, part_urls);
  851. }
  852. }
  853. }
  854. static auto
  855. html_process_block_tag(rspamd_mempool_t *pool, struct html_tag *tag,
  856. struct html_content *hc) -> void
  857. {
  858. std::optional<css::css_value> maybe_fgcolor, maybe_bgcolor;
  859. bool hidden = false;
  860. for (const auto &param : tag->components) {
  861. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_COLOR) {
  862. maybe_fgcolor = css::css_value::maybe_color_from_string(param.value);
  863. }
  864. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_BGCOLOR) {
  865. maybe_bgcolor = css::css_value::maybe_color_from_string(param.value);
  866. }
  867. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_STYLE) {
  868. tag->block = rspamd::css::parse_css_declaration(pool, param.value);
  869. }
  870. if (param.type == html_component_type::RSPAMD_HTML_COMPONENT_HIDDEN) {
  871. hidden = true;
  872. }
  873. }
  874. if (!tag->block) {
  875. tag->block = html_block::undefined_html_block_pool(pool);
  876. }
  877. if (hidden) {
  878. tag->block->set_display(false);
  879. }
  880. if (maybe_fgcolor) {
  881. tag->block->set_fgcolor(maybe_fgcolor->to_color().value());
  882. }
  883. if (maybe_bgcolor) {
  884. tag->block->set_bgcolor(maybe_bgcolor->to_color().value());
  885. }
  886. }
  887. static inline auto
  888. html_append_parsed(struct html_content *hc,
  889. std::string_view data,
  890. bool transparent,
  891. std::size_t input_len,
  892. std::string &dest) -> std::size_t
  893. {
  894. auto cur_offset = dest.size();
  895. if (dest.size() > input_len) {
  896. /* Impossible case, refuse to append */
  897. return 0;
  898. }
  899. if (data.size() > 0) {
  900. /* Handle multiple spaces at the begin */
  901. if (cur_offset > 0) {
  902. auto last = dest.back();
  903. if (!g_ascii_isspace(last) && g_ascii_isspace(data.front())) {
  904. dest.append(" ");
  905. data = {data.data() + 1, data.size() - 1};
  906. cur_offset++;
  907. }
  908. }
  909. if (data.find('\0') != std::string_view::npos) {
  910. auto replace_zero_func = [](const auto &input, auto &output) {
  911. const auto last = input.cend();
  912. for (auto it = input.cbegin(); it != last; ++it) {
  913. if (*it == '\0') {
  914. output.append((const char *)u8"\uFFFD");
  915. }
  916. else {
  917. output.push_back(*it);
  918. }
  919. }
  920. };
  921. dest.reserve(dest.size() + data.size() + sizeof(u8"\uFFFD"));
  922. replace_zero_func(data, dest);
  923. hc->flags |= RSPAMD_HTML_FLAG_HAS_ZEROS;
  924. }
  925. else {
  926. dest.append(data);
  927. }
  928. }
  929. auto nlen = decode_html_entitles_inplace(dest.data() + cur_offset,
  930. dest.size() - cur_offset, true);
  931. dest.resize(nlen + cur_offset);
  932. if (transparent) {
  933. /* Replace all visible characters with spaces */
  934. auto start = std::next(dest.begin(), cur_offset);
  935. std::replace_if(start, std::end(dest), [](const auto c) {
  936. return !g_ascii_isspace(c);
  937. }, ' ');
  938. }
  939. return nlen;
  940. }
  941. static auto
  942. html_process_displayed_href_tag(rspamd_mempool_t *pool,
  943. struct html_content *hc,
  944. std::string_view data,
  945. const struct html_tag *cur_tag,
  946. GList **exceptions,
  947. khash_t (rspamd_url_hash) *url_set,
  948. goffset dest_offset) -> void
  949. {
  950. if (std::holds_alternative<rspamd_url *>(cur_tag->extra)) {
  951. auto *url = std::get<rspamd_url *>(cur_tag->extra);
  952. html_check_displayed_url(pool,
  953. exceptions, url_set,
  954. data,
  955. dest_offset,
  956. url);
  957. }
  958. }
  959. static auto
  960. html_append_tag_content(rspamd_mempool_t *pool,
  961. const gchar *start, gsize len,
  962. struct html_content *hc,
  963. html_tag *tag,
  964. GList **exceptions,
  965. khash_t (rspamd_url_hash) *url_set) -> goffset
  966. {
  967. auto is_visible = true, is_block = false, is_spaces = false, is_transparent = false;
  968. goffset next_tag_offset = tag->closing.end,
  969. initial_parsed_offset = hc->parsed.size(),
  970. initial_invisible_offset = hc->invisible.size();
  971. auto calculate_final_tag_offsets = [&]() -> void {
  972. if (is_visible) {
  973. tag->content_offset = initial_parsed_offset;
  974. tag->closing.start = hc->parsed.size();
  975. }
  976. else {
  977. tag->content_offset = initial_invisible_offset;
  978. tag->closing.start = hc->invisible.size();
  979. }
  980. };
  981. if (tag->closing.end == -1) {
  982. if (tag->closing.start != -1) {
  983. next_tag_offset = tag->closing.start;
  984. tag->closing.end = tag->closing.start;
  985. }
  986. else {
  987. next_tag_offset = tag->content_offset;
  988. tag->closing.end = tag->content_offset;
  989. }
  990. }
  991. if (tag->closing.start == -1) {
  992. tag->closing.start = tag->closing.end;
  993. }
  994. auto append_margin = [&](char c) -> void {
  995. /* We do care about visible margins only */
  996. if (is_visible) {
  997. if (!hc->parsed.empty() && hc->parsed.back() != c && hc->parsed.back() != '\n') {
  998. if (hc->parsed.back() == ' ') {
  999. /* We also strip extra spaces at the end, but limiting the start */
  1000. auto last = std::make_reverse_iterator(hc->parsed.begin() + initial_parsed_offset);
  1001. auto first = std::find_if(hc->parsed.rbegin(), last,
  1002. [](auto ch) -> auto {
  1003. return ch != ' ';
  1004. });
  1005. hc->parsed.erase(first.base(), hc->parsed.end());
  1006. g_assert(hc->parsed.size() >= initial_parsed_offset);
  1007. }
  1008. hc->parsed.push_back(c);
  1009. }
  1010. }
  1011. };
  1012. if (tag->id == Tag_BR || tag->id == Tag_HR) {
  1013. if (!(tag->flags & FL_IGNORE)) {
  1014. hc->parsed.append("\n");
  1015. }
  1016. auto ret = tag->content_offset;
  1017. calculate_final_tag_offsets();
  1018. return ret;
  1019. }
  1020. else if ((tag->id == Tag_HEAD && (tag->flags & FL_IGNORE)) || (tag->flags & CM_HEAD)) {
  1021. auto ret = tag->closing.end;
  1022. calculate_final_tag_offsets();
  1023. return ret;
  1024. }
  1025. if ((tag->flags & (FL_COMMENT | FL_XML | FL_IGNORE | CM_HEAD))) {
  1026. is_visible = false;
  1027. }
  1028. else {
  1029. if (!tag->block) {
  1030. is_visible = true;
  1031. }
  1032. else if (!tag->block->is_visible()) {
  1033. if (!tag->block->is_transparent()) {
  1034. is_visible = false;
  1035. }
  1036. else {
  1037. if (tag->block->has_display() &&
  1038. tag->block->display == css::css_display_value::DISPLAY_HIDDEN) {
  1039. is_visible = false;
  1040. }
  1041. else {
  1042. is_transparent = true;
  1043. }
  1044. }
  1045. }
  1046. else {
  1047. if (tag->block->display == css::css_display_value::DISPLAY_BLOCK) {
  1048. is_block = true;
  1049. }
  1050. else if (tag->block->display == css::css_display_value::DISPLAY_TABLE_ROW) {
  1051. is_spaces = true;
  1052. }
  1053. }
  1054. }
  1055. if (is_block) {
  1056. append_margin('\n');
  1057. }
  1058. else if (is_spaces) {
  1059. append_margin(' ');
  1060. }
  1061. goffset cur_offset = tag->content_offset;
  1062. for (auto *cld : tag->children) {
  1063. auto enclosed_start = cld->tag_start;
  1064. goffset initial_part_len = enclosed_start - cur_offset;
  1065. if (initial_part_len > 0) {
  1066. if (is_visible) {
  1067. html_append_parsed(hc,
  1068. {start + cur_offset, std::size_t(initial_part_len)},
  1069. is_transparent, len, hc->parsed);
  1070. }
  1071. else {
  1072. html_append_parsed(hc,
  1073. {start + cur_offset, std::size_t(initial_part_len)},
  1074. is_transparent, len, hc->invisible);
  1075. }
  1076. }
  1077. auto next_offset = html_append_tag_content(pool, start, len,
  1078. hc, cld, exceptions, url_set);
  1079. /* Do not allow shifting back */
  1080. if (next_offset > cur_offset) {
  1081. cur_offset = next_offset;
  1082. }
  1083. }
  1084. if (cur_offset < tag->closing.start) {
  1085. goffset final_part_len = tag->closing.start - cur_offset;
  1086. if (final_part_len > 0) {
  1087. if (is_visible) {
  1088. html_append_parsed(hc,
  1089. {start + cur_offset, std::size_t(final_part_len)},
  1090. is_transparent,
  1091. len,
  1092. hc->parsed);
  1093. }
  1094. else {
  1095. html_append_parsed(hc,
  1096. {start + cur_offset, std::size_t(final_part_len)},
  1097. is_transparent,
  1098. len,
  1099. hc->invisible);
  1100. }
  1101. }
  1102. }
  1103. if (is_block) {
  1104. append_margin('\n');
  1105. }
  1106. else if (is_spaces) {
  1107. append_margin(' ');
  1108. }
  1109. if (is_visible) {
  1110. if (tag->id == Tag_A) {
  1111. auto written_len = hc->parsed.size() - initial_parsed_offset;
  1112. html_process_displayed_href_tag(pool, hc,
  1113. {hc->parsed.data() + initial_parsed_offset, std::size_t(written_len)},
  1114. tag, exceptions,
  1115. url_set, initial_parsed_offset);
  1116. }
  1117. else if (tag->id == Tag_IMG) {
  1118. /* Process ALT if presented */
  1119. auto maybe_alt = tag->find_component(html_component_type::RSPAMD_HTML_COMPONENT_ALT);
  1120. if (maybe_alt) {
  1121. if (!hc->parsed.empty() && !g_ascii_isspace (hc->parsed.back())) {
  1122. /* Add a space */
  1123. hc->parsed += ' ';
  1124. }
  1125. hc->parsed.append(maybe_alt.value());
  1126. if (!hc->parsed.empty() && !g_ascii_isspace (hc->parsed.back())) {
  1127. /* Add a space */
  1128. hc->parsed += ' ';
  1129. }
  1130. }
  1131. }
  1132. }
  1133. else {
  1134. /* Invisible stuff */
  1135. if (std::holds_alternative<rspamd_url *>(tag->extra)) {
  1136. auto *url_enclosed = std::get<rspamd_url *>(tag->extra);
  1137. /*
  1138. * TODO: when hash is fixed to include flags we need to remove and add
  1139. * url to the hash set
  1140. */
  1141. if (url_enclosed) {
  1142. url_enclosed->flags |= RSPAMD_URL_FLAG_INVISIBLE;
  1143. }
  1144. }
  1145. }
  1146. calculate_final_tag_offsets();
  1147. return next_tag_offset;
  1148. }
  1149. auto
  1150. html_process_input(rspamd_mempool_t *pool,
  1151. GByteArray *in,
  1152. GList **exceptions,
  1153. khash_t (rspamd_url_hash) *url_set,
  1154. GPtrArray *part_urls,
  1155. bool allow_css) -> html_content *
  1156. {
  1157. const gchar *p, *c, *end, *start;
  1158. guchar t;
  1159. auto closing = false;
  1160. guint obrace = 0, ebrace = 0;
  1161. struct rspamd_url *url = nullptr;
  1162. gint href_offset = -1;
  1163. struct html_tag *cur_tag = nullptr, *parent_tag = nullptr, cur_closing_tag;
  1164. struct tag_content_parser_state content_parser_env;
  1165. enum {
  1166. parse_start = 0,
  1167. content_before_start,
  1168. tag_begin,
  1169. sgml_tag,
  1170. xml_tag,
  1171. compound_tag,
  1172. comment_tag,
  1173. comment_content,
  1174. sgml_content,
  1175. tag_content,
  1176. tag_end_opening,
  1177. tag_end_closing,
  1178. html_text_content,
  1179. xml_tag_end,
  1180. tag_raw_text,
  1181. tag_raw_text_less_than,
  1182. tags_limit_overflow,
  1183. } state = parse_start;
  1184. enum class html_document_state {
  1185. doctype,
  1186. head,
  1187. body
  1188. } html_document_state = html_document_state::doctype;
  1189. g_assert (in != NULL);
  1190. g_assert (pool != NULL);
  1191. struct html_content *hc = new html_content;
  1192. rspamd_mempool_add_destructor(pool, html_content::html_content_dtor, hc);
  1193. auto new_tag = [&](int flags = 0) -> struct html_tag * {
  1194. if (hc->all_tags.size() > rspamd::html::max_tags) {
  1195. hc->flags |= RSPAMD_HTML_FLAG_TOO_MANY_TAGS;
  1196. return nullptr;
  1197. }
  1198. hc->all_tags.emplace_back(std::make_unique<html_tag>());
  1199. auto *ntag = hc->all_tags.back().get();
  1200. ntag->tag_start = c - start;
  1201. ntag->flags = flags;
  1202. if (cur_tag && !(cur_tag->flags & (CM_EMPTY | FL_CLOSED)) && cur_tag != &cur_closing_tag) {
  1203. parent_tag = cur_tag;
  1204. }
  1205. if (flags & FL_XML) {
  1206. return ntag;
  1207. }
  1208. return ntag;
  1209. };
  1210. auto process_opening_tag = [&]() {
  1211. if (cur_tag->id > Tag_UNKNOWN) {
  1212. if (cur_tag->flags & CM_UNIQUE) {
  1213. if (!hc->tags_seen[cur_tag->id]) {
  1214. /* Duplicate tag has been found */
  1215. hc->flags |= RSPAMD_HTML_FLAG_DUPLICATE_ELEMENTS;
  1216. }
  1217. }
  1218. hc->tags_seen[cur_tag->id] = true;
  1219. }
  1220. /* Shift to the first unclosed tag */
  1221. auto *pt = parent_tag;
  1222. while (pt && (pt->flags & FL_CLOSED)) {
  1223. pt = pt->parent;
  1224. }
  1225. if (pt) {
  1226. g_assert(cur_tag != pt);
  1227. cur_tag->parent = pt;
  1228. g_assert(cur_tag->parent != &cur_closing_tag);
  1229. parent_tag = pt;
  1230. parent_tag->children.push_back(cur_tag);
  1231. }
  1232. else {
  1233. if (hc->root_tag) {
  1234. if (cur_tag != hc->root_tag) {
  1235. cur_tag->parent = hc->root_tag;
  1236. g_assert(cur_tag->parent != cur_tag);
  1237. hc->root_tag->children.push_back(cur_tag);
  1238. parent_tag = hc->root_tag;
  1239. }
  1240. }
  1241. else {
  1242. if (cur_tag->id == Tag_HTML) {
  1243. hc->root_tag = cur_tag;
  1244. }
  1245. else {
  1246. /* Insert a fake html tag */
  1247. hc->all_tags.emplace_back(std::make_unique<html_tag>());
  1248. auto *top_tag = hc->all_tags.back().get();
  1249. top_tag->tag_start = 0;
  1250. top_tag->flags = FL_VIRTUAL;
  1251. top_tag->id = Tag_HTML;
  1252. top_tag->content_offset = 0;
  1253. top_tag->children.push_back(cur_tag);
  1254. cur_tag->parent = top_tag;
  1255. g_assert(cur_tag->parent != cur_tag);
  1256. hc->root_tag = top_tag;
  1257. parent_tag = top_tag;
  1258. }
  1259. }
  1260. }
  1261. if (cur_tag->flags & FL_HREF && html_document_state == html_document_state::body) {
  1262. auto maybe_url = html_process_url_tag(pool, cur_tag, hc);
  1263. if (maybe_url.has_value()) {
  1264. url = maybe_url.value();
  1265. if (url_set != NULL) {
  1266. struct rspamd_url *maybe_existing =
  1267. rspamd_url_set_add_or_return(url_set, maybe_url.value());
  1268. if (maybe_existing == maybe_url.value()) {
  1269. html_process_query_url(pool, url, url_set,
  1270. part_urls);
  1271. }
  1272. else {
  1273. url = maybe_existing;
  1274. /* Replace extra as well */
  1275. cur_tag->extra = maybe_existing;
  1276. /* Increase count to avoid odd checks failure */
  1277. url->count++;
  1278. }
  1279. }
  1280. if (part_urls) {
  1281. g_ptr_array_add(part_urls, url);
  1282. }
  1283. href_offset = hc->parsed.size();
  1284. }
  1285. }
  1286. else if (cur_tag->id == Tag_BASE) {
  1287. /*
  1288. * Base is allowed only within head tag but HTML is retarded
  1289. */
  1290. auto maybe_url = html_process_url_tag(pool, cur_tag, hc);
  1291. if (maybe_url) {
  1292. msg_debug_html ("got valid base tag");
  1293. cur_tag->extra = maybe_url.value();
  1294. cur_tag->flags |= FL_HREF;
  1295. if (hc->base_url == nullptr) {
  1296. hc->base_url = maybe_url.value();
  1297. }
  1298. else {
  1299. msg_debug_html ("ignore redundant base tag");
  1300. }
  1301. }
  1302. else {
  1303. msg_debug_html ("got invalid base tag!");
  1304. }
  1305. }
  1306. if (cur_tag->id == Tag_IMG) {
  1307. html_process_img_tag(pool, cur_tag, hc, url_set,
  1308. part_urls);
  1309. }
  1310. else if (cur_tag->id == Tag_LINK) {
  1311. html_process_link_tag(pool, cur_tag, hc, url_set,
  1312. part_urls);
  1313. }
  1314. if (!(cur_tag->flags & CM_EMPTY)) {
  1315. html_process_block_tag(pool, cur_tag, hc);
  1316. }
  1317. else {
  1318. /* Implicitly close */
  1319. cur_tag->flags |= FL_CLOSED;
  1320. }
  1321. if (cur_tag->flags & FL_CLOSED) {
  1322. cur_tag->closing.end = cur_tag->content_offset;
  1323. cur_tag->closing.start = cur_tag->tag_start;
  1324. cur_tag = parent_tag;
  1325. }
  1326. };
  1327. p = (const char *) in->data;
  1328. c = p;
  1329. end = p + in->len;
  1330. start = c;
  1331. while (p < end) {
  1332. t = *p;
  1333. switch (state) {
  1334. case parse_start:
  1335. if (t == '<') {
  1336. state = tag_begin;
  1337. }
  1338. else {
  1339. /* We have no starting tag, so assume that it's content */
  1340. hc->flags |= RSPAMD_HTML_FLAG_BAD_START;
  1341. cur_tag = new_tag();
  1342. html_document_state = html_document_state::body;
  1343. if (cur_tag) {
  1344. cur_tag->id = Tag_HTML;
  1345. hc->root_tag = cur_tag;
  1346. state = content_before_start;
  1347. }
  1348. else {
  1349. state = tags_limit_overflow;
  1350. }
  1351. }
  1352. break;
  1353. case content_before_start:
  1354. if (t == '<') {
  1355. state = tag_begin;
  1356. }
  1357. else {
  1358. p++;
  1359. }
  1360. break;
  1361. case tag_begin:
  1362. switch (t) {
  1363. case '<':
  1364. c = p;
  1365. p++;
  1366. closing = FALSE;
  1367. break;
  1368. case '!':
  1369. cur_tag = new_tag(FL_XML | FL_CLOSED);
  1370. if (cur_tag) {
  1371. state = sgml_tag;
  1372. }
  1373. else {
  1374. state = tags_limit_overflow;
  1375. }
  1376. p++;
  1377. break;
  1378. case '?':
  1379. cur_tag = new_tag(FL_XML | FL_CLOSED);
  1380. if (cur_tag) {
  1381. state = xml_tag;
  1382. }
  1383. else {
  1384. state = tags_limit_overflow;
  1385. }
  1386. hc->flags |= RSPAMD_HTML_FLAG_XML;
  1387. p++;
  1388. break;
  1389. case '/':
  1390. closing = TRUE;
  1391. /* We fill fake closing tag to fill it with the content parser */
  1392. cur_closing_tag.clear();
  1393. /*
  1394. * For closing tags, we need to find some corresponding opening tag.
  1395. * However, at this point we have not even parsed a name, so we
  1396. * can not assume anything about balancing, etc.
  1397. *
  1398. * So we need to ensure that:
  1399. * 1) We have some opening tag in the chain cur_tag->parent...
  1400. * 2) cur_tag is nullptr - okay, html is just brain damaged
  1401. * 3) cur_tag must NOT be equal to cur_closing tag. It means that
  1402. * we had some poor closing tag but we still need to find an opening
  1403. * tag... Somewhere...
  1404. */
  1405. if (cur_tag == &cur_closing_tag) {
  1406. if (parent_tag != &cur_closing_tag) {
  1407. cur_closing_tag.parent = parent_tag;
  1408. }
  1409. else {
  1410. cur_closing_tag.parent = nullptr;
  1411. }
  1412. }
  1413. else if (cur_tag && cur_tag->flags & FL_CLOSED) {
  1414. /* Cur tag is already closed, we should find something else */
  1415. auto *tmp = cur_tag;
  1416. while (tmp) {
  1417. tmp = tmp->parent;
  1418. if (tmp == nullptr || !(tmp->flags & FL_CLOSED)) {
  1419. break;
  1420. }
  1421. }
  1422. cur_closing_tag.parent = tmp;
  1423. }
  1424. else {
  1425. cur_closing_tag.parent = cur_tag;
  1426. }
  1427. cur_tag = &cur_closing_tag;
  1428. p++;
  1429. break;
  1430. case '>':
  1431. /* Empty tag */
  1432. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  1433. state = html_text_content;
  1434. continue;
  1435. default:
  1436. if (g_ascii_isalpha(t)) {
  1437. state = tag_content;
  1438. content_parser_env.reset();
  1439. if (!closing) {
  1440. cur_tag = new_tag();
  1441. }
  1442. if (cur_tag) {
  1443. state = tag_content;
  1444. }
  1445. else {
  1446. state = tags_limit_overflow;
  1447. }
  1448. }
  1449. else {
  1450. /* Wrong bad tag */
  1451. state = html_text_content;
  1452. }
  1453. break;
  1454. }
  1455. break;
  1456. case sgml_tag:
  1457. switch (t) {
  1458. case '[':
  1459. state = compound_tag;
  1460. obrace = 1;
  1461. ebrace = 0;
  1462. p++;
  1463. break;
  1464. case '-':
  1465. cur_tag->flags |= FL_COMMENT;
  1466. state = comment_tag;
  1467. p++;
  1468. break;
  1469. default:
  1470. state = sgml_content;
  1471. break;
  1472. }
  1473. break;
  1474. case xml_tag:
  1475. if (t == '?') {
  1476. state = xml_tag_end;
  1477. }
  1478. else if (t == '>') {
  1479. /* Misformed xml tag */
  1480. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  1481. state = tag_end_opening;
  1482. continue;
  1483. }
  1484. /* We efficiently ignore xml tags */
  1485. p++;
  1486. break;
  1487. case xml_tag_end:
  1488. if (t == '>') {
  1489. state = tag_end_opening;
  1490. cur_tag->content_offset = p - start + 1;
  1491. continue;
  1492. }
  1493. else {
  1494. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  1495. }
  1496. p++;
  1497. break;
  1498. case compound_tag:
  1499. if (t == '[') {
  1500. obrace++;
  1501. }
  1502. else if (t == ']') {
  1503. ebrace++;
  1504. }
  1505. else if (t == '>' && obrace == ebrace) {
  1506. state = tag_end_opening;
  1507. cur_tag->content_offset = p - start + 1;
  1508. continue;
  1509. }
  1510. p++;
  1511. break;
  1512. case comment_tag:
  1513. if (t != '-') {
  1514. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  1515. state = tag_end_opening;
  1516. }
  1517. else {
  1518. p++;
  1519. ebrace = 0;
  1520. /*
  1521. * https://www.w3.org/TR/2012/WD-html5-20120329/syntax.html#syntax-comments
  1522. * ... the text must not start with a single
  1523. * U+003E GREATER-THAN SIGN character (>),
  1524. * nor start with a "-" (U+002D) character followed by
  1525. * a U+003E GREATER-THAN SIGN (>) character,
  1526. * nor contain two consecutive U+002D HYPHEN-MINUS
  1527. * characters (--), nor end with a "-" (U+002D) character.
  1528. */
  1529. if (p[0] == '-' && p + 1 < end && p[1] == '>') {
  1530. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  1531. p++;
  1532. state = tag_end_opening;
  1533. }
  1534. else if (*p == '>') {
  1535. hc->flags |= RSPAMD_HTML_FLAG_BAD_ELEMENTS;
  1536. state = tag_end_opening;
  1537. }
  1538. else {
  1539. state = comment_content;
  1540. }
  1541. }
  1542. break;
  1543. case comment_content:
  1544. if (t == '-') {
  1545. ebrace++;
  1546. }
  1547. else if (t == '>' && ebrace >= 2) {
  1548. cur_tag->content_offset = p - start + 1;
  1549. state = tag_end_opening;
  1550. continue;
  1551. }
  1552. else {
  1553. ebrace = 0;
  1554. }
  1555. p++;
  1556. break;
  1557. case html_text_content:
  1558. if (t != '<') {
  1559. p++;
  1560. }
  1561. else {
  1562. state = tag_begin;
  1563. }
  1564. break;
  1565. case tag_raw_text:
  1566. if (t == '<') {
  1567. c = p;
  1568. state = tag_raw_text_less_than;
  1569. }
  1570. p ++;
  1571. break;
  1572. case tag_raw_text_less_than:
  1573. if (t == '/') {
  1574. /* Here are special things: we look for obrace and then ensure
  1575. * that if there is any closing brace nearby
  1576. * (we look maximum at 30 characters). We also need to ensure
  1577. * that we have no special characters, such as punctuation marks and
  1578. * so on.
  1579. * Basically, we validate the input to be sane.
  1580. * Since closing tags must not have attributes, these assumptions
  1581. * seems to be reasonable enough for our toy parser.
  1582. */
  1583. gint cur_lookahead = 1;
  1584. gint max_lookahead = MIN (end - p, 30);
  1585. bool valid_closing_tag = true;
  1586. if (p + 1 < end && !g_ascii_isalpha (p[1])) {
  1587. valid_closing_tag = false;
  1588. }
  1589. else {
  1590. while (cur_lookahead < max_lookahead) {
  1591. gchar tt = p[cur_lookahead];
  1592. if (tt == '>') {
  1593. break;
  1594. }
  1595. else if (tt < '\n' || tt == ',') {
  1596. valid_closing_tag = false;
  1597. break;
  1598. }
  1599. cur_lookahead ++;
  1600. }
  1601. if (cur_lookahead == max_lookahead) {
  1602. valid_closing_tag = false;
  1603. }
  1604. }
  1605. if (valid_closing_tag) {
  1606. /* Shift back */
  1607. p = c;
  1608. state = tag_begin;
  1609. }
  1610. else {
  1611. p ++;
  1612. state = tag_raw_text;
  1613. }
  1614. }
  1615. else {
  1616. p ++;
  1617. state = tag_raw_text;
  1618. }
  1619. break;
  1620. case sgml_content:
  1621. /* TODO: parse DOCTYPE here */
  1622. if (t == '>') {
  1623. cur_tag->content_offset = p - start + 1;
  1624. state = tag_end_opening;
  1625. }
  1626. else {
  1627. p++;
  1628. }
  1629. break;
  1630. case tag_content:
  1631. html_parse_tag_content(pool, hc, cur_tag, p, content_parser_env);
  1632. if (t == '>') {
  1633. if (closing) {
  1634. cur_tag->closing.start = c - start;
  1635. cur_tag->closing.end = p - start + 1;
  1636. closing = FALSE;
  1637. state = tag_end_closing;
  1638. }
  1639. else {
  1640. cur_tag->content_offset = p - start + 1;
  1641. state = tag_end_opening;
  1642. }
  1643. continue;
  1644. }
  1645. p++;
  1646. break;
  1647. case tag_end_opening:
  1648. content_parser_env.reset();
  1649. state = html_text_content;
  1650. if (cur_tag) {
  1651. if (cur_tag->id == Tag_STYLE || cur_tag->id == Tag_NOSCRIPT || cur_tag->id == Tag_SCRIPT) {
  1652. state = tag_raw_text;
  1653. }
  1654. if (html_document_state == html_document_state::doctype) {
  1655. if (cur_tag->id == Tag_HEAD || (cur_tag->flags & CM_HEAD)) {
  1656. html_document_state = html_document_state::head;
  1657. cur_tag->flags |= FL_IGNORE;
  1658. }
  1659. else if (cur_tag->id != Tag_HTML) {
  1660. html_document_state = html_document_state::body;
  1661. }
  1662. }
  1663. else if (html_document_state == html_document_state::head) {
  1664. if (!(cur_tag->flags & (CM_EMPTY | CM_HEAD))) {
  1665. if (parent_tag && (parent_tag->id == Tag_HEAD || !(parent_tag->flags & CM_HEAD))) {
  1666. /*
  1667. * As by standard, we have to close the HEAD tag
  1668. * and switch to the body state
  1669. */
  1670. parent_tag->flags |= FL_CLOSED;
  1671. parent_tag->closing.start = cur_tag->tag_start;
  1672. parent_tag->closing.end = cur_tag->content_offset;
  1673. html_document_state = html_document_state::body;
  1674. }
  1675. else if (cur_tag->id == Tag_BODY) {
  1676. html_document_state = html_document_state::body;
  1677. }
  1678. else {
  1679. /*
  1680. * For propagation in something like
  1681. * <title><p><a>ololo</a></p></title> - should be unprocessed
  1682. */
  1683. cur_tag->flags |= CM_HEAD;
  1684. }
  1685. }
  1686. }
  1687. process_opening_tag();
  1688. }
  1689. p++;
  1690. c = p;
  1691. break;
  1692. case tag_end_closing: {
  1693. if (cur_tag) {
  1694. if (cur_tag->flags & CM_EMPTY) {
  1695. /* Ignore closing empty tags */
  1696. cur_tag->flags |= FL_IGNORE;
  1697. }
  1698. if (html_document_state == html_document_state::doctype) {
  1699. }
  1700. else if (html_document_state == html_document_state::head) {
  1701. if (cur_tag->id == Tag_HEAD) {
  1702. html_document_state = html_document_state::body;
  1703. }
  1704. }
  1705. /* cur_tag here is a closing tag */
  1706. auto *next_cur_tag = html_check_balance(hc, cur_tag,
  1707. c - start, p - start + 1);
  1708. if (cur_tag->id == Tag_STYLE && allow_css) {
  1709. auto *opening_tag = cur_tag->parent;
  1710. if (opening_tag && opening_tag->id == Tag_STYLE &&
  1711. (int)opening_tag->content_offset < opening_tag->closing.start) {
  1712. auto ret_maybe = rspamd::css::parse_css(pool,
  1713. {start + opening_tag->content_offset,
  1714. opening_tag->closing.start - opening_tag->content_offset},
  1715. std::move(hc->css_style));
  1716. if (!ret_maybe.has_value()) {
  1717. if (ret_maybe.error().is_fatal()) {
  1718. auto err_str = fmt::format(
  1719. "cannot parse css (error code: {}): {}",
  1720. static_cast<int>(ret_maybe.error().type),
  1721. ret_maybe.error().description.value_or("unknown error"));
  1722. msg_info_pool ("%*s", (int) err_str.size(), err_str.data());
  1723. }
  1724. }
  1725. else {
  1726. hc->css_style = ret_maybe.value();
  1727. }
  1728. }
  1729. }
  1730. if (next_cur_tag != nullptr) {
  1731. cur_tag = next_cur_tag;
  1732. }
  1733. else {
  1734. /*
  1735. * Here, we handle cases like <p>lala</b>...
  1736. * So the tag </b> is bogus and unpaired
  1737. * However, we need to exclude it from the output of <p> tag
  1738. * To do that, we create a fake opening tag and insert that to
  1739. * the current opening tag
  1740. */
  1741. auto *cur_opening_tag = cur_tag->parent;
  1742. while (cur_opening_tag && (cur_opening_tag->flags & FL_CLOSED)) {
  1743. cur_opening_tag = cur_opening_tag->parent;
  1744. }
  1745. if (!cur_opening_tag) {
  1746. cur_opening_tag = hc->root_tag;
  1747. }
  1748. auto &&vtag = std::make_unique<html_tag>();
  1749. vtag->id = cur_tag->id;
  1750. vtag->flags = FL_VIRTUAL | FL_CLOSED | cur_tag->flags;
  1751. vtag->tag_start = cur_tag->closing.start;
  1752. vtag->content_offset = p - start + 1;
  1753. vtag->closing = cur_tag->closing;
  1754. vtag->parent = cur_opening_tag;
  1755. g_assert(vtag->parent != &cur_closing_tag);
  1756. cur_opening_tag->children.push_back(vtag.get());
  1757. hc->all_tags.emplace_back(std::move(vtag));
  1758. cur_tag = cur_opening_tag;
  1759. parent_tag = cur_tag->parent;
  1760. g_assert(cur_tag->parent != &cur_closing_tag);
  1761. }
  1762. } /* if cur_tag != nullptr */
  1763. state = html_text_content;
  1764. p++;
  1765. c = p;
  1766. break;
  1767. }
  1768. case tags_limit_overflow:
  1769. msg_warn_pool("tags limit of %d tags is reached at the position %d;"
  1770. " ignoring the rest of the HTML content",
  1771. (int) hc->all_tags.size(), (int) (p - start));
  1772. c = p;
  1773. p = end;
  1774. break;
  1775. }
  1776. }
  1777. if (cur_tag && !(cur_tag->flags & FL_CLOSED) && cur_tag != &cur_closing_tag) {
  1778. cur_closing_tag.parent = cur_tag;
  1779. cur_closing_tag.id = cur_tag->id;
  1780. cur_tag = &cur_closing_tag;
  1781. html_check_balance(hc, cur_tag,
  1782. end - start, end - start);
  1783. }
  1784. /* Propagate styles */
  1785. hc->traverse_block_tags([&hc, &pool](const html_tag *tag) -> bool {
  1786. if (hc->css_style && tag->id > Tag_UNKNOWN && tag->id < Tag_MAX) {
  1787. auto *css_block = hc->css_style->check_tag_block(tag);
  1788. if (css_block) {
  1789. if (tag->block) {
  1790. tag->block->set_block(*css_block);
  1791. }
  1792. else {
  1793. tag->block = css_block;
  1794. }
  1795. }
  1796. }
  1797. if (tag->block) {
  1798. if (!tag->block->has_display()) {
  1799. /* If we have no display field, we can check it by tag */
  1800. if (tag->flags & CM_HEAD) {
  1801. tag->block->set_display(css::css_display_value::DISPLAY_HIDDEN,
  1802. html_block::set);
  1803. }
  1804. else if (tag->flags & (CM_BLOCK | CM_TABLE)) {
  1805. tag->block->set_display(css::css_display_value::DISPLAY_BLOCK,
  1806. html_block::implicit);
  1807. }
  1808. else if (tag->flags & CM_ROW) {
  1809. tag->block->set_display(css::css_display_value::DISPLAY_TABLE_ROW,
  1810. html_block::implicit);
  1811. }
  1812. else {
  1813. tag->block->set_display(css::css_display_value::DISPLAY_INLINE,
  1814. html_block::implicit);
  1815. }
  1816. }
  1817. tag->block->compute_visibility();
  1818. for (const auto *cld_tag : tag->children) {
  1819. if (cld_tag->block) {
  1820. cld_tag->block->propagate_block(*tag->block);
  1821. }
  1822. else {
  1823. cld_tag->block = rspamd_mempool_alloc0_type(pool, html_block);
  1824. *cld_tag->block = *tag->block;
  1825. }
  1826. }
  1827. }
  1828. return true;
  1829. }, html_content::traverse_type::PRE_ORDER);
  1830. /* Leftover before content */
  1831. switch (state) {
  1832. case tag_end_opening:
  1833. if (cur_tag != nullptr) {
  1834. process_opening_tag();
  1835. }
  1836. break;
  1837. default:
  1838. /* Do nothing */
  1839. break;
  1840. }
  1841. if (!hc->all_tags.empty() && hc->root_tag) {
  1842. html_append_tag_content(pool, start, end - start, hc, hc->root_tag,
  1843. exceptions, url_set);
  1844. }
  1845. /* Leftover after content */
  1846. switch (state) {
  1847. case tags_limit_overflow:
  1848. html_append_parsed(hc, {c, (std::size_t) (end - c)},
  1849. false, end - start, hc->parsed);
  1850. break;
  1851. default:
  1852. /* Do nothing */
  1853. break;
  1854. }
  1855. if (!hc->parsed.empty()) {
  1856. /* Trim extra spaces at the at the end if needed */
  1857. if (g_ascii_isspace(hc->parsed.back())) {
  1858. auto last_it = std::end(hc->parsed);
  1859. /* Allow last newline */
  1860. if (hc->parsed.back() == '\n') {
  1861. --last_it;
  1862. }
  1863. hc->parsed.erase(std::find_if(hc->parsed.rbegin(), hc->parsed.rend(),
  1864. [](auto ch) -> auto {
  1865. return !g_ascii_isspace(ch);
  1866. }).base(),
  1867. last_it);
  1868. }
  1869. }
  1870. return hc;
  1871. }
  1872. static auto
  1873. html_find_image_by_cid(const html_content &hc, std::string_view cid)
  1874. -> std::optional<const html_image *>
  1875. {
  1876. for (const auto *html_image : hc.images) {
  1877. /* Filter embedded images */
  1878. if (html_image->flags & RSPAMD_HTML_FLAG_IMAGE_EMBEDDED &&
  1879. html_image->src != nullptr) {
  1880. if (cid == html_image->src) {
  1881. return html_image;
  1882. }
  1883. }
  1884. }
  1885. return std::nullopt;
  1886. }
  1887. auto
  1888. html_debug_structure(const html_content &hc) -> std::string
  1889. {
  1890. std::string output;
  1891. if (hc.root_tag) {
  1892. auto rec_functor = [&](const html_tag *t, int level, auto rec_functor) -> void {
  1893. std::string pluses(level, '+');
  1894. if (!(t->flags & (FL_VIRTUAL | FL_IGNORE))) {
  1895. if (t->flags & FL_XML) {
  1896. output += fmt::format("{}xml;", pluses);
  1897. }
  1898. else {
  1899. output += fmt::format("{}{};", pluses,
  1900. html_tags_defs.name_by_id_safe(t->id));
  1901. }
  1902. level++;
  1903. }
  1904. for (const auto *cld : t->children) {
  1905. rec_functor(cld, level, rec_functor);
  1906. }
  1907. };
  1908. rec_functor(hc.root_tag, 1, rec_functor);
  1909. }
  1910. return output;
  1911. }
  1912. auto html_tag_by_name(const std::string_view &name)
  1913. -> std::optional<tag_id_t>
  1914. {
  1915. const auto *td = rspamd::html::html_tags_defs.by_name(name);
  1916. if (td != nullptr) {
  1917. return td->id;
  1918. }
  1919. return std::nullopt;
  1920. }
  1921. auto
  1922. html_tag::get_content(const struct html_content *hc) const -> std::string_view
  1923. {
  1924. const std::string *dest = &hc->parsed;
  1925. if (block && !block->is_visible()) {
  1926. dest = &hc->invisible;
  1927. }
  1928. const auto clen = get_content_length();
  1929. if (content_offset < dest->size()) {
  1930. if (dest->size() - content_offset >= clen) {
  1931. return std::string_view{*dest}.substr(content_offset, clen);
  1932. }
  1933. else {
  1934. return std::string_view{*dest}.substr(content_offset, dest->size() - content_offset);
  1935. }
  1936. }
  1937. return std::string_view{};
  1938. }
  1939. }
  1940. void *
  1941. rspamd_html_process_part_full(rspamd_mempool_t *pool,
  1942. GByteArray *in, GList **exceptions,
  1943. khash_t (rspamd_url_hash) *url_set,
  1944. GPtrArray *part_urls,
  1945. bool allow_css)
  1946. {
  1947. return rspamd::html::html_process_input(pool, in, exceptions, url_set,
  1948. part_urls, allow_css);
  1949. }
  1950. void *
  1951. rspamd_html_process_part(rspamd_mempool_t *pool,
  1952. GByteArray *in)
  1953. {
  1954. return rspamd_html_process_part_full (pool, in, NULL,
  1955. NULL, NULL, FALSE);
  1956. }
  1957. guint
  1958. rspamd_html_decode_entitles_inplace (gchar *s, gsize len)
  1959. {
  1960. return rspamd::html::decode_html_entitles_inplace(s, len);
  1961. }
  1962. gint
  1963. rspamd_html_tag_by_name(const gchar *name)
  1964. {
  1965. const auto *td = rspamd::html::html_tags_defs.by_name(name);
  1966. if (td != nullptr) {
  1967. return td->id;
  1968. }
  1969. return -1;
  1970. }
  1971. gboolean
  1972. rspamd_html_tag_seen(void *ptr, const gchar *tagname)
  1973. {
  1974. gint id;
  1975. auto *hc = rspamd::html::html_content::from_ptr(ptr);
  1976. g_assert (hc != NULL);
  1977. id = rspamd_html_tag_by_name(tagname);
  1978. if (id != -1) {
  1979. return hc->tags_seen[id];
  1980. }
  1981. return FALSE;
  1982. }
  1983. const gchar *
  1984. rspamd_html_tag_by_id(gint id)
  1985. {
  1986. if (id > Tag_UNKNOWN && id < Tag_MAX) {
  1987. const auto *td = rspamd::html::html_tags_defs.by_id(id);
  1988. if (td != nullptr) {
  1989. return td->name.c_str();
  1990. }
  1991. }
  1992. return nullptr;
  1993. }
  1994. const gchar *
  1995. rspamd_html_tag_name(void *p, gsize *len)
  1996. {
  1997. auto *tag = reinterpret_cast<rspamd::html::html_tag *>(p);
  1998. auto tname = rspamd::html::html_tags_defs.name_by_id_safe(tag->id);
  1999. if (len) {
  2000. *len = tname.size();
  2001. }
  2002. return tname.data();
  2003. }
  2004. struct html_image*
  2005. rspamd_html_find_embedded_image(void *html_content,
  2006. const char *cid, gsize cid_len)
  2007. {
  2008. auto *hc = rspamd::html::html_content::from_ptr(html_content);
  2009. auto maybe_img = rspamd::html::html_find_image_by_cid(*hc, {cid, cid_len});
  2010. if (maybe_img) {
  2011. return (html_image *)maybe_img.value();
  2012. }
  2013. return nullptr;
  2014. }
  2015. bool
  2016. rspamd_html_get_parsed_content(void *html_content, rspamd_ftok_t *dest)
  2017. {
  2018. auto *hc = rspamd::html::html_content::from_ptr(html_content);
  2019. dest->begin = hc->parsed.data();
  2020. dest->len = hc->parsed.size();
  2021. return true;
  2022. }
  2023. gsize
  2024. rspamd_html_get_tags_count(void *html_content)
  2025. {
  2026. auto *hc = rspamd::html::html_content::from_ptr(html_content);
  2027. if (!hc) {
  2028. return 0;
  2029. }
  2030. return hc->all_tags.size();
  2031. }