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.

util.c 47KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454
  1. /*-
  2. * Copyright 2017 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 "unix-std.h"
  19. #include "xxhash.h"
  20. #include "ottery.h"
  21. #include "cryptobox.h"
  22. #ifdef HAVE_TERMIOS_H
  23. #include <termios.h>
  24. #endif
  25. #ifdef HAVE_READPASSPHRASE_H
  26. #include <readpassphrase.h>
  27. #endif
  28. /* libutil */
  29. #ifdef HAVE_LIBUTIL_H
  30. #include <libutil.h>
  31. #endif
  32. #ifdef __APPLE__
  33. #include <mach/mach_time.h>
  34. #include <mach/mach_init.h>
  35. #include <mach/thread_act.h>
  36. #include <mach/mach_port.h>
  37. #endif
  38. /* poll */
  39. #ifdef HAVE_POLL_H
  40. #include <poll.h>
  41. #endif
  42. #ifdef HAVE_SIGINFO_H
  43. #include <siginfo.h>
  44. #endif
  45. /* sys/wait */
  46. #ifdef HAVE_SYS_WAIT_H
  47. #include <sys/wait.h>
  48. #endif
  49. /* sys/resource.h */
  50. #ifdef HAVE_SYS_RESOURCE_H
  51. #include <sys/resource.h>
  52. #endif
  53. #ifdef HAVE_RDTSC
  54. #ifdef __x86_64__
  55. #include <x86intrin.h>
  56. #endif
  57. #endif
  58. #include <math.h> /* for pow */
  59. #include <glob.h> /* in fact, we require this file ultimately */
  60. #include "zlib.h"
  61. #include "contrib/uthash/utlist.h"
  62. #include "blas-config.h"
  63. /* Check log messages intensity once per minute */
  64. #define CHECK_TIME 60
  65. /* More than 2 log messages per second */
  66. #define BUF_INTENSITY 2
  67. /* Default connect timeout for sync sockets */
  68. #define CONNECT_TIMEOUT 3
  69. /*
  70. * Should be defined in a single point
  71. */
  72. const struct rspamd_controller_pbkdf pbkdf_list[] = {
  73. {
  74. .name = "PBKDF2-blake2b",
  75. .alias = "pbkdf2",
  76. .description = "standard CPU intensive \"slow\" KDF using blake2b hash function",
  77. .type = RSPAMD_CRYPTOBOX_PBKDF2,
  78. .id = RSPAMD_PBKDF_ID_V1,
  79. .complexity = 16000,
  80. .salt_len = 20,
  81. .key_len = rspamd_cryptobox_HASHBYTES / 2
  82. },
  83. {
  84. .name = "Catena-Butterfly",
  85. .alias = "catena",
  86. .description = "modern CPU and memory intensive KDF",
  87. .type = RSPAMD_CRYPTOBOX_CATENA,
  88. .id = RSPAMD_PBKDF_ID_V2,
  89. .complexity = 10,
  90. .salt_len = 20,
  91. .key_len = rspamd_cryptobox_HASHBYTES / 2
  92. }
  93. };
  94. gint
  95. rspamd_socket_nonblocking (gint fd)
  96. {
  97. gint ofl;
  98. ofl = fcntl (fd, F_GETFL, 0);
  99. if (fcntl (fd, F_SETFL, ofl | O_NONBLOCK) == -1) {
  100. return -1;
  101. }
  102. return 0;
  103. }
  104. gint
  105. rspamd_socket_blocking (gint fd)
  106. {
  107. gint ofl;
  108. ofl = fcntl (fd, F_GETFL, 0);
  109. if (fcntl (fd, F_SETFL, ofl & (~O_NONBLOCK)) == -1) {
  110. return -1;
  111. }
  112. return 0;
  113. }
  114. gint
  115. rspamd_socket_poll (gint fd, gint timeout, short events)
  116. {
  117. gint r;
  118. struct pollfd fds[1];
  119. fds->fd = fd;
  120. fds->events = events;
  121. fds->revents = 0;
  122. while ((r = poll (fds, 1, timeout)) < 0) {
  123. if (errno != EINTR) {
  124. break;
  125. }
  126. }
  127. return r;
  128. }
  129. gint
  130. rspamd_socket_create (gint af, gint type, gint protocol, gboolean async)
  131. {
  132. gint fd;
  133. fd = socket (af, type, protocol);
  134. if (fd == -1) {
  135. return -1;
  136. }
  137. /* Set close on exec */
  138. if (fcntl (fd, F_SETFD, FD_CLOEXEC) == -1) {
  139. close (fd);
  140. return -1;
  141. }
  142. if (async) {
  143. if (rspamd_socket_nonblocking (fd) == -1) {
  144. close (fd);
  145. return -1;
  146. }
  147. }
  148. return fd;
  149. }
  150. static gint
  151. rspamd_inet_socket_create (gint type, struct addrinfo *addr, gboolean is_server,
  152. gboolean async, GList **list)
  153. {
  154. gint fd = -1, r, on = 1, s_error;
  155. struct addrinfo *cur;
  156. gpointer ptr;
  157. socklen_t optlen;
  158. cur = addr;
  159. while (cur) {
  160. /* Create socket */
  161. fd = rspamd_socket_create (cur->ai_family, type, cur->ai_protocol, TRUE);
  162. if (fd == -1) {
  163. goto out;
  164. }
  165. if (is_server) {
  166. (void)setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&on,
  167. sizeof (gint));
  168. #ifdef HAVE_IPV6_V6ONLY
  169. if (cur->ai_family == AF_INET6) {
  170. setsockopt (fd, IPPROTO_IPV6, IPV6_V6ONLY, (const void *)&on,
  171. sizeof (gint));
  172. }
  173. #endif
  174. r = bind (fd, cur->ai_addr, cur->ai_addrlen);
  175. }
  176. else {
  177. r = connect (fd, cur->ai_addr, cur->ai_addrlen);
  178. }
  179. if (r == -1) {
  180. if (errno != EINPROGRESS) {
  181. goto out;
  182. }
  183. if (!async) {
  184. /* Try to poll */
  185. if (rspamd_socket_poll (fd, CONNECT_TIMEOUT * 1000,
  186. POLLOUT) <= 0) {
  187. errno = ETIMEDOUT;
  188. goto out;
  189. }
  190. else {
  191. /* Make synced again */
  192. if (rspamd_socket_blocking (fd) < 0) {
  193. goto out;
  194. }
  195. }
  196. }
  197. }
  198. else {
  199. /* Still need to check SO_ERROR on socket */
  200. optlen = sizeof (s_error);
  201. if (getsockopt (fd, SOL_SOCKET, SO_ERROR, (void *)&s_error, &optlen) != -1) {
  202. if (s_error) {
  203. errno = s_error;
  204. goto out;
  205. }
  206. }
  207. }
  208. if (list == NULL) {
  209. /* Go out immediately */
  210. break;
  211. }
  212. else if (fd != -1) {
  213. ptr = GINT_TO_POINTER (fd);
  214. *list = g_list_prepend (*list, ptr);
  215. cur = cur->ai_next;
  216. continue;
  217. }
  218. out:
  219. if (fd != -1) {
  220. close (fd);
  221. }
  222. fd = -1;
  223. cur = cur->ai_next;
  224. }
  225. return (fd);
  226. }
  227. gint
  228. rspamd_socket_tcp (struct addrinfo *addr, gboolean is_server, gboolean async)
  229. {
  230. return rspamd_inet_socket_create (SOCK_STREAM, addr, is_server, async, NULL);
  231. }
  232. gint
  233. rspamd_socket_udp (struct addrinfo *addr, gboolean is_server, gboolean async)
  234. {
  235. return rspamd_inet_socket_create (SOCK_DGRAM, addr, is_server, async, NULL);
  236. }
  237. gint
  238. rspamd_socket_unix (const gchar *path,
  239. struct sockaddr_un *addr,
  240. gint type,
  241. gboolean is_server,
  242. gboolean async)
  243. {
  244. socklen_t optlen;
  245. gint fd = -1, s_error, r, serrno, on = 1;
  246. struct stat st;
  247. if (path == NULL)
  248. return -1;
  249. addr->sun_family = AF_UNIX;
  250. rspamd_strlcpy (addr->sun_path, path, sizeof (addr->sun_path));
  251. #ifdef FREEBSD
  252. addr->sun_len = SUN_LEN (addr);
  253. #endif
  254. if (is_server) {
  255. /* Unlink socket if it exists already */
  256. if (lstat (addr->sun_path, &st) != -1) {
  257. if (S_ISSOCK (st.st_mode)) {
  258. if (unlink (addr->sun_path) == -1) {
  259. goto out;
  260. }
  261. }
  262. else {
  263. goto out;
  264. }
  265. }
  266. }
  267. fd = socket (PF_LOCAL, type, 0);
  268. if (fd == -1) {
  269. return -1;
  270. }
  271. if (rspamd_socket_nonblocking (fd) < 0) {
  272. goto out;
  273. }
  274. /* Set close on exec */
  275. if (fcntl (fd, F_SETFD, FD_CLOEXEC) == -1) {
  276. goto out;
  277. }
  278. if (is_server) {
  279. (void)setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&on,
  280. sizeof (gint));
  281. r = bind (fd, (struct sockaddr *)addr, SUN_LEN (addr));
  282. }
  283. else {
  284. r = connect (fd, (struct sockaddr *)addr, SUN_LEN (addr));
  285. }
  286. if (r == -1) {
  287. if (errno != EINPROGRESS) {
  288. goto out;
  289. }
  290. if (!async) {
  291. /* Try to poll */
  292. if (rspamd_socket_poll (fd, CONNECT_TIMEOUT * 1000, POLLOUT) <= 0) {
  293. errno = ETIMEDOUT;
  294. goto out;
  295. }
  296. else {
  297. /* Make synced again */
  298. if (rspamd_socket_blocking (fd) < 0) {
  299. goto out;
  300. }
  301. }
  302. }
  303. }
  304. else {
  305. /* Still need to check SO_ERROR on socket */
  306. optlen = sizeof (s_error);
  307. if (getsockopt (fd, SOL_SOCKET, SO_ERROR, (void *)&s_error, &optlen) != -1) {
  308. if (s_error) {
  309. errno = s_error;
  310. goto out;
  311. }
  312. }
  313. }
  314. return (fd);
  315. out:
  316. serrno = errno;
  317. if (fd != -1) {
  318. close (fd);
  319. }
  320. errno = serrno;
  321. return (-1);
  322. }
  323. static int
  324. rspamd_prefer_v4_hack (const struct addrinfo *a1, const struct addrinfo *a2)
  325. {
  326. return a1->ai_addr->sa_family - a2->ai_addr->sa_family;
  327. }
  328. /**
  329. * Make a universal socket
  330. * @param credits host, ip or path to unix socket
  331. * @param port port (used for network sockets)
  332. * @param async make this socket asynced
  333. * @param is_server make this socket as server socket
  334. * @param try_resolve try name resolution for a socket (BLOCKING)
  335. */
  336. gint
  337. rspamd_socket (const gchar *credits, guint16 port,
  338. gint type, gboolean async, gboolean is_server, gboolean try_resolve)
  339. {
  340. struct sockaddr_un un;
  341. struct stat st;
  342. struct addrinfo hints, *res;
  343. gint r;
  344. gchar portbuf[8];
  345. if (*credits == '/') {
  346. if (is_server) {
  347. return rspamd_socket_unix (credits, &un, type, is_server, async);
  348. }
  349. else {
  350. r = stat (credits, &st);
  351. if (r == -1) {
  352. /* Unix socket doesn't exists it must be created first */
  353. errno = ENOENT;
  354. return -1;
  355. }
  356. else {
  357. if ((st.st_mode & S_IFSOCK) == 0) {
  358. /* Path is not valid socket */
  359. errno = EINVAL;
  360. return -1;
  361. }
  362. else {
  363. return rspamd_socket_unix (credits,
  364. &un,
  365. type,
  366. is_server,
  367. async);
  368. }
  369. }
  370. }
  371. }
  372. else {
  373. /* TCP related part */
  374. memset (&hints, 0, sizeof (hints));
  375. hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
  376. hints.ai_socktype = type; /* Type of the socket */
  377. hints.ai_flags = is_server ? AI_PASSIVE : 0;
  378. hints.ai_protocol = 0; /* Any protocol */
  379. hints.ai_canonname = NULL;
  380. hints.ai_addr = NULL;
  381. hints.ai_next = NULL;
  382. if (!try_resolve) {
  383. hints.ai_flags |= AI_NUMERICHOST | AI_NUMERICSERV;
  384. }
  385. rspamd_snprintf (portbuf, sizeof (portbuf), "%d", (int)port);
  386. if ((r = getaddrinfo (credits, portbuf, &hints, &res)) == 0) {
  387. LL_SORT2 (res, rspamd_prefer_v4_hack, ai_next);
  388. r = rspamd_inet_socket_create (type, res, is_server, async, NULL);
  389. freeaddrinfo (res);
  390. return r;
  391. }
  392. else {
  393. return -1;
  394. }
  395. }
  396. }
  397. gboolean
  398. rspamd_socketpair (gint pair[2], gint af)
  399. {
  400. gint r = -1, serrno;
  401. #ifdef HAVE_SOCK_SEQPACKET
  402. if (af == SOCK_SEQPACKET) {
  403. r = socketpair (AF_LOCAL, SOCK_SEQPACKET, 0, pair);
  404. if (r == -1) {
  405. r = socketpair (AF_LOCAL, SOCK_DGRAM, 0, pair);
  406. }
  407. }
  408. #endif
  409. if (r == -1) {
  410. r = socketpair (AF_LOCAL, af, 0, pair);
  411. }
  412. if (r == -1) {
  413. return -1;
  414. }
  415. /* Set close on exec */
  416. if (fcntl (pair[0], F_SETFD, FD_CLOEXEC) == -1) {
  417. goto out;
  418. }
  419. if (fcntl (pair[1], F_SETFD, FD_CLOEXEC) == -1) {
  420. goto out;
  421. }
  422. return TRUE;
  423. out:
  424. serrno = errno;
  425. close (pair[0]);
  426. close (pair[1]);
  427. errno = serrno;
  428. return FALSE;
  429. }
  430. #ifdef HAVE_SA_SIGINFO
  431. void
  432. rspamd_signals_init (struct sigaction *signals, void (*sig_handler)(gint,
  433. siginfo_t *,
  434. void *))
  435. #else
  436. void
  437. rspamd_signals_init (struct sigaction *signals, void (*sig_handler)(gint))
  438. #endif
  439. {
  440. struct sigaction sigpipe_act;
  441. /* Setting up signal handlers */
  442. /* SIGUSR1 - reopen config file */
  443. /* SIGUSR2 - worker is ready for accept */
  444. sigemptyset (&signals->sa_mask);
  445. sigaddset (&signals->sa_mask, SIGTERM);
  446. sigaddset (&signals->sa_mask, SIGINT);
  447. sigaddset (&signals->sa_mask, SIGHUP);
  448. sigaddset (&signals->sa_mask, SIGCHLD);
  449. sigaddset (&signals->sa_mask, SIGUSR1);
  450. sigaddset (&signals->sa_mask, SIGUSR2);
  451. sigaddset (&signals->sa_mask, SIGALRM);
  452. #ifdef SIGPOLL
  453. sigaddset (&signals->sa_mask, SIGPOLL);
  454. #endif
  455. #ifdef SIGIO
  456. sigaddset (&signals->sa_mask, SIGIO);
  457. #endif
  458. #ifdef HAVE_SA_SIGINFO
  459. signals->sa_flags = SA_SIGINFO;
  460. signals->sa_handler = NULL;
  461. signals->sa_sigaction = sig_handler;
  462. #else
  463. signals->sa_handler = sig_handler;
  464. signals->sa_flags = 0;
  465. #endif
  466. sigaction (SIGTERM, signals, NULL);
  467. sigaction (SIGINT, signals, NULL);
  468. sigaction (SIGHUP, signals, NULL);
  469. sigaction (SIGCHLD, signals, NULL);
  470. sigaction (SIGUSR1, signals, NULL);
  471. sigaction (SIGUSR2, signals, NULL);
  472. sigaction (SIGALRM, signals, NULL);
  473. #ifdef SIGPOLL
  474. sigaction (SIGPOLL, signals, NULL);
  475. #endif
  476. #ifdef SIGIO
  477. sigaction (SIGIO, signals, NULL);
  478. #endif
  479. /* Ignore SIGPIPE as we handle write errors manually */
  480. sigemptyset (&sigpipe_act.sa_mask);
  481. sigaddset (&sigpipe_act.sa_mask, SIGPIPE);
  482. sigpipe_act.sa_handler = SIG_IGN;
  483. sigpipe_act.sa_flags = 0;
  484. sigaction (SIGPIPE, &sigpipe_act, NULL);
  485. }
  486. #ifndef HAVE_SETPROCTITLE
  487. #ifdef LINUX
  488. static gchar *title_buffer = NULL;
  489. static size_t title_buffer_size = 0;
  490. static gchar *title_progname, *title_progname_full;
  491. #endif
  492. #ifdef LINUX
  493. static void
  494. rspamd_title_dtor (gpointer d)
  495. {
  496. gchar **env = (gchar **)d;
  497. guint i;
  498. for (i = 0; env[i] != NULL; i++) {
  499. g_free (env[i]);
  500. }
  501. g_free (env);
  502. }
  503. #endif
  504. gint
  505. init_title (rspamd_mempool_t *pool,
  506. gint argc, gchar *argv[], gchar *envp[])
  507. {
  508. #ifdef LINUX
  509. gchar *begin_of_buffer = 0, *end_of_buffer = 0;
  510. gint i;
  511. for (i = 0; i < argc; ++i) {
  512. if (!begin_of_buffer) {
  513. begin_of_buffer = argv[i];
  514. }
  515. if (!end_of_buffer || end_of_buffer + 1 == argv[i]) {
  516. end_of_buffer = argv[i] + strlen (argv[i]);
  517. }
  518. }
  519. for (i = 0; envp[i]; ++i) {
  520. if (!begin_of_buffer) {
  521. begin_of_buffer = envp[i];
  522. }
  523. if (!end_of_buffer || end_of_buffer + 1 == envp[i]) {
  524. end_of_buffer = envp[i] + strlen (envp[i]);
  525. }
  526. }
  527. if (!end_of_buffer) {
  528. return 0;
  529. }
  530. gchar **new_environ = g_malloc ((i + 1) * sizeof (envp[0]));
  531. for (i = 0; envp[i]; ++i) {
  532. new_environ[i] = g_strdup (envp[i]);
  533. }
  534. new_environ[i] = NULL;
  535. if (program_invocation_name) {
  536. title_progname_full = g_strdup (program_invocation_name);
  537. gchar *p = strrchr (title_progname_full, '/');
  538. if (p) {
  539. title_progname = p + 1;
  540. }
  541. else {
  542. title_progname = title_progname_full;
  543. }
  544. program_invocation_name = title_progname_full;
  545. program_invocation_short_name = title_progname;
  546. }
  547. environ = new_environ;
  548. title_buffer = begin_of_buffer;
  549. title_buffer_size = end_of_buffer - begin_of_buffer;
  550. rspamd_mempool_add_destructor (pool,
  551. rspamd_title_dtor, new_environ);
  552. #endif
  553. return 0;
  554. }
  555. gint
  556. setproctitle (const gchar *fmt, ...)
  557. {
  558. #if defined(LINUX)
  559. if (!title_buffer || !title_buffer_size) {
  560. errno = ENOMEM;
  561. return -1;
  562. }
  563. memset (title_buffer, '\0', title_buffer_size);
  564. ssize_t written;
  565. if (fmt) {
  566. va_list ap;
  567. written = rspamd_snprintf (title_buffer,
  568. title_buffer_size,
  569. "%s: ",
  570. title_progname);
  571. if (written < 0 || (size_t) written >= title_buffer_size)
  572. return -1;
  573. va_start (ap, fmt);
  574. rspamd_vsnprintf (title_buffer + written,
  575. title_buffer_size - written,
  576. fmt,
  577. ap);
  578. va_end (ap);
  579. }
  580. else {
  581. written = rspamd_snprintf (title_buffer,
  582. title_buffer_size,
  583. "%s",
  584. title_progname);
  585. if (written < 0 || (size_t) written >= title_buffer_size)
  586. return -1;
  587. }
  588. written = strlen (title_buffer);
  589. memset (title_buffer + written, '\0', title_buffer_size - written);
  590. #elif defined(__APPLE__)
  591. /* OSX is broken, ignore this brain damaged system */
  592. #else
  593. /* Last resort (usually broken, but eh...) */
  594. GString *dest;
  595. va_list ap;
  596. dest = g_string_new ("");
  597. va_start (ap, fmt);
  598. rspamd_vprintf_gstring (dest, fmt, ap);
  599. va_end (ap);
  600. g_set_prgname (dest->str);
  601. g_string_free (dest, TRUE);
  602. #endif
  603. return 0;
  604. }
  605. #endif
  606. #ifndef HAVE_PIDFILE
  607. static gint _rspamd_pidfile_remove (rspamd_pidfh_t *pfh, gint freeit);
  608. static gint
  609. rspamd_pidfile_verify (rspamd_pidfh_t *pfh)
  610. {
  611. struct stat sb;
  612. if (pfh == NULL || pfh->pf_fd == -1)
  613. return (-1);
  614. /*
  615. * Check remembered descriptor.
  616. */
  617. if (fstat (pfh->pf_fd, &sb) == -1)
  618. return (errno);
  619. if (sb.st_dev != pfh->pf_dev || sb.st_ino != pfh->pf_ino)
  620. return -1;
  621. return 0;
  622. }
  623. static gint
  624. rspamd_pidfile_read (const gchar *path, pid_t * pidptr)
  625. {
  626. gchar buf[16], *endptr;
  627. gint error, fd, i;
  628. fd = open (path, O_RDONLY);
  629. if (fd == -1)
  630. return (errno);
  631. i = read (fd, buf, sizeof (buf) - 1);
  632. error = errno; /* Remember errno in case close() wants to change it. */
  633. close (fd);
  634. if (i == -1)
  635. return error;
  636. else if (i == 0)
  637. return EAGAIN;
  638. buf[i] = '\0';
  639. *pidptr = strtol (buf, &endptr, 10);
  640. if (endptr != &buf[i])
  641. return EINVAL;
  642. return 0;
  643. }
  644. rspamd_pidfh_t *
  645. rspamd_pidfile_open (const gchar *path, mode_t mode, pid_t * pidptr)
  646. {
  647. rspamd_pidfh_t *pfh;
  648. struct stat sb;
  649. gint error, fd, len, count;
  650. struct timespec rqtp;
  651. pfh = g_malloc (sizeof (*pfh));
  652. if (pfh == NULL)
  653. return NULL;
  654. if (path == NULL)
  655. len = snprintf (pfh->pf_path,
  656. sizeof (pfh->pf_path),
  657. "/var/run/%s.pid",
  658. g_get_prgname ());
  659. else
  660. len = snprintf (pfh->pf_path, sizeof (pfh->pf_path), "%s", path);
  661. if (len >= (gint)sizeof (pfh->pf_path)) {
  662. g_free (pfh);
  663. errno = ENAMETOOLONG;
  664. return NULL;
  665. }
  666. /*
  667. * Open the PID file and obtain exclusive lock.
  668. * We truncate PID file here only to remove old PID immediatelly,
  669. * PID file will be truncated again in pidfile_write(), so
  670. * pidfile_write() can be called multiple times.
  671. */
  672. fd = open (pfh->pf_path, O_WRONLY | O_CREAT | O_TRUNC | O_NONBLOCK, mode);
  673. rspamd_file_lock (fd, TRUE);
  674. if (fd == -1) {
  675. count = 0;
  676. rqtp.tv_sec = 0;
  677. rqtp.tv_nsec = 5000000;
  678. if (errno == EWOULDBLOCK && pidptr != NULL) {
  679. again:
  680. errno = rspamd_pidfile_read (pfh->pf_path, pidptr);
  681. if (errno == 0)
  682. errno = EEXIST;
  683. else if (errno == EAGAIN) {
  684. if (++count <= 3) {
  685. nanosleep (&rqtp, 0);
  686. goto again;
  687. }
  688. }
  689. }
  690. g_free (pfh);
  691. return NULL;
  692. }
  693. /*
  694. * Remember file information, so in pidfile_write() we are sure we write
  695. * to the proper descriptor.
  696. */
  697. if (fstat (fd, &sb) == -1) {
  698. error = errno;
  699. unlink (pfh->pf_path);
  700. close (fd);
  701. g_free (pfh);
  702. errno = error;
  703. return NULL;
  704. }
  705. pfh->pf_fd = fd;
  706. pfh->pf_dev = sb.st_dev;
  707. pfh->pf_ino = sb.st_ino;
  708. return pfh;
  709. }
  710. gint
  711. rspamd_pidfile_write (rspamd_pidfh_t *pfh)
  712. {
  713. gchar pidstr[16];
  714. gint error, fd;
  715. /*
  716. * Check remembered descriptor, so we don't overwrite some other
  717. * file if pidfile was closed and descriptor reused.
  718. */
  719. errno = rspamd_pidfile_verify (pfh);
  720. if (errno != 0) {
  721. /*
  722. * Don't close descriptor, because we are not sure if it's ours.
  723. */
  724. return -1;
  725. }
  726. fd = pfh->pf_fd;
  727. /*
  728. * Truncate PID file, so multiple calls of pidfile_write() are allowed.
  729. */
  730. if (ftruncate (fd, 0) == -1) {
  731. error = errno;
  732. _rspamd_pidfile_remove (pfh, 0);
  733. errno = error;
  734. return -1;
  735. }
  736. rspamd_snprintf (pidstr, sizeof (pidstr), "%P", getpid ());
  737. if (pwrite (fd, pidstr, strlen (pidstr), 0) != (ssize_t) strlen (pidstr)) {
  738. error = errno;
  739. _rspamd_pidfile_remove (pfh, 0);
  740. errno = error;
  741. return -1;
  742. }
  743. return 0;
  744. }
  745. gint
  746. rspamd_pidfile_close (rspamd_pidfh_t *pfh)
  747. {
  748. gint error;
  749. error = rspamd_pidfile_verify (pfh);
  750. if (error != 0) {
  751. errno = error;
  752. return -1;
  753. }
  754. if (close (pfh->pf_fd) == -1)
  755. error = errno;
  756. g_free (pfh);
  757. if (error != 0) {
  758. errno = error;
  759. return -1;
  760. }
  761. return 0;
  762. }
  763. static gint
  764. _rspamd_pidfile_remove (rspamd_pidfh_t *pfh, gint freeit)
  765. {
  766. gint error;
  767. error = rspamd_pidfile_verify (pfh);
  768. if (error != 0) {
  769. errno = error;
  770. return -1;
  771. }
  772. if (unlink (pfh->pf_path) == -1)
  773. error = errno;
  774. if (!rspamd_file_unlock (pfh->pf_fd, FALSE)) {
  775. if (error == 0)
  776. error = errno;
  777. }
  778. if (close (pfh->pf_fd) == -1) {
  779. if (error == 0)
  780. error = errno;
  781. }
  782. if (freeit)
  783. g_free (pfh);
  784. else
  785. pfh->pf_fd = -1;
  786. if (error != 0) {
  787. errno = error;
  788. return -1;
  789. }
  790. return 0;
  791. }
  792. gint
  793. rspamd_pidfile_remove (rspamd_pidfh_t *pfh)
  794. {
  795. return (_rspamd_pidfile_remove (pfh, 1));
  796. }
  797. #endif
  798. /* Replace %r with rcpt value and %f with from value, new string is allocated in pool */
  799. gchar *
  800. resolve_stat_filename (rspamd_mempool_t * pool,
  801. gchar *pattern,
  802. gchar *rcpt,
  803. gchar *from)
  804. {
  805. gint need_to_format = 0, len = 0;
  806. gint rcptlen, fromlen;
  807. gchar *c = pattern, *new, *s;
  808. if (rcpt) {
  809. rcptlen = strlen (rcpt);
  810. }
  811. else {
  812. rcptlen = 0;
  813. }
  814. if (from) {
  815. fromlen = strlen (from);
  816. }
  817. else {
  818. fromlen = 0;
  819. }
  820. /* Calculate length */
  821. while (*c++) {
  822. if (*c == '%' && *(c + 1) == 'r') {
  823. len += rcptlen;
  824. c += 2;
  825. need_to_format = 1;
  826. continue;
  827. }
  828. else if (*c == '%' && *(c + 1) == 'f') {
  829. len += fromlen;
  830. c += 2;
  831. need_to_format = 1;
  832. continue;
  833. }
  834. len++;
  835. }
  836. /* Do not allocate extra memory if we do not need to format string */
  837. if (!need_to_format) {
  838. return pattern;
  839. }
  840. /* Allocate new string */
  841. new = rspamd_mempool_alloc (pool, len);
  842. c = pattern;
  843. s = new;
  844. /* Format string */
  845. while (*c++) {
  846. if (*c == '%' && *(c + 1) == 'r') {
  847. c += 2;
  848. memcpy (s, rcpt, rcptlen);
  849. s += rcptlen;
  850. continue;
  851. }
  852. *s++ = *c;
  853. }
  854. *s = '\0';
  855. return new;
  856. }
  857. const gchar *
  858. rspamd_log_check_time (gdouble start, gdouble end, gint resolution)
  859. {
  860. gdouble diff;
  861. static gchar res[64];
  862. gchar fmt[32];
  863. diff = (end - start) * 1000.0;
  864. rspamd_snprintf (fmt, sizeof (fmt), "%%.%dfms", resolution);
  865. rspamd_snprintf (res, sizeof (res), fmt, diff);
  866. return (const gchar *)res;
  867. }
  868. #ifdef HAVE_FLOCK
  869. /* Flock version */
  870. gboolean
  871. rspamd_file_lock (gint fd, gboolean async)
  872. {
  873. gint flags;
  874. if (async) {
  875. flags = LOCK_EX | LOCK_NB;
  876. }
  877. else {
  878. flags = LOCK_EX;
  879. }
  880. if (flock (fd, flags) == -1) {
  881. if (async && errno == EAGAIN) {
  882. return FALSE;
  883. }
  884. return FALSE;
  885. }
  886. return TRUE;
  887. }
  888. gboolean
  889. rspamd_file_unlock (gint fd, gboolean async)
  890. {
  891. gint flags;
  892. if (async) {
  893. flags = LOCK_UN | LOCK_NB;
  894. }
  895. else {
  896. flags = LOCK_UN;
  897. }
  898. if (flock (fd, flags) == -1) {
  899. if (async && errno == EAGAIN) {
  900. return FALSE;
  901. }
  902. return FALSE;
  903. }
  904. return TRUE;
  905. }
  906. #else /* HAVE_FLOCK */
  907. /* Fctnl version */
  908. gboolean
  909. rspamd_file_lock (gint fd, gboolean async)
  910. {
  911. struct flock fl = {
  912. .l_type = F_WRLCK,
  913. .l_whence = SEEK_SET,
  914. .l_start = 0,
  915. .l_len = 0
  916. };
  917. if (fcntl (fd, async ? F_SETLK : F_SETLKW, &fl) == -1) {
  918. if (async && (errno == EAGAIN || errno == EACCES)) {
  919. return FALSE;
  920. }
  921. if (errno != ENOTSUP) {
  922. msg_warn ("lock on file failed: %s", strerror (errno));
  923. }
  924. return FALSE;
  925. }
  926. return TRUE;
  927. }
  928. gboolean
  929. rspamd_file_unlock (gint fd, gboolean async)
  930. {
  931. struct flock fl = {
  932. .l_type = F_UNLCK,
  933. .l_whence = SEEK_SET,
  934. .l_start = 0,
  935. .l_len = 0
  936. };
  937. if (fcntl (fd, async ? F_SETLK : F_SETLKW, &fl) == -1) {
  938. if (async && (errno == EAGAIN || errno == EACCES)) {
  939. return FALSE;
  940. }
  941. if (errno != ENOTSUP) {
  942. msg_warn ("unlock on file failed: %s", strerror (errno));
  943. }
  944. return FALSE;
  945. }
  946. return TRUE;
  947. }
  948. #endif /* HAVE_FLOCK */
  949. #if ((GLIB_MAJOR_VERSION == 2) && (GLIB_MINOR_VERSION < 22))
  950. void
  951. g_ptr_array_unref (GPtrArray *array)
  952. {
  953. g_ptr_array_free (array, TRUE);
  954. }
  955. gboolean
  956. g_int64_equal (gconstpointer v1, gconstpointer v2)
  957. {
  958. return *((const gint64*) v1) == *((const gint64*) v2);
  959. }
  960. guint
  961. g_int64_hash (gconstpointer v)
  962. {
  963. guint64 v64 = *(guint64 *)v;
  964. return (guint) (v ^ (v >> 32));
  965. }
  966. #endif
  967. #if ((GLIB_MAJOR_VERSION == 2) && (GLIB_MINOR_VERSION < 14))
  968. void
  969. g_queue_clear (GQueue *queue)
  970. {
  971. g_return_if_fail (queue != NULL);
  972. g_list_free (queue->head);
  973. queue->head = queue->tail = NULL;
  974. queue->length = 0;
  975. }
  976. #endif
  977. #if ((GLIB_MAJOR_VERSION == 2) && (GLIB_MINOR_VERSION < 30))
  978. GPtrArray*
  979. g_ptr_array_new_full (guint reserved_size,
  980. GDestroyNotify element_free_func)
  981. {
  982. GPtrArray *array;
  983. array = g_ptr_array_sized_new (reserved_size);
  984. g_ptr_array_set_free_func (array, element_free_func);
  985. return array;
  986. }
  987. #endif
  988. #if ((GLIB_MAJOR_VERSION == 2) && (GLIB_MINOR_VERSION < 32))
  989. void
  990. g_queue_free_full (GQueue *queue, GDestroyNotify free_func)
  991. {
  992. GList *cur;
  993. cur = queue->head;
  994. while (cur) {
  995. free_func (cur->data);
  996. cur = g_list_next (cur);
  997. }
  998. g_queue_free (queue);
  999. }
  1000. #endif
  1001. #if ((GLIB_MAJOR_VERSION == 2) && (GLIB_MINOR_VERSION < 40))
  1002. void
  1003. g_ptr_array_insert (GPtrArray *array, gint index_, gpointer data)
  1004. {
  1005. g_return_if_fail (array);
  1006. g_return_if_fail (index_ >= -1);
  1007. g_return_if_fail (index_ <= (gint )array->len);
  1008. g_ptr_array_set_size (array, array->len + 1);
  1009. if (index_ < 0) {
  1010. index_ = array->len;
  1011. }
  1012. if (index_ < array->len) {
  1013. memmove (&(array->pdata[index_ + 1]), &(array->pdata[index_]),
  1014. (array->len - index_) * sizeof(gpointer));
  1015. }
  1016. array->pdata[index_] = data;
  1017. }
  1018. #endif
  1019. #if ((GLIB_MAJOR_VERSION == 2) && (GLIB_MINOR_VERSION < 32))
  1020. const gchar *
  1021. g_environ_getenv (gchar **envp, const gchar *variable)
  1022. {
  1023. gsize len;
  1024. gint i;
  1025. if (envp == NULL) {
  1026. return NULL;
  1027. }
  1028. len = strlen (variable);
  1029. for (i = 0; envp[i]; i++) {
  1030. if (strncmp (envp[i], variable, len) == 0 && envp[i][len] == '=') {
  1031. return envp[i] + len + 1;
  1032. }
  1033. }
  1034. return NULL;
  1035. }
  1036. #endif
  1037. gint
  1038. rspamd_fallocate (gint fd, off_t offset, off_t len)
  1039. {
  1040. #if defined(HAVE_FALLOCATE)
  1041. return fallocate (fd, 0, offset, len);
  1042. #elif defined(HAVE_POSIX_FALLOCATE)
  1043. return posix_fallocate (fd, offset, len);
  1044. #else
  1045. /* Return 0 as nothing can be done on this system */
  1046. return 0;
  1047. #endif
  1048. }
  1049. /**
  1050. * Create new mutex
  1051. * @return mutex or NULL
  1052. */
  1053. inline rspamd_mutex_t *
  1054. rspamd_mutex_new (void)
  1055. {
  1056. rspamd_mutex_t *new;
  1057. new = g_malloc0 (sizeof (rspamd_mutex_t));
  1058. #if ((GLIB_MAJOR_VERSION == 2) && (GLIB_MINOR_VERSION > 30))
  1059. g_mutex_init (&new->mtx);
  1060. #else
  1061. g_static_mutex_init (&new->mtx);
  1062. #endif
  1063. return new;
  1064. }
  1065. /**
  1066. * Lock mutex
  1067. * @param mtx
  1068. */
  1069. inline void
  1070. rspamd_mutex_lock (rspamd_mutex_t *mtx)
  1071. {
  1072. #if ((GLIB_MAJOR_VERSION == 2) && (GLIB_MINOR_VERSION > 30))
  1073. g_mutex_lock (&mtx->mtx);
  1074. #else
  1075. g_static_mutex_lock (&mtx->mtx);
  1076. #endif
  1077. }
  1078. /**
  1079. * Unlock mutex
  1080. * @param mtx
  1081. */
  1082. inline void
  1083. rspamd_mutex_unlock (rspamd_mutex_t *mtx)
  1084. {
  1085. #if ((GLIB_MAJOR_VERSION == 2) && (GLIB_MINOR_VERSION > 30))
  1086. g_mutex_unlock (&mtx->mtx);
  1087. #else
  1088. g_static_mutex_unlock (&mtx->mtx);
  1089. #endif
  1090. }
  1091. void
  1092. rspamd_mutex_free (rspamd_mutex_t *mtx)
  1093. {
  1094. #if ((GLIB_MAJOR_VERSION == 2) && (GLIB_MINOR_VERSION > 30))
  1095. g_mutex_clear (&mtx->mtx);
  1096. #endif
  1097. g_free (mtx);
  1098. }
  1099. struct rspamd_thread_data {
  1100. gchar *name;
  1101. gint id;
  1102. GThreadFunc func;
  1103. gpointer data;
  1104. };
  1105. static gpointer
  1106. rspamd_thread_func (gpointer ud)
  1107. {
  1108. struct rspamd_thread_data *td = ud;
  1109. sigset_t s_mask;
  1110. /* Ignore signals in thread */
  1111. sigemptyset (&s_mask);
  1112. sigaddset (&s_mask, SIGINT);
  1113. sigaddset (&s_mask, SIGHUP);
  1114. sigaddset (&s_mask, SIGCHLD);
  1115. sigaddset (&s_mask, SIGUSR1);
  1116. sigaddset (&s_mask, SIGUSR2);
  1117. sigaddset (&s_mask, SIGALRM);
  1118. sigaddset (&s_mask, SIGPIPE);
  1119. pthread_sigmask (SIG_BLOCK, &s_mask, NULL);
  1120. ud = td->func (td->data);
  1121. g_free (td->name);
  1122. g_free (td);
  1123. return ud;
  1124. }
  1125. struct hash_copy_callback_data {
  1126. gpointer (*key_copy_func)(gconstpointer data, gpointer ud);
  1127. gpointer (*value_copy_func)(gconstpointer data, gpointer ud);
  1128. gpointer ud;
  1129. GHashTable *dst;
  1130. };
  1131. static void
  1132. copy_foreach_callback (gpointer key, gpointer value, gpointer ud)
  1133. {
  1134. struct hash_copy_callback_data *cb = ud;
  1135. gpointer nkey, nvalue;
  1136. nkey = cb->key_copy_func ? cb->key_copy_func (key, cb->ud) : (gpointer)key;
  1137. nvalue =
  1138. cb->value_copy_func ? cb->value_copy_func (value,
  1139. cb->ud) : (gpointer)value;
  1140. g_hash_table_insert (cb->dst, nkey, nvalue);
  1141. }
  1142. /**
  1143. * Deep copy of one hash table to another
  1144. * @param src source hash
  1145. * @param dst destination hash
  1146. * @param key_copy_func function called to copy or modify keys (or NULL)
  1147. * @param value_copy_func function called to copy or modify values (or NULL)
  1148. * @param ud user data for copy functions
  1149. */
  1150. void
  1151. rspamd_hash_table_copy (GHashTable *src, GHashTable *dst,
  1152. gpointer (*key_copy_func)(gconstpointer data, gpointer ud),
  1153. gpointer (*value_copy_func)(gconstpointer data, gpointer ud),
  1154. gpointer ud)
  1155. {
  1156. struct hash_copy_callback_data cb;
  1157. if (src != NULL && dst != NULL) {
  1158. cb.key_copy_func = key_copy_func;
  1159. cb.value_copy_func = value_copy_func;
  1160. cb.ud = ud;
  1161. cb.dst = dst;
  1162. g_hash_table_foreach (src, copy_foreach_callback, &cb);
  1163. }
  1164. }
  1165. static volatile sig_atomic_t saved_signo[NSIG];
  1166. static
  1167. void
  1168. read_pass_tmp_sig_handler (int s)
  1169. {
  1170. saved_signo[s] = 1;
  1171. }
  1172. #ifndef _PATH_TTY
  1173. # define _PATH_TTY "/dev/tty"
  1174. #endif
  1175. gint
  1176. rspamd_read_passphrase (gchar *buf, gint size, gint rwflag, gpointer key)
  1177. {
  1178. #ifdef HAVE_PASSPHRASE_H
  1179. gint len = 0;
  1180. gchar pass[BUFSIZ];
  1181. if (readpassphrase ("Enter passphrase: ", buf, size, RPP_ECHO_OFF |
  1182. RPP_REQUIRE_TTY) == NULL) {
  1183. return 0;
  1184. }
  1185. return strlen (buf);
  1186. #else
  1187. struct sigaction sa, savealrm, saveint, savehup, savequit, saveterm;
  1188. struct sigaction savetstp, savettin, savettou, savepipe;
  1189. struct termios term, oterm;
  1190. gint input, output, i;
  1191. gchar *end, *p, ch;
  1192. restart:
  1193. if ((input = output = open (_PATH_TTY, O_RDWR)) == -1) {
  1194. errno = ENOTTY;
  1195. return 0;
  1196. }
  1197. (void)fcntl (input, F_SETFD, FD_CLOEXEC);
  1198. /* Turn echo off */
  1199. if (tcgetattr (input, &oterm) != 0) {
  1200. close (input);
  1201. errno = ENOTTY;
  1202. return 0;
  1203. }
  1204. memcpy (&term, &oterm, sizeof(term));
  1205. term.c_lflag &= ~(ECHO | ECHONL);
  1206. if (tcsetattr (input, TCSAFLUSH, &term) == -1) {
  1207. errno = ENOTTY;
  1208. close (input);
  1209. return 0;
  1210. }
  1211. g_assert (write (output, "Enter passphrase: ", sizeof ("Enter passphrase: ") -
  1212. 1) != -1);
  1213. /* Save the current sighandler */
  1214. for (i = 0; i < NSIG; i++) {
  1215. saved_signo[i] = 0;
  1216. }
  1217. sigemptyset (&sa.sa_mask);
  1218. sa.sa_flags = 0;
  1219. sa.sa_handler = read_pass_tmp_sig_handler;
  1220. (void)sigaction (SIGALRM, &sa, &savealrm);
  1221. (void)sigaction (SIGHUP, &sa, &savehup);
  1222. (void)sigaction (SIGINT, &sa, &saveint);
  1223. (void)sigaction (SIGPIPE, &sa, &savepipe);
  1224. (void)sigaction (SIGQUIT, &sa, &savequit);
  1225. (void)sigaction (SIGTERM, &sa, &saveterm);
  1226. (void)sigaction (SIGTSTP, &sa, &savetstp);
  1227. (void)sigaction (SIGTTIN, &sa, &savettin);
  1228. (void)sigaction (SIGTTOU, &sa, &savettou);
  1229. /* Now read a passphrase */
  1230. p = buf;
  1231. end = p + size - 1;
  1232. while (read (input, &ch, 1) == 1 && ch != '\n' && ch != '\r') {
  1233. if (p < end) {
  1234. *p++ = ch;
  1235. }
  1236. }
  1237. *p = '\0';
  1238. g_assert (write (output, "\n", 1) == 1);
  1239. /* Restore terminal state */
  1240. if (memcmp (&term, &oterm, sizeof (term)) != 0) {
  1241. while (tcsetattr (input, TCSAFLUSH, &oterm) == -1 &&
  1242. errno == EINTR && !saved_signo[SIGTTOU]) ;
  1243. }
  1244. /* Restore signal handlers */
  1245. (void)sigaction (SIGALRM, &savealrm, NULL);
  1246. (void)sigaction (SIGHUP, &savehup, NULL);
  1247. (void)sigaction (SIGINT, &saveint, NULL);
  1248. (void)sigaction (SIGQUIT, &savequit, NULL);
  1249. (void)sigaction (SIGPIPE, &savepipe, NULL);
  1250. (void)sigaction (SIGTERM, &saveterm, NULL);
  1251. (void)sigaction (SIGTSTP, &savetstp, NULL);
  1252. (void)sigaction (SIGTTIN, &savettin, NULL);
  1253. (void)sigaction (SIGTTOU, &savettou, NULL);
  1254. close (input);
  1255. /* Send signals pending */
  1256. for (i = 0; i < NSIG; i++) {
  1257. if (saved_signo[i]) {
  1258. kill (getpid (), i);
  1259. switch (i) {
  1260. case SIGTSTP:
  1261. case SIGTTIN:
  1262. case SIGTTOU:
  1263. goto restart;
  1264. }
  1265. }
  1266. }
  1267. return (p - buf);
  1268. #endif
  1269. }
  1270. #ifdef HAVE_CLOCK_GETTIME
  1271. # ifdef CLOCK_MONOTONIC_COARSE
  1272. # define RSPAMD_FAST_MONOTONIC_CLOCK CLOCK_MONOTONIC_COARSE
  1273. # elif defined(CLOCK_MONOTONIC_FAST)
  1274. # define RSPAMD_FAST_MONOTONIC_CLOCK CLOCK_MONOTONIC_FAST
  1275. # else
  1276. # define RSPAMD_FAST_MONOTONIC_CLOCK CLOCK_MONOTONIC
  1277. # endif
  1278. #endif
  1279. gdouble
  1280. rspamd_get_ticks (gboolean rdtsc_ok)
  1281. {
  1282. gdouble res;
  1283. #ifdef HAVE_RDTSC
  1284. # ifdef __x86_64__
  1285. guint64 r64;
  1286. if (rdtsc_ok) {
  1287. __builtin_ia32_lfence ();
  1288. r64 = __rdtsc ();
  1289. /* Preserve lower 52 bits */
  1290. res = r64 & ((1ULL << 53) - 1);
  1291. return res;
  1292. }
  1293. # endif
  1294. #endif
  1295. #ifdef HAVE_CLOCK_GETTIME
  1296. struct timespec ts;
  1297. gint clk_id = RSPAMD_FAST_MONOTONIC_CLOCK;
  1298. clock_gettime (clk_id, &ts);
  1299. if (rdtsc_ok) {
  1300. res = (double) ts.tv_sec * 1e9 + ts.tv_nsec;
  1301. }
  1302. else {
  1303. res = (double) ts.tv_sec + ts.tv_nsec / 1000000000.;
  1304. }
  1305. # elif defined(__APPLE__)
  1306. if (rdtsc_ok) {
  1307. res = mach_absolute_time ();
  1308. }
  1309. else {
  1310. res = mach_absolute_time () / 1000000000.;
  1311. }
  1312. #else
  1313. struct timeval tv;
  1314. (void)gettimeofday (&tv, NULL);
  1315. if (rdtsc_ok) {
  1316. res = (double) ts.tv_sec * 1e9 + tv.tv_usec * 1e3;
  1317. }
  1318. else {
  1319. res = (double)tv.tv_sec + tv.tv_usec / 1000000.;
  1320. }
  1321. #endif
  1322. return res;
  1323. }
  1324. gdouble
  1325. rspamd_get_virtual_ticks (void)
  1326. {
  1327. gdouble res;
  1328. #ifdef HAVE_CLOCK_GETTIME
  1329. struct timespec ts;
  1330. static clockid_t cid = (clockid_t)-1;
  1331. if (cid == (clockid_t)-1) {
  1332. # ifdef HAVE_CLOCK_GETCPUCLOCKID
  1333. if (clock_getcpuclockid (0, &cid) == -1) {
  1334. # endif
  1335. # ifdef CLOCK_PROCESS_CPUTIME_ID
  1336. cid = CLOCK_PROCESS_CPUTIME_ID;
  1337. # elif defined(CLOCK_PROF)
  1338. cid = CLOCK_PROF;
  1339. # else
  1340. cid = CLOCK_REALTIME;
  1341. # endif
  1342. # ifdef HAVE_CLOCK_GETCPUCLOCKID
  1343. }
  1344. # endif
  1345. }
  1346. clock_gettime (cid, &ts);
  1347. res = (double)ts.tv_sec + ts.tv_nsec / 1000000000.;
  1348. #elif defined(__APPLE__)
  1349. thread_port_t thread = mach_thread_self ();
  1350. mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
  1351. thread_basic_info_data_t info;
  1352. if (thread_info (thread, THREAD_BASIC_INFO, (thread_info_t)&info, &count) != KERN_SUCCESS) {
  1353. return -1;
  1354. }
  1355. res = info.user_time.seconds + info.system_time.seconds;
  1356. res += ((gdouble)(info.user_time.microseconds + info.system_time.microseconds)) / 1e6;
  1357. mach_port_deallocate(mach_task_self(), thread);
  1358. #elif defined(HAVE_RUSAGE_SELF)
  1359. struct rusage rusage;
  1360. if (getrusage (RUSAGE_SELF, &rusage) != -1) {
  1361. res = (double) rusage.ru_utime.tv_sec +
  1362. (double) rusage.ru_utime.tv_usec / 1000000.0;
  1363. }
  1364. #else
  1365. res = clock () / (double)CLOCKS_PER_SEC;
  1366. #endif
  1367. return res;
  1368. }
  1369. gdouble
  1370. rspamd_get_calendar_ticks (void)
  1371. {
  1372. gdouble res;
  1373. #ifdef HAVE_CLOCK_GETTIME
  1374. struct timespec ts;
  1375. clock_gettime (CLOCK_REALTIME, &ts);
  1376. res = ts_to_double (&ts);
  1377. #else
  1378. struct timeval tv;
  1379. if (gettimeofday (&tv, NULL) == 0) {
  1380. res = tv_to_double (&tv);
  1381. }
  1382. else {
  1383. res = time (NULL);
  1384. }
  1385. #endif
  1386. return res;
  1387. }
  1388. void
  1389. rspamd_random_hex (guchar *buf, guint64 len)
  1390. {
  1391. static const gchar hexdigests[16] = "0123456789abcdef";
  1392. gint64 i;
  1393. g_assert (len > 0);
  1394. ottery_rand_bytes (buf, ceil (len / 2.0));
  1395. for (i = (gint64)len - 1; i >= 0; i -= 2) {
  1396. buf[i] = hexdigests[buf[i / 2] & 0xf];
  1397. if (i > 0) {
  1398. buf[i - 1] = hexdigests[(buf[i / 2] >> 4) & 0xf];
  1399. }
  1400. }
  1401. }
  1402. gint
  1403. rspamd_shmem_mkstemp (gchar *pattern)
  1404. {
  1405. gint fd = -1;
  1406. gchar *nbuf, *xpos;
  1407. gsize blen;
  1408. xpos = strchr (pattern, 'X');
  1409. if (xpos == NULL) {
  1410. errno = EINVAL;
  1411. return -1;
  1412. }
  1413. blen = strlen (pattern);
  1414. nbuf = g_malloc (blen + 1);
  1415. rspamd_strlcpy (nbuf, pattern, blen + 1);
  1416. xpos = nbuf + (xpos - pattern);
  1417. for (;;) {
  1418. rspamd_random_hex (xpos, blen - (xpos - nbuf));
  1419. fd = shm_open (nbuf, O_RDWR | O_EXCL | O_CREAT, 0600);
  1420. if (fd != -1) {
  1421. rspamd_strlcpy (pattern, nbuf, blen + 1);
  1422. break;
  1423. }
  1424. else if (errno != EEXIST) {
  1425. g_free (nbuf);
  1426. return -1;
  1427. }
  1428. }
  1429. g_free (nbuf);
  1430. return fd;
  1431. }
  1432. void
  1433. rspamd_ptr_array_free_hard (gpointer p)
  1434. {
  1435. GPtrArray *ar = (GPtrArray *)p;
  1436. g_ptr_array_free (ar, TRUE);
  1437. }
  1438. void
  1439. rspamd_array_free_hard (gpointer p)
  1440. {
  1441. GArray *ar = (GArray *)p;
  1442. g_array_free (ar, TRUE);
  1443. }
  1444. void
  1445. rspamd_gstring_free_hard (gpointer p)
  1446. {
  1447. GString *ar = (GString *)p;
  1448. g_string_free (ar, TRUE);
  1449. }
  1450. void rspamd_gerror_free_maybe (gpointer p)
  1451. {
  1452. GError **err;
  1453. if (p) {
  1454. err = (GError **)p;
  1455. if (*err) {
  1456. g_error_free (*err);
  1457. }
  1458. }
  1459. }
  1460. /*
  1461. * Openblas creates threads that are not supported by
  1462. * jemalloc allocator (aside of being bloody stupid). So this hack
  1463. * is intended to set number of threads to one by default.
  1464. * FIXME: is it legit to do so in ctor?
  1465. */
  1466. #ifdef HAVE_OPENBLAS_SET_NUM_THREADS
  1467. extern void openblas_set_num_threads(int num_threads);
  1468. RSPAMD_CONSTRUCTOR (openblas_thread_fix_ctor)
  1469. {
  1470. bli_thread_set_num_threads (1;
  1471. }
  1472. #endif
  1473. #ifdef HAVE_BLI_THREAD_SET_NUM_THREADS
  1474. extern void bli_thread_set_num_threads(int num_threads);
  1475. RSPAMD_CONSTRUCTOR (blis_thread_fix_ctor)
  1476. {
  1477. bli_thread_set_num_threads (1;
  1478. }
  1479. #endif
  1480. guint64
  1481. rspamd_hash_seed (void)
  1482. {
  1483. #if 0
  1484. static guint64 seed;
  1485. if (seed == 0) {
  1486. seed = ottery_rand_uint64 ();
  1487. }
  1488. #endif
  1489. /* Proved to be random, I promise! */
  1490. /*
  1491. * TODO: discover if it worth to use random seed on run
  1492. * with ordinary hash function or we need to switch to
  1493. * siphash1-3 or other slow cooker function...
  1494. */
  1495. return 0xabf9727ba290690bULL;
  1496. }
  1497. static inline gdouble
  1498. rspamd_double_from_int64 (guint64 x)
  1499. {
  1500. const union { guint64 i; double d; } u = {
  1501. .i = G_GUINT64_CONSTANT(0x3FF) << 52 | x >> 12
  1502. };
  1503. return u.d - 1.0;
  1504. }
  1505. gdouble
  1506. rspamd_random_double (void)
  1507. {
  1508. guint64 rnd_int;
  1509. rnd_int = ottery_rand_uint64 ();
  1510. return rspamd_double_from_int64 (rnd_int);
  1511. }
  1512. static guint64 xorshifto_seed[4];
  1513. static inline guint64
  1514. xoroshiro_rotl (const guint64 x, int k) {
  1515. return (x << k) | (x >> (64 - k));
  1516. }
  1517. gdouble
  1518. rspamd_random_double_fast (void)
  1519. {
  1520. return rspamd_random_double_fast_seed (xorshifto_seed);
  1521. }
  1522. /* xoshiro256+ */
  1523. inline gdouble
  1524. rspamd_random_double_fast_seed (guint64 seed[4])
  1525. {
  1526. const uint64_t result = seed[0] + seed[3];
  1527. const uint64_t t = seed[1] << 17;
  1528. seed[2] ^= seed[0];
  1529. seed[3] ^= seed[1];
  1530. seed[1] ^= seed[2];
  1531. seed[0] ^= seed[3];
  1532. seed[2] ^= t;
  1533. seed[3] = xoroshiro_rotl (seed[3], 45);
  1534. return rspamd_double_from_int64 (result);
  1535. }
  1536. /* xoroshiro256** */
  1537. static inline guint64
  1538. rspamd_random_uint64_fast_seed (guint64 seed[4])
  1539. {
  1540. const uint64_t result = xoroshiro_rotl (seed[1] * 5, 7) * 9;
  1541. const uint64_t t = seed[1] << 17;
  1542. seed[2] ^= seed[0];
  1543. seed[3] ^= seed[1];
  1544. seed[1] ^= seed[2];
  1545. seed[0] ^= seed[3];
  1546. seed[2] ^= t;
  1547. seed[3] = xoroshiro_rotl (seed[3], 45);
  1548. return result;
  1549. }
  1550. guint64
  1551. rspamd_random_uint64_fast (void)
  1552. {
  1553. return rspamd_random_uint64_fast_seed (xorshifto_seed);
  1554. }
  1555. void
  1556. rspamd_random_seed_fast (void)
  1557. {
  1558. ottery_rand_bytes (xorshifto_seed, sizeof (xorshifto_seed));
  1559. }
  1560. gdouble
  1561. rspamd_time_jitter (gdouble in, gdouble jitter)
  1562. {
  1563. if (jitter == 0) {
  1564. jitter = in;
  1565. }
  1566. return in + jitter * rspamd_random_double ();
  1567. }
  1568. gboolean
  1569. rspamd_constant_memcmp (const void *a, const void *b, gsize len)
  1570. {
  1571. gsize lena, lenb, i;
  1572. guint16 d, r = 0, m;
  1573. guint16 v;
  1574. const guint8 *aa = (const guint8 *)a,
  1575. *bb = (const guint8 *)b;
  1576. if (len == 0) {
  1577. lena = strlen ((const char*)a);
  1578. lenb = strlen ((const char*)b);
  1579. if (lena != lenb) {
  1580. return FALSE;
  1581. }
  1582. len = lena;
  1583. }
  1584. for (i = 0; i < len; i++) {
  1585. v = ((guint16)(guint8)r) + 255;
  1586. m = v / 256 - 1;
  1587. d = (guint16)((int)aa[i] - (int)bb[i]);
  1588. r |= (d & m);
  1589. }
  1590. return (((gint32)(guint16)((guint32)r + 0x8000) - 0x8000) == 0);
  1591. }
  1592. int
  1593. rspamd_file_xopen (const char *fname, int oflags, guint mode,
  1594. gboolean allow_symlink)
  1595. {
  1596. struct stat sb;
  1597. int fd, flags = oflags;
  1598. if (lstat (fname, &sb) == -1) {
  1599. if (errno != ENOENT) {
  1600. return (-1);
  1601. }
  1602. }
  1603. else if (!S_ISREG (sb.st_mode)) {
  1604. if (S_ISLNK (sb.st_mode)) {
  1605. if (!allow_symlink) {
  1606. return -1;
  1607. }
  1608. }
  1609. else {
  1610. return -1;
  1611. }
  1612. }
  1613. #ifdef HAVE_OCLOEXEC
  1614. flags |= O_CLOEXEC;
  1615. #endif
  1616. #ifdef HAVE_ONOFOLLOW
  1617. if (!allow_symlink) {
  1618. flags |= O_NOFOLLOW;
  1619. fd = open (fname, flags, mode);
  1620. }
  1621. else {
  1622. fd = open (fname, flags, mode);
  1623. }
  1624. #else
  1625. fd = open (fname, flags, mode);
  1626. #endif
  1627. #ifndef HAVE_OCLOEXEC
  1628. if (fcntl (fd, F_SETFD, FD_CLOEXEC) == -1) {
  1629. msg_warn ("fcntl failed: %d, '%s'", errno, strerror (errno));
  1630. close (fd);
  1631. return -1;
  1632. }
  1633. #endif
  1634. return (fd);
  1635. }
  1636. gpointer
  1637. rspamd_file_xmap (const char *fname, guint mode, gsize *size,
  1638. gboolean allow_symlink)
  1639. {
  1640. gint fd;
  1641. struct stat sb;
  1642. gpointer map;
  1643. g_assert (fname != NULL);
  1644. g_assert (size != NULL);
  1645. if (mode & PROT_WRITE) {
  1646. fd = rspamd_file_xopen (fname, O_RDWR, 0, allow_symlink);
  1647. }
  1648. else {
  1649. fd = rspamd_file_xopen (fname, O_RDONLY, 0, allow_symlink);
  1650. }
  1651. if (fd == -1) {
  1652. return NULL;
  1653. }
  1654. if (fstat (fd, &sb) == -1 || !S_ISREG (sb.st_mode)) {
  1655. close (fd);
  1656. *size = (gsize)-1;
  1657. return NULL;
  1658. }
  1659. if (sb.st_size == 0) {
  1660. close (fd);
  1661. *size = (gsize)0;
  1662. return NULL;
  1663. }
  1664. map = mmap (NULL, sb.st_size, mode, MAP_SHARED, fd, 0);
  1665. close (fd);
  1666. if (map == MAP_FAILED) {
  1667. return NULL;
  1668. }
  1669. *size = sb.st_size;
  1670. return map;
  1671. }
  1672. gpointer
  1673. rspamd_shmem_xmap (const char *fname, guint mode,
  1674. gsize *size)
  1675. {
  1676. gint fd;
  1677. struct stat sb;
  1678. gpointer map;
  1679. g_assert (fname != NULL);
  1680. g_assert (size != NULL);
  1681. #ifdef HAVE_SANE_SHMEM
  1682. if (mode & PROT_WRITE) {
  1683. fd = shm_open (fname, O_RDWR, 0);
  1684. }
  1685. else {
  1686. fd = shm_open (fname, O_RDONLY, 0);
  1687. }
  1688. #else
  1689. if (mode & PROT_WRITE) {
  1690. fd = open (fname, O_RDWR, 0);
  1691. }
  1692. else {
  1693. fd = open (fname, O_RDONLY, 0);
  1694. }
  1695. #endif
  1696. if (fd == -1) {
  1697. return NULL;
  1698. }
  1699. if (fstat (fd, &sb) == -1) {
  1700. close (fd);
  1701. return NULL;
  1702. }
  1703. map = mmap (NULL, sb.st_size, mode, MAP_SHARED, fd, 0);
  1704. close (fd);
  1705. if (map == MAP_FAILED) {
  1706. return NULL;
  1707. }
  1708. *size = sb.st_size;
  1709. return map;
  1710. }
  1711. /*
  1712. * A(x - 0.5)^4 + B(x - 0.5)^3 + C(x - 0.5)^2 + D(x - 0.5)
  1713. * A = 32,
  1714. * B = -6
  1715. * C = -7
  1716. * D = 3
  1717. * y = 32(x - 0.5)^4 - 6(x - 0.5)^3 - 7(x - 0.5)^2 + 3(x - 0.5)
  1718. *
  1719. * New approach:
  1720. * y = ((x - bias)*2)^8
  1721. */
  1722. gdouble
  1723. rspamd_normalize_probability (gdouble x, gdouble bias)
  1724. {
  1725. gdouble xx;
  1726. xx = (x - bias) * 2.0;
  1727. return pow (xx, 8);
  1728. }
  1729. /*
  1730. * Calculations from musl libc
  1731. */
  1732. guint64
  1733. rspamd_tm_to_time (const struct tm *tm, glong tz)
  1734. {
  1735. guint64 result;
  1736. gboolean is_leap = FALSE;
  1737. gint leaps, y = tm->tm_year, cycles, rem, centuries;
  1738. glong offset = (tz / 100) * 3600 + (tz % 100) * 60;
  1739. /* How many seconds in each month from the beginning of the year */
  1740. static const gint secs_through_month[] = {
  1741. 0, 31*86400, 59*86400, 90*86400,
  1742. 120*86400, 151*86400, 181*86400, 212*86400,
  1743. 243*86400, 273*86400, 304*86400, 334*86400
  1744. };
  1745. /* Convert year */
  1746. if (tm->tm_year - 2ULL <= 136) {
  1747. leaps = (y - 68) / 4;
  1748. if (!((y - 68) & 3)) {
  1749. leaps--;
  1750. is_leap = 1;
  1751. }
  1752. result = 31536000 * (y - 70) + 86400 * leaps;
  1753. }
  1754. else {
  1755. cycles = (y - 100) / 400;
  1756. rem = (y - 100) % 400;
  1757. if (rem < 0) {
  1758. cycles--;
  1759. rem += 400;
  1760. }
  1761. if (!rem) {
  1762. is_leap = 1;
  1763. centuries = 0;
  1764. leaps = 0;
  1765. }
  1766. else {
  1767. if (rem >= 200) {
  1768. if (rem >= 300) {
  1769. centuries = 3;
  1770. rem -= 300;
  1771. }
  1772. else {
  1773. centuries = 2;
  1774. rem -= 200;
  1775. }
  1776. }
  1777. else {
  1778. if (rem >= 100) {
  1779. centuries = 1;
  1780. rem -= 100;
  1781. }
  1782. else {
  1783. centuries = 0;
  1784. }
  1785. }
  1786. if (!rem) {
  1787. is_leap = 1;
  1788. leaps = 0;
  1789. } else {
  1790. leaps = rem / 4U;
  1791. rem %= 4U;
  1792. is_leap = !rem;
  1793. }
  1794. }
  1795. leaps += 97 * cycles + 24 * centuries - (gint)is_leap;
  1796. result = (y - 100) * 31536000LL + leaps * 86400LL + 946684800 + 86400;
  1797. }
  1798. /* Now convert months to seconds */
  1799. result += secs_through_month[tm->tm_mon];
  1800. /* One more day */
  1801. if (is_leap && tm->tm_mon >= 2) {
  1802. result += 86400;
  1803. }
  1804. result += 86400LL * (tm->tm_mday-1);
  1805. result += 3600LL * tm->tm_hour;
  1806. result += 60LL * tm->tm_min;
  1807. result += tm->tm_sec;
  1808. /* Now apply tz offset */
  1809. result -= offset;
  1810. return result;
  1811. }
  1812. void
  1813. rspamd_gmtime (gint64 ts, struct tm *dest)
  1814. {
  1815. guint64 days, secs, years;
  1816. int remdays, remsecs, remyears;
  1817. int leap_400_cycles, leap_100_cycles, leap_4_cycles;
  1818. int months;
  1819. int wday, yday, leap;
  1820. /* From March */
  1821. static const uint8_t days_in_month[] = {31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29};
  1822. static const guint64 leap_epoch = 946684800ULL + 86400 * (31 + 29);
  1823. static const guint64 days_per_400y = 365*400 + 97;
  1824. static const guint64 days_per_100y = 365*100 + 24;
  1825. static const guint64 days_per_4y = 365*4 + 1;
  1826. secs = ts - leap_epoch;
  1827. days = secs / 86400;
  1828. remsecs = secs % 86400;
  1829. if (remsecs < 0) {
  1830. remsecs += 86400;
  1831. days--;
  1832. }
  1833. wday = (3 + days) % 7;
  1834. if (wday < 0) {
  1835. wday += 7;
  1836. }
  1837. /* Deal with gregorian adjustments */
  1838. leap_400_cycles = days / days_per_400y;
  1839. remdays = days % days_per_400y;
  1840. if (remdays < 0) {
  1841. remdays += days_per_400y;
  1842. leap_400_cycles--;
  1843. }
  1844. leap_100_cycles = remdays / days_per_100y;
  1845. if (leap_100_cycles == 4) {
  1846. /* 400 years */
  1847. leap_100_cycles--;
  1848. }
  1849. remdays -= leap_100_cycles * days_per_100y;
  1850. leap_4_cycles = remdays / days_per_4y;
  1851. if (leap_4_cycles == 25) {
  1852. /* 100 years */
  1853. leap_4_cycles--;
  1854. }
  1855. remdays -= leap_4_cycles * days_per_4y;
  1856. remyears = remdays / 365;
  1857. if (remyears == 4) {
  1858. /* Ordinary leap year */
  1859. remyears--;
  1860. }
  1861. remdays -= remyears * 365;
  1862. leap = !remyears && (leap_4_cycles || !leap_100_cycles);
  1863. yday = remdays + 31 + 28 + leap;
  1864. if (yday >= 365 + leap) {
  1865. yday -= 365 + leap;
  1866. }
  1867. years = remyears + 4 * leap_4_cycles + 100 * leap_100_cycles +
  1868. 400ULL * leap_400_cycles;
  1869. for (months=0; days_in_month[months] <= remdays; months++) {
  1870. remdays -= days_in_month[months];
  1871. }
  1872. if (months >= 10) {
  1873. months -= 12;
  1874. years++;
  1875. }
  1876. dest->tm_year = years + 100;
  1877. dest->tm_mon = months + 2;
  1878. dest->tm_mday = remdays + 1;
  1879. dest->tm_wday = wday;
  1880. dest->tm_yday = yday;
  1881. dest->tm_hour = remsecs / 3600;
  1882. dest->tm_min = remsecs / 60 % 60;
  1883. dest->tm_sec = remsecs % 60;
  1884. #if !defined(__sun)
  1885. dest->tm_gmtoff = 0;
  1886. dest->tm_zone = "GMT";
  1887. #endif
  1888. }
  1889. void
  1890. rspamd_localtime (gint64 ts, struct tm *dest)
  1891. {
  1892. time_t t = ts;
  1893. localtime_r (&t, dest);
  1894. }
  1895. gboolean
  1896. rspamd_fstring_gzip (rspamd_fstring_t **in)
  1897. {
  1898. z_stream strm;
  1899. gint rc;
  1900. rspamd_fstring_t *comp, *buf = *in;
  1901. gchar *p;
  1902. gsize remain;
  1903. memset (&strm, 0, sizeof (strm));
  1904. rc = deflateInit2 (&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED,
  1905. MAX_WBITS + 16, MAX_MEM_LEVEL - 1, Z_DEFAULT_STRATEGY);
  1906. if (rc != Z_OK) {
  1907. return FALSE;
  1908. }
  1909. comp = rspamd_fstring_sized_new (deflateBound (&strm, buf->len));
  1910. strm.avail_in = buf->len;
  1911. strm.next_in = (guchar *)buf->str;
  1912. p = comp->str;
  1913. remain = comp->allocated;
  1914. while (strm.avail_in != 0) {
  1915. strm.avail_out = remain;
  1916. strm.next_out = p;
  1917. rc = deflate (&strm, Z_FINISH);
  1918. if (rc != Z_OK && rc != Z_BUF_ERROR) {
  1919. if (rc == Z_STREAM_END) {
  1920. break;
  1921. }
  1922. else {
  1923. rspamd_fstring_free (comp);
  1924. deflateEnd (&strm);
  1925. return FALSE;
  1926. }
  1927. }
  1928. comp->len = strm.total_out;
  1929. if (strm.avail_out == 0 && strm.avail_in != 0) {
  1930. /* Need to allocate more */
  1931. remain = comp->len;
  1932. comp = rspamd_fstring_grow (comp, strm.avail_in);
  1933. p = comp->str + remain;
  1934. remain = comp->allocated - remain;
  1935. }
  1936. }
  1937. deflateEnd (&strm);
  1938. comp->len = strm.total_out;
  1939. rspamd_fstring_free (buf); /* We replace buf with its compressed version */
  1940. *in = comp;
  1941. return TRUE;
  1942. }
  1943. static gboolean
  1944. rspamd_glob_dir (const gchar *full_path, const gchar *pattern,
  1945. gboolean recursive, guint rec_len,
  1946. GPtrArray *res, GError **err)
  1947. {
  1948. glob_t globbuf;
  1949. const gchar *path;
  1950. static gchar pathbuf[PATH_MAX]; /* Static to help recursion */
  1951. guint i;
  1952. gint rc;
  1953. static const guint rec_lim = 16;
  1954. struct stat st;
  1955. if (rec_len > rec_lim) {
  1956. g_set_error (err, g_quark_from_static_string ("glob"), EOVERFLOW,
  1957. "maximum nesting is reached: %d", rec_lim);
  1958. return FALSE;
  1959. }
  1960. memset (&globbuf, 0, sizeof (globbuf));
  1961. if ((rc = glob (full_path, 0, NULL, &globbuf)) != 0) {
  1962. if (rc != GLOB_NOMATCH) {
  1963. g_set_error (err, g_quark_from_static_string ("glob"), errno,
  1964. "glob %s failed: %s", full_path, strerror (errno));
  1965. globfree (&globbuf);
  1966. return FALSE;
  1967. }
  1968. else {
  1969. globfree (&globbuf);
  1970. return TRUE;
  1971. }
  1972. }
  1973. for (i = 0; i < globbuf.gl_pathc; i ++) {
  1974. path = globbuf.gl_pathv[i];
  1975. if (stat (path, &st) == -1) {
  1976. if (errno == EPERM || errno == EACCES || errno == ELOOP) {
  1977. /* Silently ignore */
  1978. continue;
  1979. }
  1980. g_set_error (err, g_quark_from_static_string ("glob"), errno,
  1981. "stat %s failed: %s", path, strerror (errno));
  1982. globfree (&globbuf);
  1983. return FALSE;
  1984. }
  1985. if (S_ISREG (st.st_mode)) {
  1986. g_ptr_array_add (res, g_strdup (path));
  1987. }
  1988. else if (recursive && S_ISDIR (st.st_mode)) {
  1989. rspamd_snprintf (pathbuf, sizeof (pathbuf), "%s%c%s",
  1990. path, G_DIR_SEPARATOR, pattern);
  1991. if (!rspamd_glob_dir (full_path, pattern, recursive, rec_len + 1,
  1992. res, err)) {
  1993. globfree (&globbuf);
  1994. return FALSE;
  1995. }
  1996. }
  1997. }
  1998. globfree (&globbuf);
  1999. return TRUE;
  2000. }
  2001. GPtrArray *
  2002. rspamd_glob_path (const gchar *dir,
  2003. const gchar *pattern,
  2004. gboolean recursive,
  2005. GError **err)
  2006. {
  2007. gchar path[PATH_MAX];
  2008. GPtrArray *res;
  2009. res = g_ptr_array_new_full (32, (GDestroyNotify)g_free);
  2010. rspamd_snprintf (path, sizeof (path), "%s%c%s", dir, G_DIR_SEPARATOR, pattern);
  2011. if (!rspamd_glob_dir (path, pattern, recursive, 0, res, err)) {
  2012. g_ptr_array_free (res, TRUE);
  2013. return NULL;
  2014. }
  2015. return res;
  2016. }
  2017. double
  2018. rspamd_set_counter (struct rspamd_counter_data *cd, gdouble value)
  2019. {
  2020. gdouble cerr;
  2021. /* Cumulative moving average using per-process counter data */
  2022. if (cd->number == 0) {
  2023. cd->mean = 0;
  2024. cd->stddev = 0;
  2025. }
  2026. cd->mean += (value - cd->mean) / (gdouble)(++cd->number);
  2027. cerr = (value - cd->mean) * (value - cd->mean);
  2028. cd->stddev += (cerr - cd->stddev) / (gdouble)(cd->number);
  2029. return cd->mean;
  2030. }
  2031. double
  2032. rspamd_set_counter_ema (struct rspamd_counter_data *cd,
  2033. gdouble value,
  2034. gdouble alpha)
  2035. {
  2036. gdouble diff, incr;
  2037. /* Cumulative moving average using per-process counter data */
  2038. if (cd->number == 0) {
  2039. cd->mean = 0;
  2040. cd->stddev = 0;
  2041. }
  2042. diff = value - cd->mean;
  2043. incr = diff * alpha;
  2044. cd->mean += incr;
  2045. cd->stddev = (1 - alpha) * (cd->stddev + diff * incr);
  2046. cd->number ++;
  2047. return cd->mean;
  2048. }
  2049. void
  2050. rspamd_ptr_array_shuffle (GPtrArray *ar)
  2051. {
  2052. if (ar->len < 2) {
  2053. return;
  2054. }
  2055. guint n = ar->len;
  2056. for (guint i = 0; i < n - 1; i++) {
  2057. guint j = i + rspamd_random_uint64_fast () % (n - i);
  2058. gpointer t = g_ptr_array_index (ar, j);
  2059. g_ptr_array_index (ar, j) = g_ptr_array_index (ar, i);
  2060. g_ptr_array_index (ar, i) = t;
  2061. }
  2062. }