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.

http_connection.c 58KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436
  1. /*-
  2. * Copyright 2016 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 "http_connection.h"
  18. #include "http_private.h"
  19. #include "http_message.h"
  20. #include "utlist.h"
  21. #include "util.h"
  22. #include "printf.h"
  23. #include "logger.h"
  24. #include "ref.h"
  25. #include "ottery.h"
  26. #include "keypair_private.h"
  27. #include "cryptobox.h"
  28. #include "libutil/ssl_util.h"
  29. #include "libserver/url.h"
  30. #include "contrib/mumhash/mum.h"
  31. #include "contrib/http-parser/http_parser.h"
  32. #include "unix-std.h"
  33. #include <openssl/err.h>
  34. #define ENCRYPTED_VERSION " HTTP/1.0"
  35. struct _rspamd_http_privbuf {
  36. rspamd_fstring_t *data;
  37. const gchar *zc_buf;
  38. gsize zc_remain;
  39. ref_entry_t ref;
  40. };
  41. enum rspamd_http_priv_flags {
  42. RSPAMD_HTTP_CONN_FLAG_ENCRYPTED = 1 << 0,
  43. RSPAMD_HTTP_CONN_FLAG_NEW_HEADER = 1 << 1,
  44. RSPAMD_HTTP_CONN_FLAG_RESETED = 1 << 2,
  45. RSPAMD_HTTP_CONN_FLAG_TOO_LARGE = 1 << 3,
  46. RSPAMD_HTTP_CONN_FLAG_ENCRYPTION_NEEDED = 1 << 4,
  47. };
  48. #define IS_CONN_ENCRYPTED(c) ((c)->flags & RSPAMD_HTTP_CONN_FLAG_ENCRYPTED)
  49. #define IS_CONN_RESETED(c) ((c)->flags & RSPAMD_HTTP_CONN_FLAG_RESETED)
  50. struct rspamd_http_connection_private {
  51. struct rspamd_http_context *ctx;
  52. struct rspamd_ssl_connection *ssl;
  53. struct _rspamd_http_privbuf *buf;
  54. struct rspamd_keypair_cache *cache;
  55. struct rspamd_cryptobox_pubkey *peer_key;
  56. struct rspamd_cryptobox_keypair *local_key;
  57. struct rspamd_http_header *header;
  58. struct http_parser parser;
  59. struct http_parser_settings parser_cb;
  60. struct event ev;
  61. struct timeval tv;
  62. struct timeval *ptv;
  63. struct rspamd_http_message *msg;
  64. struct iovec *out;
  65. guint outlen;
  66. enum rspamd_http_priv_flags flags;
  67. gsize wr_pos;
  68. gsize wr_total;
  69. };
  70. static const rspamd_ftok_t key_header = {
  71. .begin = "Key",
  72. .len = 3
  73. };
  74. static const rspamd_ftok_t date_header = {
  75. .begin = "Date",
  76. .len = 4
  77. };
  78. static const rspamd_ftok_t last_modified_header = {
  79. .begin = "Last-Modified",
  80. .len = 13
  81. };
  82. #define HTTP_ERROR http_error_quark ()
  83. GQuark
  84. http_error_quark (void)
  85. {
  86. return g_quark_from_static_string ("http-error-quark");
  87. }
  88. static void
  89. rspamd_http_privbuf_dtor (gpointer ud)
  90. {
  91. struct _rspamd_http_privbuf *p = (struct _rspamd_http_privbuf *)ud;
  92. if (p->data) {
  93. rspamd_fstring_free (p->data);
  94. }
  95. g_free (p);
  96. }
  97. static const gchar *
  98. rspamd_http_code_to_str (gint code)
  99. {
  100. if (code == 200) {
  101. return "OK";
  102. }
  103. else if (code == 404) {
  104. return "Not found";
  105. }
  106. else if (code == 403 || code == 401) {
  107. return "Not authorized";
  108. }
  109. else if (code >= 400 && code < 500) {
  110. return "Bad request";
  111. }
  112. else if (code >= 300 && code < 400) {
  113. return "See Other";
  114. }
  115. else if (code >= 500 && code < 600) {
  116. return "Internal server error";
  117. }
  118. return "Unknown error";
  119. }
  120. static void
  121. rspamd_http_parse_key (rspamd_ftok_t *data, struct rspamd_http_connection *conn,
  122. struct rspamd_http_connection_private *priv)
  123. {
  124. guchar *decoded_id;
  125. const gchar *eq_pos;
  126. gsize id_len;
  127. struct rspamd_cryptobox_pubkey *pk;
  128. if (priv->local_key == NULL) {
  129. /* In this case we cannot do anything, e.g. we cannot decrypt payload */
  130. priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_ENCRYPTED;
  131. }
  132. else {
  133. /* Check sanity of what we have */
  134. eq_pos = memchr (data->begin, '=', data->len);
  135. if (eq_pos != NULL) {
  136. decoded_id = rspamd_decode_base32 (data->begin, eq_pos - data->begin,
  137. &id_len);
  138. if (decoded_id != NULL && id_len >= RSPAMD_KEYPAIR_SHORT_ID_LEN) {
  139. pk = rspamd_pubkey_from_base32 (eq_pos + 1,
  140. data->begin + data->len - eq_pos - 1,
  141. RSPAMD_KEYPAIR_KEX,
  142. RSPAMD_CRYPTOBOX_MODE_25519);
  143. if (pk != NULL) {
  144. if (memcmp (rspamd_keypair_get_id (priv->local_key),
  145. decoded_id,
  146. RSPAMD_KEYPAIR_SHORT_ID_LEN) == 0) {
  147. priv->msg->peer_key = pk;
  148. if (priv->cache && priv->msg->peer_key) {
  149. rspamd_keypair_cache_process (priv->cache,
  150. priv->local_key,
  151. priv->msg->peer_key);
  152. }
  153. }
  154. else {
  155. rspamd_pubkey_unref (pk);
  156. }
  157. }
  158. }
  159. priv->flags |= RSPAMD_HTTP_CONN_FLAG_ENCRYPTED;
  160. g_free (decoded_id);
  161. }
  162. }
  163. }
  164. static inline void
  165. rspamd_http_check_special_header (struct rspamd_http_connection *conn,
  166. struct rspamd_http_connection_private *priv)
  167. {
  168. if (rspamd_ftok_casecmp (&priv->header->name, &date_header) == 0) {
  169. priv->msg->date = rspamd_http_parse_date (priv->header->value.begin,
  170. priv->header->value.len);
  171. }
  172. else if (rspamd_ftok_casecmp (&priv->header->name, &key_header) == 0) {
  173. rspamd_http_parse_key (&priv->header->value, conn, priv);
  174. }
  175. else if (rspamd_ftok_casecmp (&priv->header->name, &last_modified_header) == 0) {
  176. priv->msg->last_modified = rspamd_http_parse_date (
  177. priv->header->value.begin,
  178. priv->header->value.len);
  179. }
  180. }
  181. static gint
  182. rspamd_http_on_url (http_parser * parser, const gchar *at, size_t length)
  183. {
  184. struct rspamd_http_connection *conn =
  185. (struct rspamd_http_connection *)parser->data;
  186. struct rspamd_http_connection_private *priv;
  187. priv = conn->priv;
  188. priv->msg->url = rspamd_fstring_append (priv->msg->url, at, length);
  189. return 0;
  190. }
  191. static gint
  192. rspamd_http_on_status (http_parser * parser, const gchar *at, size_t length)
  193. {
  194. struct rspamd_http_connection *conn =
  195. (struct rspamd_http_connection *)parser->data;
  196. struct rspamd_http_connection_private *priv;
  197. priv = conn->priv;
  198. if (parser->status_code != 200) {
  199. if (priv->msg->status == NULL) {
  200. priv->msg->status = rspamd_fstring_new ();
  201. }
  202. priv->msg->status = rspamd_fstring_append (priv->msg->status, at, length);
  203. }
  204. return 0;
  205. }
  206. static void
  207. rspamd_http_finish_header (struct rspamd_http_connection *conn,
  208. struct rspamd_http_connection_private *priv)
  209. {
  210. struct rspamd_http_header *hdr;
  211. priv->header->combined = rspamd_fstring_append (priv->header->combined,
  212. "\r\n", 2);
  213. priv->header->value.len = priv->header->combined->len -
  214. priv->header->name.len - 4;
  215. priv->header->value.begin = priv->header->combined->str +
  216. priv->header->name.len + 2;
  217. priv->header->name.begin = priv->header->combined->str;
  218. HASH_FIND (hh, priv->msg->headers, priv->header->name.begin,
  219. priv->header->name.len, hdr);
  220. if (hdr == NULL) {
  221. HASH_ADD_KEYPTR (hh, priv->msg->headers, priv->header->name.begin,
  222. priv->header->name.len, priv->header);
  223. }
  224. DL_APPEND (hdr, priv->header);
  225. rspamd_http_check_special_header (conn, priv);
  226. }
  227. static void
  228. rspamd_http_init_header (struct rspamd_http_connection_private *priv)
  229. {
  230. priv->header = g_malloc0 (sizeof (struct rspamd_http_header));
  231. priv->header->combined = rspamd_fstring_new ();
  232. }
  233. static gint
  234. rspamd_http_on_header_field (http_parser * parser,
  235. const gchar *at,
  236. size_t length)
  237. {
  238. struct rspamd_http_connection *conn =
  239. (struct rspamd_http_connection *)parser->data;
  240. struct rspamd_http_connection_private *priv;
  241. priv = conn->priv;
  242. if (priv->header == NULL) {
  243. rspamd_http_init_header (priv);
  244. }
  245. else if (priv->flags & RSPAMD_HTTP_CONN_FLAG_NEW_HEADER) {
  246. rspamd_http_finish_header (conn, priv);
  247. rspamd_http_init_header (priv);
  248. }
  249. priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_NEW_HEADER;
  250. priv->header->combined = rspamd_fstring_append (priv->header->combined,
  251. at, length);
  252. return 0;
  253. }
  254. static gint
  255. rspamd_http_on_header_value (http_parser * parser,
  256. const gchar *at,
  257. size_t length)
  258. {
  259. struct rspamd_http_connection *conn =
  260. (struct rspamd_http_connection *)parser->data;
  261. struct rspamd_http_connection_private *priv;
  262. priv = conn->priv;
  263. if (priv->header == NULL) {
  264. /* Should not happen */
  265. return -1;
  266. }
  267. if (!(priv->flags & RSPAMD_HTTP_CONN_FLAG_NEW_HEADER)) {
  268. priv->flags |= RSPAMD_HTTP_CONN_FLAG_NEW_HEADER;
  269. priv->header->combined = rspamd_fstring_append (priv->header->combined,
  270. ": ", 2);
  271. priv->header->name.len = priv->header->combined->len - 2;
  272. }
  273. priv->header->combined = rspamd_fstring_append (priv->header->combined,
  274. at, length);
  275. return 0;
  276. }
  277. static int
  278. rspamd_http_on_headers_complete (http_parser * parser)
  279. {
  280. struct rspamd_http_connection *conn =
  281. (struct rspamd_http_connection *)parser->data;
  282. struct rspamd_http_connection_private *priv;
  283. struct rspamd_http_message *msg;
  284. int ret;
  285. priv = conn->priv;
  286. msg = priv->msg;
  287. if (priv->header != NULL) {
  288. rspamd_http_finish_header (conn, priv);
  289. priv->header = NULL;
  290. priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_NEW_HEADER;
  291. }
  292. if (msg->method == HTTP_HEAD) {
  293. /* We don't care about the rest */
  294. if (rspamd_event_pending (&priv->ev, EV_READ)) {
  295. event_del (&priv->ev);
  296. }
  297. msg->code = parser->status_code;
  298. rspamd_http_connection_ref (conn);
  299. ret = conn->finish_handler (conn, msg);
  300. if (conn->opts & RSPAMD_HTTP_CLIENT_KEEP_ALIVE) {
  301. rspamd_http_context_push_keepalive (conn->priv->ctx, conn,
  302. msg, conn->priv->ctx->ev_base);
  303. rspamd_http_connection_reset (conn);
  304. }
  305. else {
  306. conn->finished = TRUE;
  307. }
  308. rspamd_http_connection_unref (conn);
  309. return ret;
  310. }
  311. /*
  312. * HTTP parser sets content length to (-1) when it doesn't know the real
  313. * length, for example, in case of chunked encoding.
  314. *
  315. * Hence, we skip body setup here
  316. */
  317. if (parser->content_length != ULLONG_MAX && parser->content_length != 0) {
  318. if (conn->max_size > 0 &&
  319. parser->content_length > conn->max_size) {
  320. /* Too large message */
  321. priv->flags |= RSPAMD_HTTP_CONN_FLAG_TOO_LARGE;
  322. return -1;
  323. }
  324. if (!rspamd_http_message_set_body (msg, NULL, parser->content_length)) {
  325. return -1;
  326. }
  327. }
  328. if (parser->flags & F_SPAMC) {
  329. msg->flags |= RSPAMD_HTTP_FLAG_SPAMC;
  330. }
  331. msg->method = parser->method;
  332. msg->code = parser->status_code;
  333. return 0;
  334. }
  335. static void
  336. rspamd_http_switch_zc (struct _rspamd_http_privbuf *pbuf,
  337. struct rspamd_http_message *msg)
  338. {
  339. pbuf->zc_buf = msg->body_buf.begin + msg->body_buf.len;
  340. pbuf->zc_remain = msg->body_buf.allocated_len - msg->body_buf.len;
  341. }
  342. static int
  343. rspamd_http_on_body (http_parser * parser, const gchar *at, size_t length)
  344. {
  345. struct rspamd_http_connection *conn =
  346. (struct rspamd_http_connection *)parser->data;
  347. struct rspamd_http_connection_private *priv;
  348. struct rspamd_http_message *msg;
  349. struct _rspamd_http_privbuf *pbuf;
  350. const gchar *p;
  351. priv = conn->priv;
  352. msg = priv->msg;
  353. pbuf = priv->buf;
  354. p = at;
  355. if (!(msg->flags & RSPAMD_HTTP_FLAG_HAS_BODY)) {
  356. if (!rspamd_http_message_set_body (msg, NULL, parser->content_length)) {
  357. return -1;
  358. }
  359. }
  360. if (conn->finished) {
  361. return 0;
  362. }
  363. if (conn->max_size > 0 &&
  364. msg->body_buf.len + length > conn->max_size) {
  365. /* Body length overflow */
  366. priv->flags |= RSPAMD_HTTP_CONN_FLAG_TOO_LARGE;
  367. return -1;
  368. }
  369. if (!pbuf->zc_buf) {
  370. if (!rspamd_http_message_append_body (msg, at, length)) {
  371. return -1;
  372. }
  373. /* We might have some leftover in our private buffer */
  374. if (pbuf->data->len == length) {
  375. /* Switch to zero-copy mode */
  376. rspamd_http_switch_zc (pbuf, msg);
  377. }
  378. }
  379. else {
  380. if (msg->body_buf.begin + msg->body_buf.len != at) {
  381. /* Likely chunked encoding */
  382. memmove ((gchar *)msg->body_buf.begin + msg->body_buf.len, at, length);
  383. p = msg->body_buf.begin + msg->body_buf.len;
  384. }
  385. /* Adjust zero-copy buf */
  386. msg->body_buf.len += length;
  387. if (!(msg->flags & RSPAMD_HTTP_FLAG_SHMEM)) {
  388. msg->body_buf.c.normal->len += length;
  389. }
  390. pbuf->zc_buf = msg->body_buf.begin + msg->body_buf.len;
  391. pbuf->zc_remain = msg->body_buf.allocated_len - msg->body_buf.len;
  392. }
  393. if ((conn->opts & RSPAMD_HTTP_BODY_PARTIAL) && !IS_CONN_ENCRYPTED (priv)) {
  394. /* Incremental update is impossible for encrypted requests so far */
  395. return (conn->body_handler (conn, msg, p, length));
  396. }
  397. return 0;
  398. }
  399. static int
  400. rspamd_http_on_body_decrypted (http_parser * parser, const gchar *at, size_t length)
  401. {
  402. struct rspamd_http_connection *conn =
  403. (struct rspamd_http_connection *)parser->data;
  404. struct rspamd_http_connection_private *priv;
  405. priv = conn->priv;
  406. if (priv->header != NULL) {
  407. rspamd_http_finish_header (conn, priv);
  408. priv->header = NULL;
  409. }
  410. if (conn->finished) {
  411. return 0;
  412. }
  413. if (priv->msg->body_buf.len == 0) {
  414. priv->msg->body_buf.begin = at;
  415. priv->msg->method = parser->method;
  416. priv->msg->code = parser->status_code;
  417. }
  418. priv->msg->body_buf.len += length;
  419. return 0;
  420. }
  421. static int
  422. rspamd_http_on_headers_complete_decrypted (http_parser *parser)
  423. {
  424. struct rspamd_http_connection *conn =
  425. (struct rspamd_http_connection *) parser->data;
  426. struct rspamd_http_connection_private *priv;
  427. struct rspamd_http_message *msg;
  428. int ret;
  429. priv = conn->priv;
  430. msg = priv->msg;
  431. if (priv->header != NULL) {
  432. rspamd_http_finish_header (conn, priv);
  433. priv->header = NULL;
  434. priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_NEW_HEADER;
  435. }
  436. if (parser->flags & F_SPAMC) {
  437. priv->msg->flags |= RSPAMD_HTTP_FLAG_SPAMC;
  438. }
  439. if (msg->method == HTTP_HEAD) {
  440. /* We don't care about the rest */
  441. if (rspamd_event_pending (&priv->ev, EV_READ)) {
  442. event_del (&priv->ev);
  443. }
  444. msg->code = parser->status_code;
  445. rspamd_http_connection_ref (conn);
  446. ret = conn->finish_handler (conn, msg);
  447. if (conn->opts & RSPAMD_HTTP_CLIENT_KEEP_ALIVE) {
  448. rspamd_http_context_push_keepalive (conn->priv->ctx, conn,
  449. msg, conn->priv->ctx->ev_base);
  450. rspamd_http_connection_reset (conn);
  451. }
  452. else {
  453. conn->finished = TRUE;
  454. }
  455. rspamd_http_connection_unref (conn);
  456. return ret;
  457. }
  458. priv->msg->method = parser->method;
  459. priv->msg->code = parser->status_code;
  460. return 0;
  461. }
  462. static int
  463. rspamd_http_decrypt_message (struct rspamd_http_connection *conn,
  464. struct rspamd_http_connection_private *priv,
  465. struct rspamd_cryptobox_pubkey *peer_key)
  466. {
  467. guchar *nonce, *m;
  468. const guchar *nm;
  469. gsize dec_len;
  470. struct rspamd_http_message *msg = priv->msg;
  471. struct rspamd_http_header *hdr, *hdrtmp, *hcur, *hcurtmp;
  472. struct http_parser decrypted_parser;
  473. struct http_parser_settings decrypted_cb;
  474. enum rspamd_cryptobox_mode mode;
  475. mode = rspamd_keypair_alg (priv->local_key);
  476. nonce = msg->body_buf.str;
  477. m = msg->body_buf.str + rspamd_cryptobox_nonce_bytes (mode) +
  478. rspamd_cryptobox_mac_bytes (mode);
  479. dec_len = msg->body_buf.len - rspamd_cryptobox_nonce_bytes (mode) -
  480. rspamd_cryptobox_mac_bytes (mode);
  481. if ((nm = rspamd_pubkey_get_nm (peer_key, priv->local_key)) == NULL) {
  482. nm = rspamd_pubkey_calculate_nm (peer_key, priv->local_key);
  483. }
  484. if (!rspamd_cryptobox_decrypt_nm_inplace (m, dec_len, nonce,
  485. nm, m - rspamd_cryptobox_mac_bytes (mode), mode)) {
  486. msg_err ("cannot verify encrypted message, first bytes of the input: %*xs",
  487. (gint)MIN(msg->body_buf.len, 64), msg->body_buf.begin);
  488. return -1;
  489. }
  490. /* Cleanup message */
  491. HASH_ITER (hh, msg->headers, hdr, hdrtmp) {
  492. HASH_DELETE (hh, msg->headers, hdr);
  493. DL_FOREACH_SAFE (hdr, hcur, hcurtmp) {
  494. rspamd_fstring_free (hcur->combined);
  495. g_free (hcur);
  496. }
  497. }
  498. msg->headers = NULL;
  499. if (msg->url != NULL) {
  500. msg->url = rspamd_fstring_assign (msg->url, "", 0);
  501. }
  502. msg->body_buf.len = 0;
  503. memset (&decrypted_parser, 0, sizeof (decrypted_parser));
  504. http_parser_init (&decrypted_parser,
  505. conn->type == RSPAMD_HTTP_SERVER ? HTTP_REQUEST : HTTP_RESPONSE);
  506. memset (&decrypted_cb, 0, sizeof (decrypted_cb));
  507. decrypted_cb.on_url = rspamd_http_on_url;
  508. decrypted_cb.on_status = rspamd_http_on_status;
  509. decrypted_cb.on_header_field = rspamd_http_on_header_field;
  510. decrypted_cb.on_header_value = rspamd_http_on_header_value;
  511. decrypted_cb.on_headers_complete = rspamd_http_on_headers_complete_decrypted;
  512. decrypted_cb.on_body = rspamd_http_on_body_decrypted;
  513. decrypted_parser.data = conn;
  514. decrypted_parser.content_length = dec_len;
  515. if (http_parser_execute (&decrypted_parser, &decrypted_cb, m,
  516. dec_len) != (size_t)dec_len) {
  517. msg_err ("HTTP parser error: %s when parsing encrypted request",
  518. http_errno_description (decrypted_parser.http_errno));
  519. return -1;
  520. }
  521. return 0;
  522. }
  523. static int
  524. rspamd_http_on_message_complete (http_parser * parser)
  525. {
  526. struct rspamd_http_connection *conn =
  527. (struct rspamd_http_connection *)parser->data;
  528. struct rspamd_http_connection_private *priv;
  529. int ret = 0;
  530. enum rspamd_cryptobox_mode mode;
  531. if (conn->finished) {
  532. return 0;
  533. }
  534. priv = conn->priv;
  535. if ((conn->opts & RSPAMD_HTTP_REQUIRE_ENCRYPTION) && !IS_CONN_ENCRYPTED (priv)) {
  536. priv->flags |= RSPAMD_HTTP_CONN_FLAG_ENCRYPTION_NEEDED;
  537. msg_err ("unencrypted connection when encryption has been requested");
  538. return -1;
  539. }
  540. if ((conn->opts & RSPAMD_HTTP_BODY_PARTIAL) == 0 && IS_CONN_ENCRYPTED (priv)) {
  541. mode = rspamd_keypair_alg (priv->local_key);
  542. if (priv->local_key == NULL || priv->msg->peer_key == NULL ||
  543. priv->msg->body_buf.len < rspamd_cryptobox_nonce_bytes (mode) +
  544. rspamd_cryptobox_mac_bytes (mode)) {
  545. msg_err ("cannot decrypt message");
  546. return -1;
  547. }
  548. /* We have keys, so we can decrypt message */
  549. ret = rspamd_http_decrypt_message (conn, priv, priv->msg->peer_key);
  550. if (ret != 0) {
  551. return ret;
  552. }
  553. if (conn->body_handler != NULL) {
  554. rspamd_http_connection_ref (conn);
  555. ret = conn->body_handler (conn,
  556. priv->msg,
  557. priv->msg->body_buf.begin,
  558. priv->msg->body_buf.len);
  559. rspamd_http_connection_unref (conn);
  560. }
  561. }
  562. else if ((conn->opts & RSPAMD_HTTP_BODY_PARTIAL) == 0 && conn->body_handler) {
  563. g_assert (conn->body_handler != NULL);
  564. rspamd_http_connection_ref (conn);
  565. ret = conn->body_handler (conn,
  566. priv->msg,
  567. priv->msg->body_buf.begin,
  568. priv->msg->body_buf.len);
  569. rspamd_http_connection_unref (conn);
  570. }
  571. if (ret == 0) {
  572. if (rspamd_event_pending (&priv->ev, EV_READ)) {
  573. event_del (&priv->ev);
  574. }
  575. rspamd_http_connection_ref (conn);
  576. ret = conn->finish_handler (conn, priv->msg);
  577. if (conn->opts & RSPAMD_HTTP_CLIENT_KEEP_ALIVE) {
  578. rspamd_http_context_push_keepalive (conn->priv->ctx, conn,
  579. priv->msg, conn->priv->ctx->ev_base);
  580. rspamd_http_connection_reset (conn);
  581. }
  582. else {
  583. conn->finished = TRUE;
  584. }
  585. rspamd_http_connection_unref (conn);
  586. }
  587. return ret;
  588. }
  589. static void
  590. rspamd_http_simple_client_helper (struct rspamd_http_connection *conn)
  591. {
  592. struct rspamd_http_connection_private *priv;
  593. gpointer ssl;
  594. gint request_method;
  595. rspamd_fstring_t *prev_host;
  596. priv = conn->priv;
  597. ssl = priv->ssl;
  598. priv->ssl = NULL;
  599. /* Preserve data */
  600. if (priv->msg) {
  601. request_method = priv->msg->method;
  602. /* Preserve host for keepalive */
  603. prev_host = priv->msg->host;
  604. priv->msg->host = NULL;
  605. }
  606. rspamd_http_connection_reset (conn);
  607. priv->ssl = ssl;
  608. /* Plan read message */
  609. if (conn->opts & RSPAMD_HTTP_CLIENT_SHARED) {
  610. rspamd_http_connection_read_message_shared (conn, conn->ud,
  611. conn->priv->ptv);
  612. }
  613. else {
  614. rspamd_http_connection_read_message (conn, conn->ud,
  615. conn->priv->ptv);
  616. }
  617. if (priv->msg) {
  618. priv->msg->method = request_method;
  619. priv->msg->host = prev_host;
  620. }
  621. else {
  622. if (prev_host) {
  623. rspamd_fstring_free (prev_host);
  624. }
  625. }
  626. }
  627. static void
  628. rspamd_http_write_helper (struct rspamd_http_connection *conn)
  629. {
  630. struct rspamd_http_connection_private *priv;
  631. struct iovec *start;
  632. guint niov, i;
  633. gint flags = 0;
  634. gsize remain;
  635. gssize r;
  636. GError *err;
  637. struct iovec *cur_iov;
  638. struct msghdr msg;
  639. priv = conn->priv;
  640. if (priv->wr_pos == priv->wr_total) {
  641. goto call_finish_handler;
  642. }
  643. start = &priv->out[0];
  644. niov = priv->outlen;
  645. remain = priv->wr_pos;
  646. /* We know that niov is small enough for that */
  647. cur_iov = alloca (niov * sizeof (struct iovec));
  648. memcpy (cur_iov, priv->out, niov * sizeof (struct iovec));
  649. for (i = 0; i < priv->outlen && remain > 0; i++) {
  650. /* Find out the first iov required */
  651. start = &cur_iov[i];
  652. if (start->iov_len <= remain) {
  653. remain -= start->iov_len;
  654. start = &cur_iov[i + 1];
  655. niov--;
  656. }
  657. else {
  658. start->iov_base = (void *)((char *)start->iov_base + remain);
  659. start->iov_len -= remain;
  660. remain = 0;
  661. }
  662. }
  663. memset (&msg, 0, sizeof (msg));
  664. msg.msg_iov = start;
  665. msg.msg_iovlen = MIN (IOV_MAX, niov);
  666. g_assert (niov > 0);
  667. #ifdef MSG_NOSIGNAL
  668. flags = MSG_NOSIGNAL;
  669. #endif
  670. if (priv->ssl) {
  671. r = rspamd_ssl_writev (priv->ssl, msg.msg_iov, msg.msg_iovlen);
  672. }
  673. else {
  674. r = sendmsg (conn->fd, &msg, flags);
  675. }
  676. if (r == -1) {
  677. if (!priv->ssl) {
  678. err = g_error_new (HTTP_ERROR, errno, "IO write error: %s", strerror (errno));
  679. rspamd_http_connection_ref (conn);
  680. conn->error_handler (conn, err);
  681. rspamd_http_connection_unref (conn);
  682. g_error_free (err);
  683. }
  684. return;
  685. }
  686. else {
  687. priv->wr_pos += r;
  688. }
  689. if (priv->wr_pos >= priv->wr_total) {
  690. goto call_finish_handler;
  691. }
  692. else {
  693. /* Want to write more */
  694. priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_RESETED;
  695. event_add (&priv->ev, priv->ptv);
  696. }
  697. return;
  698. call_finish_handler:
  699. if ((conn->opts & RSPAMD_HTTP_CLIENT_SIMPLE) == 0) {
  700. rspamd_http_connection_ref (conn);
  701. conn->finished = TRUE;
  702. conn->finish_handler (conn, priv->msg);
  703. rspamd_http_connection_unref (conn);
  704. }
  705. else {
  706. /* Plan read message */
  707. rspamd_http_simple_client_helper (conn);
  708. }
  709. }
  710. static gssize
  711. rspamd_http_try_read (gint fd,
  712. struct rspamd_http_connection *conn,
  713. struct rspamd_http_connection_private *priv,
  714. struct _rspamd_http_privbuf *pbuf,
  715. const gchar **buf_ptr)
  716. {
  717. gssize r;
  718. gchar *data;
  719. gsize len;
  720. struct rspamd_http_message *msg;
  721. msg = priv->msg;
  722. if (pbuf->zc_buf == NULL) {
  723. data = priv->buf->data->str;
  724. len = priv->buf->data->allocated;
  725. }
  726. else {
  727. data = (gchar *)pbuf->zc_buf;
  728. len = pbuf->zc_remain;
  729. if (len == 0) {
  730. rspamd_http_message_grow_body (priv->msg, priv->buf->data->allocated);
  731. rspamd_http_switch_zc (pbuf, msg);
  732. data = (gchar *)pbuf->zc_buf;
  733. len = pbuf->zc_remain;
  734. }
  735. }
  736. if (priv->ssl) {
  737. r = rspamd_ssl_read (priv->ssl, data, len);
  738. }
  739. else {
  740. r = read (fd, data, len);
  741. }
  742. if (r <= 0) {
  743. return r;
  744. }
  745. else {
  746. if (pbuf->zc_buf == NULL) {
  747. priv->buf->data->len = r;
  748. }
  749. else {
  750. pbuf->zc_remain -= r;
  751. pbuf->zc_buf += r;
  752. }
  753. }
  754. if (buf_ptr) {
  755. *buf_ptr = data;
  756. }
  757. return r;
  758. }
  759. static void
  760. rspamd_http_ssl_err_handler (gpointer ud, GError *err)
  761. {
  762. struct rspamd_http_connection *conn = (struct rspamd_http_connection *)ud;
  763. rspamd_http_connection_ref (conn);
  764. conn->error_handler (conn, err);
  765. rspamd_http_connection_unref (conn);
  766. }
  767. static void
  768. rspamd_http_event_handler (int fd, short what, gpointer ud)
  769. {
  770. struct rspamd_http_connection *conn = (struct rspamd_http_connection *)ud;
  771. struct rspamd_http_connection_private *priv;
  772. struct _rspamd_http_privbuf *pbuf;
  773. const gchar *d;
  774. gssize r;
  775. GError *err;
  776. priv = conn->priv;
  777. pbuf = priv->buf;
  778. REF_RETAIN (pbuf);
  779. rspamd_http_connection_ref (conn);
  780. if (what == EV_READ) {
  781. r = rspamd_http_try_read (fd, conn, priv, pbuf, &d);
  782. if (r > 0) {
  783. if (http_parser_execute (&priv->parser, &priv->parser_cb,
  784. d, r) != (size_t)r || priv->parser.http_errno != 0) {
  785. if (priv->flags & RSPAMD_HTTP_CONN_FLAG_TOO_LARGE) {
  786. err = g_error_new (HTTP_ERROR, 413,
  787. "Request entity too large: %zu",
  788. (size_t)priv->parser.content_length);
  789. }
  790. else if (priv->flags & RSPAMD_HTTP_CONN_FLAG_ENCRYPTION_NEEDED) {
  791. err = g_error_new (HTTP_ERROR, 400,
  792. "Encryption required");
  793. }
  794. else {
  795. err = g_error_new (HTTP_ERROR, 500 + priv->parser.http_errno,
  796. "HTTP parser error: %s",
  797. http_errno_description (priv->parser.http_errno));
  798. }
  799. if (!conn->finished) {
  800. conn->error_handler (conn, err);
  801. }
  802. else {
  803. msg_err ("got error after HTTP request is finished: %e", err);
  804. }
  805. g_error_free (err);
  806. REF_RELEASE (pbuf);
  807. rspamd_http_connection_unref (conn);
  808. return;
  809. }
  810. }
  811. else if (r == 0) {
  812. /* We can still call http parser */
  813. http_parser_execute (&priv->parser, &priv->parser_cb, d, r);
  814. if (!conn->finished) {
  815. err = g_error_new (HTTP_ERROR,
  816. errno,
  817. "IO read error: unexpected EOF");
  818. conn->error_handler (conn, err);
  819. g_error_free (err);
  820. }
  821. REF_RELEASE (pbuf);
  822. rspamd_http_connection_unref (conn);
  823. return;
  824. }
  825. else {
  826. if (!priv->ssl) {
  827. err = g_error_new (HTTP_ERROR,
  828. errno,
  829. "IO read error: %s",
  830. strerror (errno));
  831. conn->error_handler (conn, err);
  832. g_error_free (err);
  833. }
  834. REF_RELEASE (pbuf);
  835. rspamd_http_connection_unref (conn);
  836. return;
  837. }
  838. }
  839. else if (what == EV_TIMEOUT) {
  840. /* Let's try to read from the socket first */
  841. r = rspamd_http_try_read (fd, conn, priv, pbuf, &d);
  842. if (r > 0) {
  843. if (http_parser_execute (&priv->parser, &priv->parser_cb,
  844. d, r) != (size_t)r || priv->parser.http_errno != 0) {
  845. err = g_error_new (HTTP_ERROR, priv->parser.http_errno,
  846. "HTTP parser error: %s",
  847. http_errno_description (priv->parser.http_errno));
  848. if (!conn->finished) {
  849. conn->error_handler (conn, err);
  850. }
  851. else {
  852. msg_err ("got error after HTTP request is finished: %e", err);
  853. }
  854. g_error_free (err);
  855. REF_RELEASE (pbuf);
  856. rspamd_http_connection_unref (conn);
  857. return;
  858. }
  859. }
  860. else if (r == 0) {
  861. if (!conn->finished) {
  862. err = g_error_new (HTTP_ERROR, ETIMEDOUT,
  863. "IO timeout");
  864. conn->error_handler (conn, err);
  865. g_error_free (err);
  866. }
  867. REF_RELEASE (pbuf);
  868. rspamd_http_connection_unref (conn);
  869. return;
  870. }
  871. else {
  872. err = g_error_new (HTTP_ERROR, ETIMEDOUT,
  873. "IO timeout");
  874. conn->error_handler (conn, err);
  875. g_error_free (err);
  876. REF_RELEASE (pbuf);
  877. rspamd_http_connection_unref (conn);
  878. return;
  879. }
  880. }
  881. else if (what == EV_WRITE) {
  882. rspamd_http_write_helper (conn);
  883. }
  884. REF_RELEASE (pbuf);
  885. rspamd_http_connection_unref (conn);
  886. }
  887. static void
  888. rspamd_http_parser_reset (struct rspamd_http_connection *conn)
  889. {
  890. struct rspamd_http_connection_private *priv = conn->priv;
  891. http_parser_init (&priv->parser,
  892. conn->type == RSPAMD_HTTP_SERVER ? HTTP_REQUEST : HTTP_RESPONSE);
  893. priv->parser_cb.on_url = rspamd_http_on_url;
  894. priv->parser_cb.on_status = rspamd_http_on_status;
  895. priv->parser_cb.on_header_field = rspamd_http_on_header_field;
  896. priv->parser_cb.on_header_value = rspamd_http_on_header_value;
  897. priv->parser_cb.on_headers_complete = rspamd_http_on_headers_complete;
  898. priv->parser_cb.on_body = rspamd_http_on_body;
  899. priv->parser_cb.on_message_complete = rspamd_http_on_message_complete;
  900. }
  901. struct rspamd_http_connection *
  902. rspamd_http_connection_new (
  903. struct rspamd_http_context *ctx,
  904. gint fd,
  905. rspamd_http_body_handler_t body_handler,
  906. rspamd_http_error_handler_t error_handler,
  907. rspamd_http_finish_handler_t finish_handler,
  908. unsigned opts,
  909. enum rspamd_http_connection_type type)
  910. {
  911. struct rspamd_http_connection *conn;
  912. struct rspamd_http_connection_private *priv;
  913. if (error_handler == NULL || finish_handler == NULL) {
  914. return NULL;
  915. }
  916. conn = g_malloc0 (sizeof (struct rspamd_http_connection));
  917. conn->opts = opts;
  918. conn->type = type;
  919. conn->body_handler = body_handler;
  920. conn->error_handler = error_handler;
  921. conn->finish_handler = finish_handler;
  922. conn->fd = fd;
  923. conn->ref = 1;
  924. conn->finished = FALSE;
  925. /* Init priv */
  926. if (ctx == NULL) {
  927. ctx = rspamd_http_context_default ();
  928. }
  929. priv = g_malloc0 (sizeof (struct rspamd_http_connection_private));
  930. conn->priv = priv;
  931. priv->ctx = ctx;
  932. if (conn->type == RSPAMD_HTTP_CLIENT) {
  933. priv->cache = ctx->client_kp_cache;
  934. if (ctx->client_kp) {
  935. priv->local_key = rspamd_keypair_ref (ctx->client_kp);
  936. }
  937. }
  938. else {
  939. priv->cache = ctx->server_kp_cache;
  940. }
  941. rspamd_http_parser_reset (conn);
  942. priv->parser.data = conn;
  943. return conn;
  944. }
  945. struct rspamd_http_connection *
  946. rspamd_http_connection_new_keepalive (struct rspamd_http_context *ctx,
  947. rspamd_http_body_handler_t body_handler,
  948. rspamd_http_error_handler_t error_handler,
  949. rspamd_http_finish_handler_t finish_handler,
  950. rspamd_inet_addr_t *addr,
  951. const gchar *host)
  952. {
  953. struct rspamd_http_connection *conn;
  954. gint fd;
  955. if (error_handler == NULL || finish_handler == NULL) {
  956. return NULL;
  957. }
  958. if (ctx == NULL) {
  959. ctx = rspamd_http_context_default ();
  960. }
  961. conn = rspamd_http_context_check_keepalive (ctx, addr, host);
  962. if (conn) {
  963. return conn;
  964. }
  965. fd = rspamd_inet_address_connect (addr, SOCK_STREAM, TRUE);
  966. if (fd == -1) {
  967. msg_info ("cannot connect to %s: %s", rspamd_inet_address_to_string (addr),
  968. host);
  969. return NULL;
  970. }
  971. conn = rspamd_http_connection_new (ctx, fd, body_handler, error_handler,
  972. finish_handler,
  973. RSPAMD_HTTP_CLIENT_SIMPLE|RSPAMD_HTTP_CLIENT_KEEP_ALIVE,
  974. RSPAMD_HTTP_CLIENT);
  975. if (conn) {
  976. rspamd_http_context_prepare_keepalive (ctx, conn, addr, host);
  977. }
  978. return conn;
  979. }
  980. void
  981. rspamd_http_connection_reset (struct rspamd_http_connection *conn)
  982. {
  983. struct rspamd_http_connection_private *priv;
  984. struct rspamd_http_message *msg;
  985. priv = conn->priv;
  986. msg = priv->msg;
  987. /* Clear request */
  988. if (msg != NULL) {
  989. if (msg->peer_key) {
  990. priv->peer_key = msg->peer_key;
  991. msg->peer_key = NULL;
  992. }
  993. rspamd_http_message_unref (msg);
  994. priv->msg = NULL;
  995. }
  996. conn->finished = FALSE;
  997. /* Clear priv */
  998. if (!(priv->flags & RSPAMD_HTTP_CONN_FLAG_RESETED)) {
  999. if (rspamd_event_pending (&priv->ev, EV_READ|EV_WRITE|EV_TIMEOUT)) {
  1000. event_del (&priv->ev);
  1001. }
  1002. rspamd_http_parser_reset (conn);
  1003. }
  1004. if (priv->buf != NULL) {
  1005. REF_RELEASE (priv->buf);
  1006. priv->buf = NULL;
  1007. }
  1008. if (priv->out != NULL) {
  1009. g_free (priv->out);
  1010. priv->out = NULL;
  1011. }
  1012. priv->flags |= RSPAMD_HTTP_CONN_FLAG_RESETED;
  1013. }
  1014. struct rspamd_http_message *
  1015. rspamd_http_connection_steal_msg (struct rspamd_http_connection *conn)
  1016. {
  1017. struct rspamd_http_connection_private *priv;
  1018. struct rspamd_http_message *msg;
  1019. priv = conn->priv;
  1020. msg = priv->msg;
  1021. /* Clear request */
  1022. if (msg != NULL) {
  1023. if (msg->peer_key) {
  1024. priv->peer_key = msg->peer_key;
  1025. msg->peer_key = NULL;
  1026. }
  1027. priv->msg = NULL;
  1028. }
  1029. return msg;
  1030. }
  1031. struct rspamd_http_message *
  1032. rspamd_http_connection_copy_msg (struct rspamd_http_message *msg, GError **err)
  1033. {
  1034. struct rspamd_http_message *new_msg;
  1035. struct rspamd_http_header *hdr, *nhdr, *nhdrs, *thdr, *hcur;
  1036. const gchar *old_body;
  1037. gsize old_len;
  1038. struct stat st;
  1039. union _rspamd_storage_u *storage;
  1040. new_msg = rspamd_http_new_message (msg->type);
  1041. new_msg->flags = msg->flags;
  1042. if (msg->body_buf.len > 0) {
  1043. if (msg->flags & RSPAMD_HTTP_FLAG_SHMEM) {
  1044. /* Avoid copying by just maping a shared segment */
  1045. new_msg->flags |= RSPAMD_HTTP_FLAG_SHMEM_IMMUTABLE;
  1046. storage = &new_msg->body_buf.c;
  1047. storage->shared.shm_fd = dup (msg->body_buf.c.shared.shm_fd);
  1048. if (storage->shared.shm_fd == -1) {
  1049. rspamd_http_message_unref (new_msg);
  1050. g_set_error (err, http_error_quark (), errno,
  1051. "cannot dup shmem fd: %d: %s",
  1052. msg->body_buf.c.shared.shm_fd, strerror (errno));
  1053. return NULL;
  1054. }
  1055. if (fstat (storage->shared.shm_fd, &st) == -1) {
  1056. g_set_error (err, http_error_quark (), errno,
  1057. "cannot stat shmem fd: %d: %s",
  1058. storage->shared.shm_fd, strerror (errno));
  1059. rspamd_http_message_unref (new_msg);
  1060. return NULL;
  1061. }
  1062. /* We don't own segment, so do not try to touch it */
  1063. if (msg->body_buf.c.shared.name) {
  1064. storage->shared.name = msg->body_buf.c.shared.name;
  1065. REF_RETAIN (storage->shared.name);
  1066. }
  1067. new_msg->body_buf.str = mmap (NULL, st.st_size,
  1068. PROT_READ, MAP_SHARED,
  1069. storage->shared.shm_fd, 0);
  1070. if (new_msg->body_buf.str == MAP_FAILED) {
  1071. g_set_error (err, http_error_quark (), errno,
  1072. "cannot mmap shmem fd: %d: %s",
  1073. storage->shared.shm_fd, strerror (errno));
  1074. rspamd_http_message_unref (new_msg);
  1075. return NULL;
  1076. }
  1077. new_msg->body_buf.begin = new_msg->body_buf.str;
  1078. new_msg->body_buf.len = msg->body_buf.len;
  1079. new_msg->body_buf.begin = new_msg->body_buf.str +
  1080. (msg->body_buf.begin - msg->body_buf.str);
  1081. }
  1082. else {
  1083. old_body = rspamd_http_message_get_body (msg, &old_len);
  1084. if (!rspamd_http_message_set_body (new_msg, old_body, old_len)) {
  1085. g_set_error (err, http_error_quark (), errno,
  1086. "cannot set body for message, length: %zd",
  1087. old_len);
  1088. rspamd_http_message_unref (new_msg);
  1089. return NULL;
  1090. }
  1091. }
  1092. }
  1093. if (msg->url) {
  1094. if (new_msg->url) {
  1095. new_msg->url = rspamd_fstring_append (new_msg->url, msg->url->str,
  1096. msg->url->len);
  1097. }
  1098. else {
  1099. new_msg->url = rspamd_fstring_new_init (msg->url->str,
  1100. msg->url->len);
  1101. }
  1102. }
  1103. if (msg->host) {
  1104. new_msg->host = rspamd_fstring_new_init (msg->host->str,
  1105. msg->host->len);
  1106. }
  1107. new_msg->method = msg->method;
  1108. new_msg->port = msg->port;
  1109. new_msg->date = msg->date;
  1110. new_msg->last_modified = msg->last_modified;
  1111. HASH_ITER (hh, msg->headers, hdr, thdr) {
  1112. nhdrs = NULL;
  1113. DL_FOREACH (hdr, hcur) {
  1114. nhdr = g_malloc (sizeof (struct rspamd_http_header));
  1115. nhdr->combined = rspamd_fstring_new_init (hcur->combined->str,
  1116. hcur->combined->len);
  1117. nhdr->name.begin = nhdr->combined->str +
  1118. (hcur->name.begin - hcur->combined->str);
  1119. nhdr->name.len = hcur->name.len;
  1120. nhdr->value.begin = nhdr->combined->str +
  1121. (hcur->value.begin - hcur->combined->str);
  1122. nhdr->value.len = hcur->value.len;
  1123. DL_APPEND (nhdrs, nhdr);
  1124. }
  1125. HASH_ADD_KEYPTR (hh, new_msg->headers, nhdrs->name.begin,
  1126. nhdrs->name.len, nhdrs);
  1127. }
  1128. return new_msg;
  1129. }
  1130. void
  1131. rspamd_http_connection_free (struct rspamd_http_connection *conn)
  1132. {
  1133. struct rspamd_http_connection_private *priv;
  1134. priv = conn->priv;
  1135. if (priv != NULL) {
  1136. rspamd_http_connection_reset (conn);
  1137. if (priv->ssl) {
  1138. rspamd_ssl_connection_free (priv->ssl);
  1139. priv->ssl = NULL;
  1140. }
  1141. if (priv->local_key) {
  1142. rspamd_keypair_unref (priv->local_key);
  1143. }
  1144. if (priv->peer_key) {
  1145. rspamd_pubkey_unref (priv->peer_key);
  1146. }
  1147. g_free (priv);
  1148. }
  1149. if (conn->opts & RSPAMD_HTTP_CLIENT_KEEP_ALIVE) {
  1150. /* Fd is owned by a connection */
  1151. close (conn->fd);
  1152. }
  1153. g_free (conn);
  1154. }
  1155. static void
  1156. rspamd_http_connection_read_message_common (struct rspamd_http_connection *conn,
  1157. gpointer ud, struct timeval *timeout,
  1158. gint flags)
  1159. {
  1160. struct rspamd_http_connection_private *priv = conn->priv;
  1161. struct rspamd_http_message *req;
  1162. conn->ud = ud;
  1163. req = rspamd_http_new_message (
  1164. conn->type == RSPAMD_HTTP_SERVER ? HTTP_REQUEST : HTTP_RESPONSE);
  1165. priv->msg = req;
  1166. req->flags = flags;
  1167. if (flags & RSPAMD_HTTP_FLAG_SHMEM) {
  1168. req->body_buf.c.shared.shm_fd = -1;
  1169. }
  1170. if (priv->peer_key) {
  1171. priv->msg->peer_key = priv->peer_key;
  1172. priv->peer_key = NULL;
  1173. priv->flags |= RSPAMD_HTTP_CONN_FLAG_ENCRYPTED;
  1174. }
  1175. if (timeout == NULL) {
  1176. priv->ptv = NULL;
  1177. }
  1178. else {
  1179. memmove (&priv->tv, timeout, sizeof (struct timeval));
  1180. priv->ptv = &priv->tv;
  1181. }
  1182. priv->header = NULL;
  1183. priv->buf = g_malloc0 (sizeof (*priv->buf));
  1184. REF_INIT_RETAIN (priv->buf, rspamd_http_privbuf_dtor);
  1185. priv->buf->data = rspamd_fstring_sized_new (8192);
  1186. priv->flags |= RSPAMD_HTTP_CONN_FLAG_NEW_HEADER;
  1187. event_set (&priv->ev,
  1188. conn->fd,
  1189. EV_READ | EV_PERSIST,
  1190. rspamd_http_event_handler,
  1191. conn);
  1192. event_base_set (priv->ctx->ev_base, &priv->ev);
  1193. priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_RESETED;
  1194. event_add (&priv->ev, priv->ptv);
  1195. }
  1196. void
  1197. rspamd_http_connection_read_message (struct rspamd_http_connection *conn,
  1198. gpointer ud, struct timeval *timeout)
  1199. {
  1200. rspamd_http_connection_read_message_common (conn, ud, timeout, 0);
  1201. }
  1202. void
  1203. rspamd_http_connection_read_message_shared (struct rspamd_http_connection *conn,
  1204. gpointer ud, struct timeval *timeout)
  1205. {
  1206. rspamd_http_connection_read_message_common (conn, ud, timeout,
  1207. RSPAMD_HTTP_FLAG_SHMEM);
  1208. }
  1209. static void
  1210. rspamd_http_connection_encrypt_message (
  1211. struct rspamd_http_connection *conn,
  1212. struct rspamd_http_message *msg,
  1213. struct rspamd_http_connection_private *priv,
  1214. guchar *pbody,
  1215. guint bodylen,
  1216. guchar *pmethod,
  1217. guint methodlen,
  1218. guint preludelen,
  1219. gint hdrcount,
  1220. guchar *np,
  1221. guchar *mp,
  1222. struct rspamd_cryptobox_pubkey *peer_key)
  1223. {
  1224. struct rspamd_cryptobox_segment *segments;
  1225. guchar *crlfp;
  1226. const guchar *nm;
  1227. gint i, cnt;
  1228. guint outlen;
  1229. struct rspamd_http_header *hdr, *htmp, *hcur;
  1230. enum rspamd_cryptobox_mode mode;
  1231. mode = rspamd_keypair_alg (priv->local_key);
  1232. crlfp = mp + rspamd_cryptobox_mac_bytes (mode);
  1233. outlen = priv->out[0].iov_len + priv->out[1].iov_len;
  1234. /*
  1235. * Create segments from the following:
  1236. * Method, [URL], CRLF, nheaders, CRLF, body
  1237. */
  1238. segments = g_new (struct rspamd_cryptobox_segment, hdrcount + 5);
  1239. segments[0].data = pmethod;
  1240. segments[0].len = methodlen;
  1241. if (conn->type != RSPAMD_HTTP_SERVER) {
  1242. segments[1].data = msg->url->str;
  1243. segments[1].len = msg->url->len;
  1244. /* space + HTTP version + crlf */
  1245. segments[2].data = crlfp;
  1246. segments[2].len = preludelen - 2;
  1247. crlfp += segments[2].len;
  1248. i = 3;
  1249. }
  1250. else {
  1251. /* Here we send just CRLF */
  1252. segments[1].data = crlfp;
  1253. segments[1].len = 2;
  1254. crlfp += segments[1].len;
  1255. i = 2;
  1256. }
  1257. HASH_ITER (hh, msg->headers, hdr, htmp) {
  1258. DL_FOREACH (hdr, hcur) {
  1259. segments[i].data = hcur->combined->str;
  1260. segments[i++].len = hcur->combined->len;
  1261. }
  1262. }
  1263. /* crlfp should point now at the second crlf */
  1264. segments[i].data = crlfp;
  1265. segments[i++].len = 2;
  1266. if (pbody) {
  1267. segments[i].data = pbody;
  1268. segments[i++].len = bodylen;
  1269. }
  1270. cnt = i;
  1271. if ((nm = rspamd_pubkey_get_nm (peer_key, priv->local_key)) == NULL) {
  1272. nm = rspamd_pubkey_calculate_nm (peer_key, priv->local_key);
  1273. }
  1274. rspamd_cryptobox_encryptv_nm_inplace (segments, cnt, np, nm, mp, mode);
  1275. /*
  1276. * iov[0] = base HTTP request
  1277. * iov[1] = CRLF
  1278. * iov[2] = nonce
  1279. * iov[3] = mac
  1280. * iov[4..i] = encrypted HTTP request/reply
  1281. */
  1282. priv->out[2].iov_base = np;
  1283. priv->out[2].iov_len = rspamd_cryptobox_nonce_bytes (mode);
  1284. priv->out[3].iov_base = mp;
  1285. priv->out[3].iov_len = rspamd_cryptobox_mac_bytes (mode);
  1286. outlen += rspamd_cryptobox_nonce_bytes (mode) +
  1287. rspamd_cryptobox_mac_bytes (mode);
  1288. for (i = 0; i < cnt; i ++) {
  1289. priv->out[i + 4].iov_base = segments[i].data;
  1290. priv->out[i + 4].iov_len = segments[i].len;
  1291. outlen += segments[i].len;
  1292. }
  1293. priv->wr_total = outlen;
  1294. g_free (segments);
  1295. }
  1296. static void
  1297. rspamd_http_detach_shared (struct rspamd_http_message *msg)
  1298. {
  1299. rspamd_fstring_t *cpy_str;
  1300. cpy_str = rspamd_fstring_new_init (msg->body_buf.begin, msg->body_buf.len);
  1301. rspamd_http_message_set_body_from_fstring_steal (msg, cpy_str);
  1302. }
  1303. gint
  1304. rspamd_http_message_write_header (const gchar* mime_type, gboolean encrypted,
  1305. gchar *repbuf, gsize replen, gsize bodylen, gsize enclen, const gchar* host,
  1306. struct rspamd_http_connection* conn, struct rspamd_http_message* msg,
  1307. rspamd_fstring_t** buf,
  1308. struct rspamd_http_connection_private* priv,
  1309. struct rspamd_cryptobox_pubkey* peer_key)
  1310. {
  1311. gchar datebuf[64];
  1312. gint meth_len = 0;
  1313. const gchar *conn_type = "close";
  1314. if (conn->type == RSPAMD_HTTP_SERVER) {
  1315. /* Format reply */
  1316. if (msg->method < HTTP_SYMBOLS) {
  1317. rspamd_ftok_t status;
  1318. rspamd_http_date_format (datebuf, sizeof (datebuf), msg->date);
  1319. if (mime_type == NULL) {
  1320. mime_type =
  1321. encrypted ? "application/octet-stream" : "text/plain";
  1322. }
  1323. if (msg->status == NULL || msg->status->len == 0) {
  1324. if (msg->code == 200) {
  1325. RSPAMD_FTOK_ASSIGN (&status, "OK");
  1326. }
  1327. else if (msg->code == 404) {
  1328. RSPAMD_FTOK_ASSIGN (&status, "Not Found");
  1329. }
  1330. else if (msg->code == 403) {
  1331. RSPAMD_FTOK_ASSIGN (&status, "Forbidden");
  1332. }
  1333. else if (msg->code >= 500 && msg->code < 600) {
  1334. RSPAMD_FTOK_ASSIGN (&status, "Internal Server Error");
  1335. }
  1336. else {
  1337. RSPAMD_FTOK_ASSIGN (&status, "Undefined Error");
  1338. }
  1339. }
  1340. else {
  1341. status.begin = msg->status->str;
  1342. status.len = msg->status->len;
  1343. }
  1344. if (encrypted) {
  1345. /* Internal reply (encrypted) */
  1346. if (mime_type) {
  1347. meth_len =
  1348. rspamd_snprintf (repbuf, replen,
  1349. "HTTP/1.1 %d %T\r\n"
  1350. "Connection: close\r\n"
  1351. "Server: %s\r\n"
  1352. "Date: %s\r\n"
  1353. "Content-Length: %z\r\n"
  1354. "Content-Type: %s", /* NO \r\n at the end ! */
  1355. msg->code, &status, "rspamd/" RVERSION,
  1356. datebuf,
  1357. bodylen, mime_type);
  1358. }
  1359. else {
  1360. meth_len =
  1361. rspamd_snprintf (repbuf, replen,
  1362. "HTTP/1.1 %d %T\r\n"
  1363. "Connection: close\r\n"
  1364. "Server: %s\r\n"
  1365. "Date: %s\r\n"
  1366. "Content-Length: %z", /* NO \r\n at the end ! */
  1367. msg->code, &status, "rspamd/" RVERSION,
  1368. datebuf,
  1369. bodylen);
  1370. }
  1371. enclen += meth_len;
  1372. /* External reply */
  1373. rspamd_printf_fstring (buf,
  1374. "HTTP/1.1 200 OK\r\n"
  1375. "Connection: close\r\n"
  1376. "Server: rspamd\r\n"
  1377. "Date: %s\r\n"
  1378. "Content-Length: %z\r\n"
  1379. "Content-Type: application/octet-stream\r\n",
  1380. datebuf, enclen);
  1381. }
  1382. else {
  1383. if (mime_type) {
  1384. meth_len =
  1385. rspamd_printf_fstring (buf,
  1386. "HTTP/1.1 %d %T\r\n"
  1387. "Connection: close\r\n"
  1388. "Server: %s\r\n"
  1389. "Date: %s\r\n"
  1390. "Content-Length: %z\r\n"
  1391. "Content-Type: %s\r\n",
  1392. msg->code, &status, "rspamd/" RVERSION,
  1393. datebuf,
  1394. bodylen, mime_type);
  1395. }
  1396. else {
  1397. meth_len =
  1398. rspamd_printf_fstring (buf,
  1399. "HTTP/1.1 %d %T\r\n"
  1400. "Connection: close\r\n"
  1401. "Server: %s\r\n"
  1402. "Date: %s\r\n"
  1403. "Content-Length: %z\r\n",
  1404. msg->code, &status, "rspamd/" RVERSION,
  1405. datebuf,
  1406. bodylen);
  1407. }
  1408. }
  1409. }
  1410. else {
  1411. /* Legacy spamd reply */
  1412. if (msg->flags & RSPAMD_HTTP_FLAG_SPAMC) {
  1413. gsize real_bodylen;
  1414. goffset eoh_pos;
  1415. GString tmp;
  1416. /* Unfortunately, spamc protocol is deadly brain damaged */
  1417. tmp.str = (gchar *)msg->body_buf.begin;
  1418. tmp.len = msg->body_buf.len;
  1419. if (rspamd_string_find_eoh (&tmp, &eoh_pos) != -1 &&
  1420. bodylen > eoh_pos) {
  1421. real_bodylen = bodylen - eoh_pos;
  1422. }
  1423. else {
  1424. real_bodylen = bodylen;
  1425. }
  1426. rspamd_printf_fstring (buf, "SPAMD/1.1 0 EX_OK\r\n"
  1427. "Content-length: %z\r\n",
  1428. real_bodylen);
  1429. }
  1430. else {
  1431. rspamd_printf_fstring (buf, "RSPAMD/1.3 0 EX_OK\r\n");
  1432. }
  1433. }
  1434. }
  1435. else {
  1436. if (conn->opts & RSPAMD_HTTP_CLIENT_KEEP_ALIVE) {
  1437. conn_type = "keep-alive";
  1438. }
  1439. /* Format request */
  1440. enclen += msg->url->len + strlen (http_method_str (msg->method)) + 1;
  1441. if (host == NULL && msg->host == NULL) {
  1442. /* Fallback to HTTP/1.0 */
  1443. if (encrypted) {
  1444. rspamd_printf_fstring (buf,
  1445. "%s %s HTTP/1.0\r\n"
  1446. "Content-Length: %z\r\n"
  1447. "Content-Type: application/octet-stream\r\n"
  1448. "Connection: %s\r\n",
  1449. "POST",
  1450. "/post",
  1451. enclen,
  1452. conn_type);
  1453. }
  1454. else {
  1455. rspamd_printf_fstring (buf,
  1456. "%s %V HTTP/1.0\r\n"
  1457. "Content-Length: %z\r\n"
  1458. "Connection: %s\r\n",
  1459. http_method_str (msg->method),
  1460. msg->url,
  1461. bodylen,
  1462. conn_type);
  1463. if (bodylen > 0) {
  1464. if (mime_type == NULL) {
  1465. mime_type = "text/plain";
  1466. }
  1467. rspamd_printf_fstring (buf,
  1468. "Content-Type: %s\r\n",
  1469. mime_type);
  1470. }
  1471. }
  1472. }
  1473. else {
  1474. if (encrypted) {
  1475. if (host != NULL) {
  1476. rspamd_printf_fstring (buf,
  1477. "%s %s HTTP/1.1\r\n"
  1478. "Connection: %s\r\n"
  1479. "Host: %s\r\n"
  1480. "Content-Length: %z\r\n"
  1481. "Content-Type: application/octet-stream\r\n",
  1482. "POST",
  1483. "/post",
  1484. conn_type,
  1485. host,
  1486. enclen);
  1487. }
  1488. else {
  1489. rspamd_printf_fstring (buf,
  1490. "%s %s HTTP/1.1\r\n"
  1491. "Connection: %s\r\n"
  1492. "Host: %V\r\n"
  1493. "Content-Length: %z\r\n"
  1494. "Content-Type: application/octet-stream\r\n",
  1495. "POST",
  1496. "/post",
  1497. conn_type,
  1498. msg->host,
  1499. enclen);
  1500. }
  1501. }
  1502. else {
  1503. if (host != NULL) {
  1504. rspamd_printf_fstring (buf,
  1505. "%s %V HTTP/1.1\r\n"
  1506. "Connection: %s\r\n"
  1507. "Host: %s\r\n"
  1508. "Content-Length: %z\r\n",
  1509. http_method_str (msg->method),
  1510. msg->url,
  1511. conn_type,
  1512. host,
  1513. bodylen);
  1514. }
  1515. else {
  1516. rspamd_printf_fstring (buf,
  1517. "%s %V HTTP/1.1\r\n"
  1518. "Connection: %s\r\n"
  1519. "Host: %V\r\n"
  1520. "Content-Length: %z\r\n",
  1521. http_method_str (msg->method),
  1522. msg->url,
  1523. conn_type,
  1524. msg->host,
  1525. bodylen);
  1526. }
  1527. if (bodylen > 0) {
  1528. if (mime_type != NULL) {
  1529. rspamd_printf_fstring (buf,
  1530. "Content-Type: %s\r\n",
  1531. mime_type);
  1532. }
  1533. }
  1534. }
  1535. }
  1536. if (encrypted) {
  1537. GString *b32_key, *b32_id;
  1538. b32_key = rspamd_keypair_print (priv->local_key,
  1539. RSPAMD_KEYPAIR_PUBKEY | RSPAMD_KEYPAIR_BASE32);
  1540. b32_id = rspamd_pubkey_print (peer_key,
  1541. RSPAMD_KEYPAIR_ID_SHORT | RSPAMD_KEYPAIR_BASE32);
  1542. /* XXX: add some fuzz here */
  1543. rspamd_printf_fstring (&*buf, "Key: %v=%v\r\n", b32_id, b32_key);
  1544. g_string_free (b32_key, TRUE);
  1545. g_string_free (b32_id, TRUE);
  1546. }
  1547. }
  1548. return meth_len;
  1549. }
  1550. static void
  1551. rspamd_http_connection_write_message_common (struct rspamd_http_connection *conn,
  1552. struct rspamd_http_message *msg,
  1553. const gchar *host,
  1554. const gchar *mime_type,
  1555. gpointer ud,
  1556. struct timeval *timeout,
  1557. gboolean allow_shared)
  1558. {
  1559. struct rspamd_http_connection_private *priv = conn->priv;
  1560. struct rspamd_http_header *hdr, *htmp, *hcur;
  1561. gchar repbuf[512], *pbody;
  1562. gint i, hdrcount, meth_len = 0, preludelen = 0;
  1563. gsize bodylen, enclen = 0;
  1564. rspamd_fstring_t *buf;
  1565. gboolean encrypted = FALSE;
  1566. guchar nonce[rspamd_cryptobox_MAX_NONCEBYTES], mac[rspamd_cryptobox_MAX_MACBYTES];
  1567. guchar *np = NULL, *mp = NULL, *meth_pos = NULL;
  1568. struct rspamd_cryptobox_pubkey *peer_key = NULL;
  1569. enum rspamd_cryptobox_mode mode;
  1570. GError *err;
  1571. conn->ud = ud;
  1572. priv->msg = msg;
  1573. if (timeout == NULL) {
  1574. priv->ptv = NULL;
  1575. }
  1576. else if (timeout != &priv->tv) {
  1577. memcpy (&priv->tv, timeout, sizeof (struct timeval));
  1578. priv->ptv = &priv->tv;
  1579. }
  1580. priv->header = NULL;
  1581. priv->buf = g_malloc0 (sizeof (*priv->buf));
  1582. REF_INIT_RETAIN (priv->buf, rspamd_http_privbuf_dtor);
  1583. priv->buf->data = rspamd_fstring_sized_new (512);
  1584. buf = priv->buf->data;
  1585. if (priv->peer_key && priv->local_key) {
  1586. priv->msg->peer_key = priv->peer_key;
  1587. priv->peer_key = NULL;
  1588. priv->flags |= RSPAMD_HTTP_CONN_FLAG_ENCRYPTED;
  1589. }
  1590. if (msg->peer_key != NULL) {
  1591. if (priv->local_key == NULL) {
  1592. /* Automatically generate a temporary keypair */
  1593. priv->local_key = rspamd_keypair_new (RSPAMD_KEYPAIR_KEX,
  1594. RSPAMD_CRYPTOBOX_MODE_25519);
  1595. }
  1596. encrypted = TRUE;
  1597. if (priv->cache) {
  1598. rspamd_keypair_cache_process (priv->cache,
  1599. priv->local_key, priv->msg->peer_key);
  1600. }
  1601. }
  1602. if (encrypted && (msg->flags &
  1603. (RSPAMD_HTTP_FLAG_SHMEM_IMMUTABLE|RSPAMD_HTTP_FLAG_SHMEM))) {
  1604. /* We cannot use immutable body to encrypt message in place */
  1605. allow_shared = FALSE;
  1606. rspamd_http_detach_shared (msg);
  1607. }
  1608. if (allow_shared) {
  1609. gchar tmpbuf[64];
  1610. if (!(msg->flags & RSPAMD_HTTP_FLAG_SHMEM) ||
  1611. msg->body_buf.c.shared.name == NULL) {
  1612. allow_shared = FALSE;
  1613. }
  1614. else {
  1615. /* Insert new headers */
  1616. rspamd_http_message_add_header (msg, "Shm",
  1617. msg->body_buf.c.shared.name->shm_name);
  1618. rspamd_snprintf (tmpbuf, sizeof (tmpbuf), "%d",
  1619. (int)(msg->body_buf.begin - msg->body_buf.str));
  1620. rspamd_http_message_add_header (msg, "Shm-Offset",
  1621. tmpbuf);
  1622. rspamd_snprintf (tmpbuf, sizeof (tmpbuf), "%z",
  1623. msg->body_buf.len);
  1624. rspamd_http_message_add_header (msg, "Shm-Length",
  1625. tmpbuf);
  1626. }
  1627. }
  1628. if (priv->ctx->config.user_agent) {
  1629. rspamd_http_message_add_header (msg, "User-Agent",
  1630. priv->ctx->config.user_agent);
  1631. }
  1632. if (encrypted) {
  1633. mode = rspamd_keypair_alg (priv->local_key);
  1634. if (msg->body_buf.len == 0) {
  1635. pbody = NULL;
  1636. bodylen = 0;
  1637. msg->method = HTTP_GET;
  1638. }
  1639. else {
  1640. pbody = (gchar *)msg->body_buf.begin;
  1641. bodylen = msg->body_buf.len;
  1642. msg->method = HTTP_POST;
  1643. }
  1644. if (conn->type == RSPAMD_HTTP_SERVER) {
  1645. /*
  1646. * iov[0] = base reply
  1647. * iov[1] = CRLF
  1648. * iov[2] = nonce
  1649. * iov[3] = mac
  1650. * iov[4] = encrypted reply
  1651. * iov[6] = encrypted crlf
  1652. * iov[7..n] = encrypted headers
  1653. * iov[n + 1] = encrypted crlf
  1654. * [iov[n + 2] = encrypted body]
  1655. */
  1656. priv->outlen = 7;
  1657. enclen = rspamd_cryptobox_nonce_bytes (mode) +
  1658. rspamd_cryptobox_mac_bytes (mode) +
  1659. 4 + /* 2 * CRLF */
  1660. bodylen;
  1661. }
  1662. else {
  1663. /*
  1664. * iov[0] = base request
  1665. * iov[1] = CRLF
  1666. * iov[2] = nonce
  1667. * iov[3] = mac
  1668. * iov[4] = encrypted method + space
  1669. * iov[5] = encrypted url
  1670. * iov[7] = encrypted prelude
  1671. * iov[8..n] = encrypted headers
  1672. * iov[n + 1] = encrypted crlf
  1673. * [iov[n + 2] = encrypted body]
  1674. */
  1675. priv->outlen = 8;
  1676. if (bodylen > 0) {
  1677. if (mime_type != NULL) {
  1678. preludelen = rspamd_snprintf (repbuf, sizeof (repbuf), "%s\r\n"
  1679. "Content-Length: %z\r\n"
  1680. "Content-Type: %s\r\n"
  1681. "\r\n", ENCRYPTED_VERSION, bodylen,
  1682. mime_type);
  1683. }
  1684. else {
  1685. preludelen = rspamd_snprintf (repbuf, sizeof (repbuf), "%s\r\n"
  1686. "Content-Length: %z\r\n"
  1687. ""
  1688. "\r\n", ENCRYPTED_VERSION, bodylen);
  1689. }
  1690. }
  1691. else {
  1692. preludelen = rspamd_snprintf (repbuf, sizeof (repbuf),
  1693. "%s\r\n\r\n",
  1694. ENCRYPTED_VERSION);
  1695. }
  1696. enclen = rspamd_cryptobox_nonce_bytes (mode) +
  1697. rspamd_cryptobox_mac_bytes (mode) +
  1698. preludelen + /* version [content-length] + 2 * CRLF */
  1699. bodylen;
  1700. }
  1701. if (bodylen > 0) {
  1702. priv->outlen ++;
  1703. }
  1704. }
  1705. else {
  1706. if (msg->method < HTTP_SYMBOLS) {
  1707. if (msg->body_buf.len == 0 || allow_shared) {
  1708. pbody = NULL;
  1709. bodylen = 0;
  1710. priv->outlen = 2;
  1711. if (msg->method == HTTP_INVALID) {
  1712. msg->method = HTTP_GET;
  1713. }
  1714. }
  1715. else {
  1716. pbody = (gchar *)msg->body_buf.begin;
  1717. bodylen = msg->body_buf.len;
  1718. priv->outlen = 3;
  1719. if (msg->method == HTTP_INVALID) {
  1720. msg->method = HTTP_POST;
  1721. }
  1722. }
  1723. }
  1724. else if (msg->body_buf.len > 0) {
  1725. allow_shared = FALSE;
  1726. pbody = (gchar *)msg->body_buf.begin;
  1727. bodylen = msg->body_buf.len;
  1728. priv->outlen = 2;
  1729. }
  1730. else {
  1731. /* Invalid body for spamc method */
  1732. abort ();
  1733. }
  1734. }
  1735. peer_key = msg->peer_key;
  1736. priv->wr_total = bodylen + 2;
  1737. hdrcount = 0;
  1738. if (msg->method < HTTP_SYMBOLS) {
  1739. HASH_ITER (hh, msg->headers, hdr, htmp) {
  1740. DL_FOREACH (hdr, hcur) {
  1741. /* <name: value\r\n> */
  1742. priv->wr_total += hcur->combined->len;
  1743. enclen += hcur->combined->len;
  1744. priv->outlen ++;
  1745. hdrcount ++;
  1746. }
  1747. }
  1748. }
  1749. /* Allocate iov */
  1750. priv->out = g_malloc0 (sizeof (struct iovec) * priv->outlen);
  1751. priv->wr_pos = 0;
  1752. meth_len = rspamd_http_message_write_header (mime_type, encrypted,
  1753. repbuf, sizeof (repbuf), bodylen, enclen,
  1754. host, conn, msg,
  1755. &buf, priv, peer_key);
  1756. priv->wr_total += buf->len;
  1757. /* Setup external request body */
  1758. priv->out[0].iov_base = buf->str;
  1759. priv->out[0].iov_len = buf->len;
  1760. /* Buf will be used eventually for encryption */
  1761. if (encrypted) {
  1762. gint meth_offset, nonce_offset, mac_offset;
  1763. mode = rspamd_keypair_alg (priv->local_key);
  1764. ottery_rand_bytes (nonce, rspamd_cryptobox_nonce_bytes (mode));
  1765. memset (mac, 0, rspamd_cryptobox_mac_bytes (mode));
  1766. meth_offset = buf->len;
  1767. if (conn->type == RSPAMD_HTTP_SERVER) {
  1768. buf = rspamd_fstring_append (buf, repbuf, meth_len);
  1769. }
  1770. else {
  1771. meth_len = strlen (http_method_str (msg->method)) + 1; /* + space */
  1772. buf = rspamd_fstring_append (buf, http_method_str (msg->method),
  1773. meth_len - 1);
  1774. buf = rspamd_fstring_append (buf, " ", 1);
  1775. }
  1776. nonce_offset = buf->len;
  1777. buf = rspamd_fstring_append (buf, nonce,
  1778. rspamd_cryptobox_nonce_bytes (mode));
  1779. mac_offset = buf->len;
  1780. buf = rspamd_fstring_append (buf, mac,
  1781. rspamd_cryptobox_mac_bytes (mode));
  1782. /* Need to be encrypted */
  1783. if (conn->type == RSPAMD_HTTP_SERVER) {
  1784. buf = rspamd_fstring_append (buf, "\r\n\r\n", 4);
  1785. }
  1786. else {
  1787. buf = rspamd_fstring_append (buf, repbuf, preludelen);
  1788. }
  1789. meth_pos = buf->str + meth_offset;
  1790. np = buf->str + nonce_offset;
  1791. mp = buf->str + mac_offset;
  1792. }
  1793. /* During previous writes, buf might be reallocated and changed */
  1794. priv->buf->data = buf;
  1795. if (encrypted) {
  1796. /* Finish external HTTP request */
  1797. priv->out[1].iov_base = "\r\n";
  1798. priv->out[1].iov_len = 2;
  1799. /* Encrypt the real request */
  1800. rspamd_http_connection_encrypt_message (conn, msg, priv, pbody, bodylen,
  1801. meth_pos, meth_len, preludelen, hdrcount, np, mp, peer_key);
  1802. }
  1803. else {
  1804. i = 1;
  1805. if (msg->method < HTTP_SYMBOLS) {
  1806. HASH_ITER (hh, msg->headers, hdr, htmp) {
  1807. DL_FOREACH (hdr, hcur) {
  1808. priv->out[i].iov_base = hcur->combined->str;
  1809. priv->out[i++].iov_len = hcur->combined->len;
  1810. }
  1811. }
  1812. priv->out[i].iov_base = "\r\n";
  1813. priv->out[i++].iov_len = 2;
  1814. }
  1815. else {
  1816. /* No CRLF for compatibility reply */
  1817. priv->wr_total -= 2;
  1818. }
  1819. if (pbody != NULL) {
  1820. priv->out[i].iov_base = pbody;
  1821. priv->out[i++].iov_len = bodylen;
  1822. }
  1823. }
  1824. priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_RESETED;
  1825. if (rspamd_event_pending (&priv->ev, EV_TIMEOUT|EV_WRITE|EV_READ)) {
  1826. event_del (&priv->ev);
  1827. }
  1828. if (msg->flags & RSPAMD_HTTP_FLAG_SSL) {
  1829. gpointer ssl_ctx = (msg->flags & RSPAMD_HTTP_FLAG_SSL_NOVERIFY) ?
  1830. priv->ctx->ssl_ctx_noverify : priv->ctx->ssl_ctx;
  1831. event_base_set (priv->ctx->ev_base, &priv->ev);
  1832. if (!ssl_ctx) {
  1833. err = g_error_new (HTTP_ERROR, errno, "ssl message requested "
  1834. "with no ssl ctx");
  1835. rspamd_http_connection_ref (conn);
  1836. conn->error_handler (conn, err);
  1837. rspamd_http_connection_unref (conn);
  1838. g_error_free (err);
  1839. return;
  1840. }
  1841. else {
  1842. if (priv->ssl) {
  1843. /* Cleanup the existing connection */
  1844. rspamd_ssl_connection_free (priv->ssl);
  1845. }
  1846. priv->ssl = rspamd_ssl_connection_new (ssl_ctx, priv->ctx->ev_base,
  1847. !(msg->flags & RSPAMD_HTTP_FLAG_SSL_NOVERIFY));
  1848. g_assert (priv->ssl != NULL);
  1849. if (!rspamd_ssl_connect_fd (priv->ssl, conn->fd, host, &priv->ev,
  1850. priv->ptv, rspamd_http_event_handler,
  1851. rspamd_http_ssl_err_handler, conn)) {
  1852. err = g_error_new (HTTP_ERROR, errno,
  1853. "ssl connection error: ssl error=%s, errno=%s",
  1854. ERR_error_string (ERR_get_error (), NULL),
  1855. strerror (errno));
  1856. rspamd_http_connection_ref (conn);
  1857. conn->error_handler (conn, err);
  1858. rspamd_http_connection_unref (conn);
  1859. g_error_free (err);
  1860. return;
  1861. }
  1862. }
  1863. }
  1864. else {
  1865. event_set (&priv->ev, conn->fd, EV_WRITE, rspamd_http_event_handler, conn);
  1866. event_base_set (priv->ctx->ev_base, &priv->ev);
  1867. event_add (&priv->ev, priv->ptv);
  1868. }
  1869. }
  1870. void
  1871. rspamd_http_connection_write_message (struct rspamd_http_connection *conn,
  1872. struct rspamd_http_message *msg,
  1873. const gchar *host,
  1874. const gchar *mime_type,
  1875. gpointer ud,
  1876. struct timeval *timeout)
  1877. {
  1878. rspamd_http_connection_write_message_common (conn, msg, host, mime_type,
  1879. ud, timeout, FALSE);
  1880. }
  1881. void
  1882. rspamd_http_connection_write_message_shared (struct rspamd_http_connection *conn,
  1883. struct rspamd_http_message *msg,
  1884. const gchar *host,
  1885. const gchar *mime_type,
  1886. gpointer ud,
  1887. struct timeval *timeout)
  1888. {
  1889. rspamd_http_connection_write_message_common (conn, msg, host, mime_type,
  1890. ud, timeout, TRUE);
  1891. }
  1892. void
  1893. rspamd_http_connection_set_max_size (struct rspamd_http_connection *conn,
  1894. gsize sz)
  1895. {
  1896. conn->max_size = sz;
  1897. }
  1898. void
  1899. rspamd_http_connection_set_key (struct rspamd_http_connection *conn,
  1900. struct rspamd_cryptobox_keypair *key)
  1901. {
  1902. struct rspamd_http_connection_private *priv = conn->priv;
  1903. g_assert (key != NULL);
  1904. priv->local_key = rspamd_keypair_ref (key);
  1905. }
  1906. const struct rspamd_cryptobox_pubkey*
  1907. rspamd_http_connection_get_peer_key (struct rspamd_http_connection *conn)
  1908. {
  1909. struct rspamd_http_connection_private *priv = conn->priv;
  1910. if (priv->peer_key) {
  1911. return priv->peer_key;
  1912. }
  1913. else if (priv->msg) {
  1914. return priv->msg->peer_key;
  1915. }
  1916. return NULL;
  1917. }
  1918. gboolean
  1919. rspamd_http_connection_is_encrypted (struct rspamd_http_connection *conn)
  1920. {
  1921. struct rspamd_http_connection_private *priv = conn->priv;
  1922. if (priv->peer_key != NULL) {
  1923. return TRUE;
  1924. }
  1925. else if (priv->msg) {
  1926. return priv->msg->peer_key != NULL;
  1927. }
  1928. return FALSE;
  1929. }
  1930. GHashTable *
  1931. rspamd_http_message_parse_query (struct rspamd_http_message *msg)
  1932. {
  1933. GHashTable *res;
  1934. rspamd_fstring_t *key = NULL, *value = NULL;
  1935. rspamd_ftok_t *key_tok = NULL, *value_tok = NULL;
  1936. const gchar *p, *c, *end;
  1937. struct http_parser_url u;
  1938. enum {
  1939. parse_key,
  1940. parse_eqsign,
  1941. parse_value,
  1942. parse_ampersand
  1943. } state = parse_key;
  1944. res = g_hash_table_new_full (rspamd_ftok_icase_hash,
  1945. rspamd_ftok_icase_equal,
  1946. rspamd_fstring_mapped_ftok_free,
  1947. rspamd_fstring_mapped_ftok_free);
  1948. if (msg->url && msg->url->len > 0) {
  1949. http_parser_parse_url (msg->url->str, msg->url->len, TRUE, &u);
  1950. if (u.field_set & (1 << UF_QUERY)) {
  1951. p = msg->url->str + u.field_data[UF_QUERY].off;
  1952. c = p;
  1953. end = p + u.field_data[UF_QUERY].len;
  1954. while (p <= end) {
  1955. switch (state) {
  1956. case parse_key:
  1957. if ((p == end || *p == '&') && p > c) {
  1958. /* We have a single parameter without a value */
  1959. key = rspamd_fstring_new_init (c, p - c);
  1960. key_tok = rspamd_ftok_map (key);
  1961. key_tok->len = rspamd_url_decode (key->str, key->str,
  1962. key->len);
  1963. value = rspamd_fstring_new_init ("", 0);
  1964. value_tok = rspamd_ftok_map (value);
  1965. g_hash_table_replace (res, key_tok, value_tok);
  1966. state = parse_ampersand;
  1967. }
  1968. else if (*p == '=' && p > c) {
  1969. /* We have something like key=value */
  1970. key = rspamd_fstring_new_init (c, p - c);
  1971. key_tok = rspamd_ftok_map (key);
  1972. key_tok->len = rspamd_url_decode (key->str, key->str,
  1973. key->len);
  1974. state = parse_eqsign;
  1975. }
  1976. else {
  1977. p ++;
  1978. }
  1979. break;
  1980. case parse_eqsign:
  1981. if (*p != '=') {
  1982. c = p;
  1983. state = parse_value;
  1984. }
  1985. else {
  1986. p ++;
  1987. }
  1988. break;
  1989. case parse_value:
  1990. if ((p == end || *p == '&') && p >= c) {
  1991. g_assert (key != NULL);
  1992. if (p > c) {
  1993. value = rspamd_fstring_new_init (c, p - c);
  1994. value_tok = rspamd_ftok_map (value);
  1995. value_tok->len = rspamd_url_decode (value->str,
  1996. value->str,
  1997. value->len);
  1998. /* Detect quotes for value */
  1999. if (value_tok->begin[0] == '"') {
  2000. memmove (value->str, value->str + 1,
  2001. value_tok->len - 1);
  2002. value_tok->len --;
  2003. }
  2004. if (value_tok->begin[value_tok->len - 1] == '"') {
  2005. value_tok->len --;
  2006. }
  2007. }
  2008. else {
  2009. value = rspamd_fstring_new_init ("", 0);
  2010. value_tok = rspamd_ftok_map (value);
  2011. }
  2012. g_hash_table_replace (res, key_tok, value_tok);
  2013. key = value = NULL;
  2014. key_tok = value_tok = NULL;
  2015. state = parse_ampersand;
  2016. }
  2017. else {
  2018. p ++;
  2019. }
  2020. break;
  2021. case parse_ampersand:
  2022. if (p != end && *p != '&') {
  2023. c = p;
  2024. state = parse_key;
  2025. }
  2026. else {
  2027. p ++;
  2028. }
  2029. break;
  2030. }
  2031. }
  2032. }
  2033. if (state != parse_ampersand && key != NULL) {
  2034. rspamd_fstring_free (key);
  2035. }
  2036. }
  2037. return res;
  2038. }
  2039. struct rspamd_http_message *
  2040. rspamd_http_message_ref (struct rspamd_http_message *msg)
  2041. {
  2042. REF_RETAIN (msg);
  2043. return msg;
  2044. }
  2045. void
  2046. rspamd_http_message_unref (struct rspamd_http_message *msg)
  2047. {
  2048. REF_RELEASE (msg);
  2049. }
  2050. void
  2051. rspamd_http_connection_disable_encryption (struct rspamd_http_connection *conn)
  2052. {
  2053. struct rspamd_http_connection_private *priv;
  2054. priv = conn->priv;
  2055. if (priv) {
  2056. if (priv->local_key) {
  2057. rspamd_keypair_unref (priv->local_key);
  2058. }
  2059. if (priv->peer_key) {
  2060. rspamd_pubkey_unref (priv->peer_key);
  2061. }
  2062. priv->local_key = NULL;
  2063. priv->peer_key = NULL;
  2064. priv->flags &= ~RSPAMD_HTTP_CONN_FLAG_ENCRYPTED;
  2065. }
  2066. }