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 46KB

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