sync.c 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242
  1. /*
  2. * mbsync - mailbox synchronizer
  3. * Copyright (C) 2000-2002 Michael R. Elkins <me@mutt.org>
  4. * Copyright (C) 2002-2006,2010-2013 Oswald Buddenhagen <ossi@users.sf.net>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. * As a special exception, mbsync may be linked with the OpenSSL library,
  20. * despite that library's more restrictive license.
  21. */
  22. #include "sync.h"
  23. #include <assert.h>
  24. #include <stdio.h>
  25. #include <limits.h>
  26. #include <stdlib.h>
  27. #include <stddef.h>
  28. #include <unistd.h>
  29. #include <time.h>
  30. #include <fcntl.h>
  31. #include <ctype.h>
  32. #include <string.h>
  33. #include <errno.h>
  34. #include <sys/stat.h>
  35. #if !defined(_POSIX_SYNCHRONIZED_IO) || _POSIX_SYNCHRONIZED_IO <= 0
  36. # define fdatasync fsync
  37. #endif
  38. channel_conf_t global_conf;
  39. channel_conf_t *channels;
  40. group_conf_t *groups;
  41. const char *str_ms[] = { "master", "slave" }, *str_hl[] = { "push", "pull" };
  42. static void ATTR_PRINTFLIKE(1, 2)
  43. debug( const char *msg, ... )
  44. {
  45. va_list va;
  46. va_start( va, msg );
  47. vdebug( DEBUG_SYNC, msg, va );
  48. va_end( va );
  49. }
  50. static void ATTR_PRINTFLIKE(1, 2)
  51. debugn( const char *msg, ... )
  52. {
  53. va_list va;
  54. va_start( va, msg );
  55. vdebugn( DEBUG_SYNC, msg, va );
  56. va_end( va );
  57. }
  58. void
  59. Fclose( FILE *f, int safe )
  60. {
  61. if ((safe && (fflush( f ) || (UseFSync && fdatasync( fileno( f ) )))) || fclose( f ) == EOF) {
  62. sys_error( "Error: cannot close file" );
  63. exit( 1 );
  64. }
  65. }
  66. void
  67. vFprintf( FILE *f, const char *msg, va_list va )
  68. {
  69. int r;
  70. r = vfprintf( f, msg, va );
  71. if (r < 0) {
  72. sys_error( "Error: cannot write file" );
  73. exit( 1 );
  74. }
  75. }
  76. void
  77. Fprintf( FILE *f, const char *msg, ... )
  78. {
  79. va_list va;
  80. va_start( va, msg );
  81. vFprintf( f, msg, va );
  82. va_end( va );
  83. }
  84. static const char Flags[] = { 'D', 'F', 'R', 'S', 'T' };
  85. static int
  86. parse_flags( const char *buf )
  87. {
  88. uint flags, i, d;
  89. for (flags = i = d = 0; i < as(Flags); i++)
  90. if (buf[d] == Flags[i]) {
  91. flags |= (1 << i);
  92. d++;
  93. }
  94. return flags;
  95. }
  96. static int
  97. make_flags( int flags, char *buf )
  98. {
  99. uint i, d;
  100. for (i = d = 0; i < as(Flags); i++)
  101. if (flags & (1 << i))
  102. buf[d++] = Flags[i];
  103. buf[d] = 0;
  104. return d;
  105. }
  106. // These is the (mostly) persistent status of the sync record.
  107. // Most of these bits are actually mutually exclusive. It is a
  108. // bitfield to allow for easy testing for multiple states.
  109. #define S_EXPIRE (1<<0) // the entry is being expired (slave message removal scheduled)
  110. #define S_EXPIRED (1<<1) // the entry is expired (slave message removal confirmed)
  111. #define S_PENDING (1<<2) // the entry is new and awaits propagation (possibly a retry)
  112. #define S_SKIPPED (1<<3) // the entry was not propagated (message is too big)
  113. #define S_DEAD (1<<7) // ephemeral: the entry was killed and should be ignored
  114. // Ephemeral working set.
  115. #define W_NEXPIRE (1<<0) // temporary: new expiration state
  116. #define W_DELETE (1<<1) // ephemeral: flags propagation is a deletion
  117. #define W_DEL(ms) (1<<(2+(ms))) // ephemeral: m/s message would be subject to expunge
  118. typedef struct sync_rec {
  119. struct sync_rec *next;
  120. /* string_list_t *keywords; */
  121. uint uid[2];
  122. message_t *msg[2];
  123. uchar status, wstate, flags, aflags[2], dflags[2];
  124. char tuid[TUIDL];
  125. } sync_rec_t;
  126. typedef struct {
  127. int t[2];
  128. void (*cb)( int sts, void *aux ), *aux;
  129. char *dname, *jname, *nname, *lname, *box_name[2];
  130. FILE *jfp, *nfp;
  131. sync_rec_t *srecs, **srecadd;
  132. channel_conf_t *chan;
  133. store_t *ctx[2];
  134. driver_t *drv[2];
  135. const char *orig_name[2];
  136. message_t *msgs[2], *new_msgs[2];
  137. uint_array_alloc_t trashed_msgs[2];
  138. int state[2], opts[2], ref_count, nsrecs, ret, lfd, existing, replayed;
  139. int new_pending[2], flags_pending[2], trash_pending[2];
  140. uint maxuid[2]; // highest UID that was already propagated
  141. uint newmaxuid[2]; // highest UID that is currently being propagated
  142. uint uidval[2]; // UID validity value
  143. uint newuidval[2]; // UID validity obtained from driver
  144. uint newuid[2]; // TUID lookup makes sense only for UIDs >= this
  145. uint mmaxxuid; // highest expired UID on master
  146. } sync_vars_t;
  147. static void sync_ref( sync_vars_t *svars ) { ++svars->ref_count; }
  148. static void sync_deref( sync_vars_t *svars );
  149. static int check_cancel( sync_vars_t *svars );
  150. #define AUX &svars->t[t]
  151. #define INV_AUX &svars->t[1-t]
  152. #define DECL_SVARS \
  153. int t; \
  154. sync_vars_t *svars
  155. #define INIT_SVARS(aux) \
  156. t = *(int *)aux; \
  157. svars = (sync_vars_t *)(((char *)(&((int *)aux)[-t])) - offsetof(sync_vars_t, t))
  158. #define DECL_INIT_SVARS(aux) \
  159. int t = *(int *)aux; \
  160. sync_vars_t *svars = (sync_vars_t *)(((char *)(&((int *)aux)[-t])) - offsetof(sync_vars_t, t))
  161. /* operation dependencies:
  162. select(x): -
  163. load(x): select(x)
  164. new(M), new(S), flags(M), flags(S): load(M) & load(S)
  165. find_new(x): new(x)
  166. trash(x): flags(x)
  167. close(x): trash(x) & find_new(x) & new(!x) // with expunge
  168. cleanup: close(M) & close(S)
  169. */
  170. #define ST_LOADED (1<<0)
  171. #define ST_FIND_OLD (1<<1)
  172. #define ST_SENT_NEW (1<<2)
  173. #define ST_FIND_NEW (1<<3)
  174. #define ST_FOUND_NEW (1<<4)
  175. #define ST_SENT_FLAGS (1<<5)
  176. #define ST_SENT_TRASH (1<<6)
  177. #define ST_CLOSED (1<<7)
  178. #define ST_SENT_CANCEL (1<<8)
  179. #define ST_CANCELED (1<<9)
  180. #define ST_SELECTED (1<<10)
  181. #define ST_DID_EXPUNGE (1<<11)
  182. #define ST_CLOSING (1<<12)
  183. #define ST_CONFIRMED (1<<13)
  184. #define ST_PRESENT (1<<14)
  185. #define ST_SENDING_NEW (1<<15)
  186. void
  187. jFprintf( sync_vars_t *svars, const char *msg, ... )
  188. {
  189. va_list va;
  190. if (JLimit && !--JLimit)
  191. exit( 101 );
  192. va_start( va, msg );
  193. vFprintf( svars->jfp, msg, va );
  194. va_end( va );
  195. if (JLimit && !--JLimit)
  196. exit( 100 );
  197. }
  198. static void
  199. match_tuids( sync_vars_t *svars, int t, message_t *msgs )
  200. {
  201. sync_rec_t *srec;
  202. message_t *tmsg, *ntmsg = 0;
  203. const char *diag;
  204. int num_lost = 0;
  205. for (srec = svars->srecs; srec; srec = srec->next) {
  206. if (srec->status & S_DEAD)
  207. continue;
  208. if (!srec->uid[t] && srec->tuid[0]) {
  209. debug( " pair(%u,%u): lookup %s, TUID %." stringify(TUIDL) "s\n", srec->uid[M], srec->uid[S], str_ms[t], srec->tuid );
  210. for (tmsg = ntmsg; tmsg; tmsg = tmsg->next) {
  211. if (tmsg->status & M_DEAD)
  212. continue;
  213. if (tmsg->tuid[0] && !memcmp( tmsg->tuid, srec->tuid, TUIDL )) {
  214. diag = (tmsg == ntmsg) ? "adjacently" : "after gap";
  215. goto mfound;
  216. }
  217. }
  218. for (tmsg = msgs; tmsg != ntmsg; tmsg = tmsg->next) {
  219. if (tmsg->status & M_DEAD)
  220. continue;
  221. if (tmsg->tuid[0] && !memcmp( tmsg->tuid, srec->tuid, TUIDL )) {
  222. diag = "after reset";
  223. goto mfound;
  224. }
  225. }
  226. debug( " -> TUID lost\n" );
  227. jFprintf( svars, "& %u %u\n", srec->uid[M], srec->uid[S] );
  228. srec->flags = 0;
  229. // Note: status remains S_PENDING.
  230. srec->tuid[0] = 0;
  231. num_lost++;
  232. continue;
  233. mfound:
  234. debug( " -> new UID %u %s\n", tmsg->uid, diag );
  235. jFprintf( svars, "%c %u %u %u\n", "<>"[t], srec->uid[M], srec->uid[S], tmsg->uid );
  236. tmsg->srec = srec;
  237. srec->msg[t] = tmsg;
  238. ntmsg = tmsg->next;
  239. srec->uid[t] = tmsg->uid;
  240. srec->status = 0;
  241. srec->tuid[0] = 0;
  242. }
  243. }
  244. if (num_lost)
  245. warn( "Warning: lost track of %d %sed message(s)\n", num_lost, str_hl[t] );
  246. }
  247. typedef struct copy_vars {
  248. void (*cb)( int sts, uint uid, struct copy_vars *vars );
  249. void *aux;
  250. sync_rec_t *srec; /* also ->tuid */
  251. message_t *msg;
  252. msg_data_t data;
  253. } copy_vars_t;
  254. static void msg_fetched( int sts, void *aux );
  255. static void
  256. copy_msg( copy_vars_t *vars )
  257. {
  258. DECL_INIT_SVARS(vars->aux);
  259. t ^= 1;
  260. vars->data.flags = vars->msg->flags;
  261. vars->data.date = svars->chan->use_internal_date ? -1 : 0;
  262. svars->drv[t]->fetch_msg( svars->ctx[t], vars->msg, &vars->data, msg_fetched, vars );
  263. }
  264. static void msg_stored( int sts, uint uid, void *aux );
  265. static void
  266. copy_msg_bytes( char **out_ptr, const char *in_buf, int *in_idx, int in_len, int in_cr, int out_cr )
  267. {
  268. char *out = *out_ptr;
  269. int idx = *in_idx;
  270. if (out_cr != in_cr) {
  271. char c;
  272. if (out_cr) {
  273. for (; idx < in_len; idx++) {
  274. if ((c = in_buf[idx]) != '\r') {
  275. if (c == '\n')
  276. *out++ = '\r';
  277. *out++ = c;
  278. }
  279. }
  280. } else {
  281. for (; idx < in_len; idx++) {
  282. if ((c = in_buf[idx]) != '\r')
  283. *out++ = c;
  284. }
  285. }
  286. } else {
  287. memcpy( out, in_buf + idx, in_len - idx );
  288. out += in_len - idx;
  289. idx = in_len;
  290. }
  291. *out_ptr = out;
  292. *in_idx = idx;
  293. }
  294. static int
  295. copy_msg_convert( int in_cr, int out_cr, copy_vars_t *vars )
  296. {
  297. char *in_buf = vars->data.data;
  298. int in_len = vars->data.len;
  299. int idx = 0, sbreak = 0, ebreak = 0;
  300. int lines = 0, hdr_crs = 0, bdy_crs = 0, app_cr = 0, extra = 0;
  301. if (vars->srec) {
  302. nloop: ;
  303. int start = idx;
  304. int line_crs = 0;
  305. while (idx < in_len) {
  306. char c = in_buf[idx++];
  307. if (c == '\r') {
  308. line_crs++;
  309. } else if (c == '\n') {
  310. if (starts_with_upper( in_buf + start, in_len - start, "X-TUID: ", 8 )) {
  311. extra = (sbreak = start) - (ebreak = idx);
  312. goto oke;
  313. }
  314. lines++;
  315. hdr_crs += line_crs;
  316. if (idx - line_crs - 1 == start) {
  317. sbreak = ebreak = start;
  318. goto oke;
  319. }
  320. goto nloop;
  321. }
  322. }
  323. /* invalid message */
  324. free( in_buf );
  325. return 0;
  326. oke:
  327. app_cr = out_cr && (!in_cr || hdr_crs);
  328. extra += 8 + TUIDL + app_cr + 1;
  329. }
  330. if (out_cr != in_cr) {
  331. for (; idx < in_len; idx++) {
  332. char c = in_buf[idx];
  333. if (c == '\r')
  334. bdy_crs++;
  335. else if (c == '\n')
  336. lines++;
  337. }
  338. extra -= hdr_crs + bdy_crs;
  339. if (out_cr)
  340. extra += lines;
  341. }
  342. vars->data.len = in_len + extra;
  343. char *out_buf = vars->data.data = nfmalloc( vars->data.len );
  344. idx = 0;
  345. if (vars->srec) {
  346. copy_msg_bytes( &out_buf, in_buf, &idx, sbreak, in_cr, out_cr );
  347. memcpy( out_buf, "X-TUID: ", 8 );
  348. out_buf += 8;
  349. memcpy( out_buf, vars->srec->tuid, TUIDL );
  350. out_buf += TUIDL;
  351. if (app_cr)
  352. *out_buf++ = '\r';
  353. *out_buf++ = '\n';
  354. idx = ebreak;
  355. }
  356. copy_msg_bytes( &out_buf, in_buf, &idx, in_len, in_cr, out_cr );
  357. free( in_buf );
  358. return 1;
  359. }
  360. static void
  361. msg_fetched( int sts, void *aux )
  362. {
  363. copy_vars_t *vars = (copy_vars_t *)aux;
  364. DECL_SVARS;
  365. int scr, tcr;
  366. switch (sts) {
  367. case DRV_OK:
  368. INIT_SVARS(vars->aux);
  369. if (check_cancel( svars )) {
  370. free( vars->data.data );
  371. vars->cb( SYNC_CANCELED, 0, vars );
  372. return;
  373. }
  374. vars->msg->flags = vars->data.flags;
  375. scr = (svars->drv[1-t]->get_caps( svars->ctx[1-t] ) / DRV_CRLF) & 1;
  376. tcr = (svars->drv[t]->get_caps( svars->ctx[t] ) / DRV_CRLF) & 1;
  377. if (vars->srec || scr != tcr) {
  378. if (!copy_msg_convert( scr, tcr, vars )) {
  379. warn( "Warning: message %u from %s has incomplete header.\n",
  380. vars->msg->uid, str_ms[1-t] );
  381. vars->cb( SYNC_NOGOOD, 0, vars );
  382. return;
  383. }
  384. }
  385. svars->drv[t]->store_msg( svars->ctx[t], &vars->data, !vars->srec, msg_stored, vars );
  386. break;
  387. case DRV_CANCELED:
  388. vars->cb( SYNC_CANCELED, 0, vars );
  389. break;
  390. case DRV_MSG_BAD:
  391. vars->cb( SYNC_NOGOOD, 0, vars );
  392. break;
  393. default:
  394. vars->cb( SYNC_FAIL, 0, vars );
  395. break;
  396. }
  397. }
  398. static void
  399. msg_stored( int sts, uint uid, void *aux )
  400. {
  401. copy_vars_t *vars = (copy_vars_t *)aux;
  402. DECL_SVARS;
  403. switch (sts) {
  404. case DRV_OK:
  405. vars->cb( SYNC_OK, uid, vars );
  406. break;
  407. case DRV_CANCELED:
  408. vars->cb( SYNC_CANCELED, 0, vars );
  409. break;
  410. case DRV_MSG_BAD:
  411. INIT_SVARS(vars->aux);
  412. (void)svars;
  413. warn( "Warning: %s refuses to store message %u from %s.\n",
  414. str_ms[t], vars->msg->uid, str_ms[1-t] );
  415. vars->cb( SYNC_NOGOOD, 0, vars );
  416. break;
  417. default:
  418. vars->cb( SYNC_FAIL, 0, vars );
  419. break;
  420. }
  421. }
  422. static void sync_bail( sync_vars_t *svars );
  423. static void sync_bail2( sync_vars_t *svars );
  424. static void sync_bail3( sync_vars_t *svars );
  425. static void cancel_done( void *aux );
  426. static void
  427. cancel_sync( sync_vars_t *svars )
  428. {
  429. int t;
  430. for (t = 0; t < 2; t++) {
  431. int other_state = svars->state[1-t];
  432. if (svars->ret & SYNC_BAD(t)) {
  433. cancel_done( AUX );
  434. } else if (!(svars->state[t] & ST_SENT_CANCEL)) {
  435. /* ignore subsequent failures from in-flight commands */
  436. svars->state[t] |= ST_SENT_CANCEL;
  437. svars->drv[t]->cancel_cmds( svars->ctx[t], cancel_done, AUX );
  438. }
  439. if (other_state & ST_CANCELED)
  440. break;
  441. }
  442. }
  443. static void
  444. cancel_done( void *aux )
  445. {
  446. DECL_INIT_SVARS(aux);
  447. svars->state[t] |= ST_CANCELED;
  448. if (svars->state[1-t] & ST_CANCELED) {
  449. if (svars->nfp) {
  450. Fclose( svars->nfp, 0 );
  451. Fclose( svars->jfp, 0 );
  452. }
  453. sync_bail( svars );
  454. }
  455. }
  456. static void
  457. store_bad( void *aux )
  458. {
  459. DECL_INIT_SVARS(aux);
  460. svars->drv[t]->cancel_store( svars->ctx[t] );
  461. svars->ret |= SYNC_BAD(t);
  462. cancel_sync( svars );
  463. }
  464. static int
  465. check_cancel( sync_vars_t *svars )
  466. {
  467. return (svars->state[M] | svars->state[S]) & (ST_SENT_CANCEL | ST_CANCELED);
  468. }
  469. static int
  470. check_ret( int sts, void *aux )
  471. {
  472. DECL_SVARS;
  473. if (sts == DRV_CANCELED)
  474. return 1;
  475. INIT_SVARS(aux);
  476. if (sts == DRV_BOX_BAD) {
  477. svars->ret |= SYNC_FAIL;
  478. cancel_sync( svars );
  479. return 1;
  480. }
  481. return check_cancel( svars );
  482. }
  483. #define SVARS_CHECK_RET \
  484. DECL_SVARS; \
  485. if (check_ret( sts, aux )) \
  486. return; \
  487. INIT_SVARS(aux)
  488. #define SVARS_CHECK_RET_VARS(type) \
  489. type *vars = (type *)aux; \
  490. DECL_SVARS; \
  491. if (check_ret( sts, vars->aux )) { \
  492. free( vars ); \
  493. return; \
  494. } \
  495. INIT_SVARS(vars->aux)
  496. #define SVARS_CHECK_CANCEL_RET \
  497. DECL_SVARS; \
  498. if (sts == SYNC_CANCELED) { \
  499. free( vars ); \
  500. return; \
  501. } \
  502. INIT_SVARS(vars->aux)
  503. static char *
  504. clean_strdup( const char *s )
  505. {
  506. char *cs;
  507. int i;
  508. cs = nfstrdup( s );
  509. for (i = 0; cs[i]; i++)
  510. if (cs[i] == '/')
  511. cs[i] = '!';
  512. return cs;
  513. }
  514. #define JOURNAL_VERSION "3"
  515. static int
  516. prepare_state( sync_vars_t *svars )
  517. {
  518. char *s, *cmname, *csname;
  519. channel_conf_t *chan;
  520. chan = svars->chan;
  521. if (!strcmp( chan->sync_state ? chan->sync_state : global_conf.sync_state, "*" )) {
  522. const char *path = svars->drv[S]->get_box_path( svars->ctx[S] );
  523. if (!path) {
  524. error( "Error: store '%s' does not support in-box sync state\n", chan->stores[S]->name );
  525. return 0;
  526. }
  527. nfasprintf( &svars->dname, "%s/." EXE "state", path );
  528. } else {
  529. csname = clean_strdup( svars->box_name[S] );
  530. if (chan->sync_state)
  531. nfasprintf( &svars->dname, "%s%s", chan->sync_state, csname );
  532. else {
  533. char c = FieldDelimiter;
  534. cmname = clean_strdup( svars->box_name[M] );
  535. nfasprintf( &svars->dname, "%s%c%s%c%s_%c%s%c%s", global_conf.sync_state,
  536. c, chan->stores[M]->name, c, cmname, c, chan->stores[S]->name, c, csname );
  537. free( cmname );
  538. }
  539. free( csname );
  540. if (!(s = strrchr( svars->dname, '/' ))) {
  541. error( "Error: invalid SyncState location '%s'\n", svars->dname );
  542. return 0;
  543. }
  544. *s = 0;
  545. if (mkdir( svars->dname, 0700 ) && errno != EEXIST) {
  546. sys_error( "Error: cannot create SyncState directory '%s'", svars->dname );
  547. return 0;
  548. }
  549. *s = '/';
  550. }
  551. nfasprintf( &svars->jname, "%s.journal", svars->dname );
  552. nfasprintf( &svars->nname, "%s.new", svars->dname );
  553. nfasprintf( &svars->lname, "%s.lock", svars->dname );
  554. return 1;
  555. }
  556. static int
  557. lock_state( sync_vars_t *svars )
  558. {
  559. struct flock lck;
  560. if (svars->lfd >= 0)
  561. return 1;
  562. memset( &lck, 0, sizeof(lck) );
  563. #if SEEK_SET != 0
  564. lck.l_whence = SEEK_SET;
  565. #endif
  566. #if F_WRLCK != 0
  567. lck.l_type = F_WRLCK;
  568. #endif
  569. if ((svars->lfd = open( svars->lname, O_WRONLY|O_CREAT, 0666 )) < 0) {
  570. sys_error( "Error: cannot create lock file %s", svars->lname );
  571. return 0;
  572. }
  573. if (fcntl( svars->lfd, F_SETLK, &lck )) {
  574. error( "Error: channel :%s:%s-:%s:%s is locked\n",
  575. svars->chan->stores[M]->name, svars->orig_name[M], svars->chan->stores[S]->name, svars->orig_name[S] );
  576. close( svars->lfd );
  577. svars->lfd = -1;
  578. return 0;
  579. }
  580. return 1;
  581. }
  582. static void
  583. save_state( sync_vars_t *svars )
  584. {
  585. sync_rec_t *srec;
  586. char fbuf[16]; /* enlarge when support for keywords is added */
  587. Fprintf( svars->nfp,
  588. "MasterUidValidity %u\nSlaveUidValidity %u\nMaxPulledUid %u\nMaxPushedUid %u\n",
  589. svars->uidval[M], svars->uidval[S], svars->maxuid[M], svars->maxuid[S] );
  590. if (svars->mmaxxuid)
  591. Fprintf( svars->nfp, "MaxExpiredMasterUid %u\n", svars->mmaxxuid );
  592. Fprintf( svars->nfp, "\n" );
  593. for (srec = svars->srecs; srec; srec = srec->next) {
  594. if (srec->status & S_DEAD)
  595. continue;
  596. make_flags( srec->flags, fbuf );
  597. Fprintf( svars->nfp, "%u %u %s%s\n", srec->uid[M], srec->uid[S],
  598. (srec->status & S_SKIPPED) ? "^" : (srec->status & S_PENDING) ? "!" : (srec->status & S_EXPIRED) ? "~" : "", fbuf );
  599. }
  600. Fclose( svars->nfp, 1 );
  601. Fclose( svars->jfp, 0 );
  602. if (!(DFlags & KEEPJOURNAL)) {
  603. /* order is important! */
  604. if (rename( svars->nname, svars->dname ))
  605. warn( "Warning: cannot commit sync state %s\n", svars->dname );
  606. else if (unlink( svars->jname ))
  607. warn( "Warning: cannot delete journal %s\n", svars->jname );
  608. }
  609. }
  610. static int
  611. load_state( sync_vars_t *svars )
  612. {
  613. sync_rec_t *srec, *nsrec;
  614. char *s;
  615. FILE *jfp;
  616. int ll;
  617. uint smaxxuid = 0;
  618. char c;
  619. struct stat st;
  620. char fbuf[16]; /* enlarge when support for keywords is added */
  621. char buf[128], buf1[64], buf2[64];
  622. if ((jfp = fopen( svars->dname, "r" ))) {
  623. if (!lock_state( svars ))
  624. goto jbail;
  625. debug( "reading sync state %s ...\n", svars->dname );
  626. int line = 0;
  627. while (fgets( buf, sizeof(buf), jfp )) {
  628. line++;
  629. if (!(ll = strlen( buf )) || buf[ll - 1] != '\n') {
  630. error( "Error: incomplete sync state header entry at %s:%d\n", svars->dname, line );
  631. jbail:
  632. fclose( jfp );
  633. return 0;
  634. }
  635. if (ll == 1)
  636. goto gothdr;
  637. if (line == 1 && isdigit( buf[0] )) {
  638. if (sscanf( buf, "%63s %63s", buf1, buf2 ) != 2 ||
  639. sscanf( buf1, "%u:%u", &svars->uidval[M], &svars->maxuid[M] ) < 2 ||
  640. sscanf( buf2, "%u:%u:%u", &svars->uidval[S], &smaxxuid, &svars->maxuid[S] ) < 3) {
  641. error( "Error: invalid sync state header in %s\n", svars->dname );
  642. goto jbail;
  643. }
  644. goto gothdr;
  645. }
  646. uint uid;
  647. if (sscanf( buf, "%63s %u", buf1, &uid ) != 2) {
  648. error( "Error: malformed sync state header entry at %s:%d\n", svars->dname, line );
  649. goto jbail;
  650. }
  651. if (!strcmp( buf1, "MasterUidValidity" ))
  652. svars->uidval[M] = uid;
  653. else if (!strcmp( buf1, "SlaveUidValidity" ))
  654. svars->uidval[S] = uid;
  655. else if (!strcmp( buf1, "MaxPulledUid" ))
  656. svars->maxuid[M] = uid;
  657. else if (!strcmp( buf1, "MaxPushedUid" ))
  658. svars->maxuid[S] = uid;
  659. else if (!strcmp( buf1, "MaxExpiredMasterUid" ))
  660. svars->mmaxxuid = uid;
  661. else if (!strcmp( buf1, "MaxExpiredSlaveUid" )) // Legacy
  662. smaxxuid = uid;
  663. else {
  664. error( "Error: unrecognized sync state header entry at %s:%d\n", svars->dname, line );
  665. goto jbail;
  666. }
  667. }
  668. error( "Error: unterminated sync state header in %s\n", svars->dname );
  669. goto jbail;
  670. gothdr:
  671. while (fgets( buf, sizeof(buf), jfp )) {
  672. line++;
  673. if (!(ll = strlen( buf )) || buf[--ll] != '\n') {
  674. error( "Error: incomplete sync state entry at %s:%d\n", svars->dname, line );
  675. goto jbail;
  676. }
  677. buf[ll] = 0;
  678. fbuf[0] = 0;
  679. uint t1, t2;
  680. if (sscanf( buf, "%u %u %15s", &t1, &t2, fbuf ) < 2) {
  681. error( "Error: invalid sync state entry at %s:%d\n", svars->dname, line );
  682. goto jbail;
  683. }
  684. srec = nfmalloc( sizeof(*srec) );
  685. srec->uid[M] = t1;
  686. srec->uid[S] = t2;
  687. s = fbuf;
  688. if (*s == '^') {
  689. s++;
  690. srec->status = S_SKIPPED;
  691. } else if (*s == '!') {
  692. s++;
  693. srec->status = S_PENDING;
  694. } else if (*s == '~' || *s == 'X' /* Pre-1.3 legacy */) {
  695. s++;
  696. srec->status = S_EXPIRE | S_EXPIRED;
  697. } else if (srec->uid[M] == (uint)-1) { // Pre-1.3 legacy
  698. srec->uid[M] = 0;
  699. srec->status = S_SKIPPED;
  700. } else if (srec->uid[M] == (uint)-2) {
  701. srec->uid[M] = 0;
  702. srec->status = S_PENDING;
  703. } else if (srec->uid[S] == (uint)-1) {
  704. srec->uid[S] = 0;
  705. srec->status = S_SKIPPED;
  706. } else if (srec->uid[S] == (uint)-2) {
  707. srec->uid[S] = 0;
  708. srec->status = S_PENDING;
  709. } else
  710. srec->status = 0;
  711. srec->wstate = 0;
  712. srec->flags = parse_flags( s );
  713. debug( " entry (%u,%u,%u,%s)\n", srec->uid[M], srec->uid[S], srec->flags,
  714. (srec->status & S_SKIPPED) ? "SKIP" : (srec->status & S_PENDING) ? "FAIL" : (srec->status & S_EXPIRED) ? "XPIRE" : "" );
  715. srec->msg[M] = srec->msg[S] = 0;
  716. srec->tuid[0] = 0;
  717. srec->next = 0;
  718. *svars->srecadd = srec;
  719. svars->srecadd = &srec->next;
  720. svars->nsrecs++;
  721. }
  722. fclose( jfp );
  723. svars->existing = 1;
  724. } else {
  725. if (errno != ENOENT) {
  726. sys_error( "Error: cannot read sync state %s", svars->dname );
  727. return 0;
  728. }
  729. svars->existing = 0;
  730. }
  731. // This is legacy support for pre-1.3 sync states.
  732. if (smaxxuid) {
  733. uint minwuid = UINT_MAX;
  734. for (srec = svars->srecs; srec; srec = srec->next) {
  735. if ((srec->status & (S_DEAD | S_SKIPPED | S_PENDING)) || !srec->uid[M])
  736. continue;
  737. if (srec->status & S_EXPIRED) {
  738. if (!srec->uid[S]) {
  739. // The expired message was already gone.
  740. continue;
  741. }
  742. // The expired message was not expunged yet, so re-examine it.
  743. // This will happen en masse, so just extend the bulk fetch.
  744. } else {
  745. if (srec->uid[S] && smaxxuid >= srec->uid[S]) {
  746. // The non-expired message is in the generally expired range,
  747. // so don't make it contribute to the bulk fetch.
  748. continue;
  749. }
  750. // Usual non-expired message.
  751. }
  752. if (minwuid > srec->uid[M])
  753. minwuid = srec->uid[M];
  754. }
  755. svars->mmaxxuid = minwuid - 1;
  756. }
  757. svars->newmaxuid[M] = svars->maxuid[M];
  758. svars->newmaxuid[S] = svars->maxuid[S];
  759. int line = 0;
  760. if ((jfp = fopen( svars->jname, "r" ))) {
  761. if (!lock_state( svars ))
  762. goto jbail;
  763. if (!stat( svars->nname, &st ) && fgets( buf, sizeof(buf), jfp )) {
  764. debug( "recovering journal ...\n" );
  765. if (!(ll = strlen( buf )) || buf[--ll] != '\n') {
  766. error( "Error: incomplete journal header in %s\n", svars->jname );
  767. goto jbail;
  768. }
  769. buf[ll] = 0;
  770. if (!equals( buf, ll, JOURNAL_VERSION, strlen(JOURNAL_VERSION) )) {
  771. error( "Error: incompatible journal version "
  772. "(got %s, expected " JOURNAL_VERSION ")\n", buf );
  773. goto jbail;
  774. }
  775. srec = 0;
  776. line = 1;
  777. while (fgets( buf, sizeof(buf), jfp )) {
  778. line++;
  779. if (!(ll = strlen( buf )) || buf[--ll] != '\n') {
  780. error( "Error: incomplete journal entry at %s:%d\n", svars->jname, line );
  781. goto jbail;
  782. }
  783. buf[ll] = 0;
  784. int tn;
  785. uint t1, t2, t3;
  786. if ((c = buf[0]) == '#' ?
  787. (tn = 0, (sscanf( buf + 2, "%u %u %n", &t1, &t2, &tn ) < 2) || !tn || (ll - tn != TUIDL + 2)) :
  788. c == 'S' || c == '!' ?
  789. (sscanf( buf + 2, "%u", &t1 ) != 1) :
  790. c == 'F' || c == 'T' || c == '+' || c == '&' || c == '-' || c == '=' || c == '|' ?
  791. (sscanf( buf + 2, "%u %u", &t1, &t2 ) != 2) :
  792. (sscanf( buf + 2, "%u %u %u", &t1, &t2, &t3 ) != 3))
  793. {
  794. error( "Error: malformed journal entry at %s:%d\n", svars->jname, line );
  795. goto jbail;
  796. }
  797. if (c == 'S')
  798. svars->maxuid[t1] = svars->newmaxuid[t1];
  799. else if (c == 'F')
  800. svars->newuid[t1] = t2;
  801. else if (c == 'T')
  802. *uint_array_append( &svars->trashed_msgs[t1] ) = t2;
  803. else if (c == '!')
  804. svars->mmaxxuid = t1;
  805. else if (c == '|') {
  806. svars->uidval[M] = t1;
  807. svars->uidval[S] = t2;
  808. } else if (c == '+') {
  809. srec = nfmalloc( sizeof(*srec) );
  810. srec->uid[M] = t1;
  811. srec->uid[S] = t2;
  812. if (svars->newmaxuid[M] < t1)
  813. svars->newmaxuid[M] = t1;
  814. if (svars->newmaxuid[S] < t2)
  815. svars->newmaxuid[S] = t2;
  816. debug( " new entry(%u,%u)\n", t1, t2 );
  817. srec->msg[M] = srec->msg[S] = 0;
  818. srec->status = S_PENDING;
  819. srec->wstate = 0;
  820. srec->flags = 0;
  821. srec->tuid[0] = 0;
  822. srec->next = 0;
  823. *svars->srecadd = srec;
  824. svars->srecadd = &srec->next;
  825. svars->nsrecs++;
  826. } else {
  827. for (nsrec = srec; srec; srec = srec->next)
  828. if (srec->uid[M] == t1 && srec->uid[S] == t2)
  829. goto syncfnd;
  830. for (srec = svars->srecs; srec != nsrec; srec = srec->next)
  831. if (srec->uid[M] == t1 && srec->uid[S] == t2)
  832. goto syncfnd;
  833. error( "Error: journal entry at %s:%d refers to non-existing sync state entry\n", svars->jname, line );
  834. goto jbail;
  835. syncfnd:
  836. debugn( " entry(%u,%u,%u) ", srec->uid[M], srec->uid[S], srec->flags );
  837. switch (c) {
  838. case '-':
  839. debug( "killed\n" );
  840. srec->status = S_DEAD;
  841. break;
  842. case '=':
  843. debug( "aborted\n" );
  844. svars->mmaxxuid = srec->uid[M];
  845. srec->status = S_DEAD;
  846. break;
  847. case '#':
  848. memcpy( srec->tuid, buf + tn + 2, TUIDL );
  849. debug( "TUID now %." stringify(TUIDL) "s\n", srec->tuid );
  850. break;
  851. case '&':
  852. debug( "TUID %." stringify(TUIDL) "s lost\n", srec->tuid );
  853. srec->flags = 0;
  854. srec->tuid[0] = 0;
  855. break;
  856. case '<':
  857. debug( "master now %u\n", t3 );
  858. srec->uid[M] = t3;
  859. srec->status &= ~S_PENDING;
  860. srec->tuid[0] = 0;
  861. break;
  862. case '>':
  863. debug( "slave now %u\n", t3 );
  864. srec->uid[S] = t3;
  865. srec->status &= ~S_PENDING;
  866. srec->tuid[0] = 0;
  867. break;
  868. case '*':
  869. debug( "flags now %u\n", t3 );
  870. srec->flags = t3;
  871. break;
  872. case '~':
  873. debug( "status now %#x\n", t3 );
  874. srec->status = t3;
  875. break;
  876. default:
  877. error( "Error: unrecognized journal entry at %s:%d\n", svars->jname, line );
  878. goto jbail;
  879. }
  880. }
  881. }
  882. }
  883. fclose( jfp );
  884. } else {
  885. if (errno != ENOENT) {
  886. sys_error( "Error: cannot read journal %s", svars->jname );
  887. return 0;
  888. }
  889. }
  890. svars->replayed = line;
  891. return 1;
  892. }
  893. static void
  894. delete_state( sync_vars_t *svars )
  895. {
  896. unlink( svars->nname );
  897. unlink( svars->jname );
  898. if (unlink( svars->dname ) || unlink( svars->lname )) {
  899. sys_error( "Error: channel %s: sync state cannot be deleted", svars->chan->name );
  900. svars->ret = SYNC_FAIL;
  901. }
  902. }
  903. static void box_confirmed( int sts, int uidvalidity, void *aux );
  904. static void box_confirmed2( sync_vars_t *svars, int t );
  905. static void box_deleted( int sts, void *aux );
  906. static void box_created( int sts, void *aux );
  907. static void box_opened( int sts, int uidvalidity, void *aux );
  908. static void box_opened2( sync_vars_t *svars, int t );
  909. static void load_box( sync_vars_t *svars, int t, uint minwuid, uint_array_t mexcs );
  910. void
  911. sync_boxes( store_t *ctx[], const char *names[], int present[], channel_conf_t *chan,
  912. void (*cb)( int sts, void *aux ), void *aux )
  913. {
  914. sync_vars_t *svars;
  915. int t;
  916. svars = nfcalloc( sizeof(*svars) );
  917. svars->t[1] = 1;
  918. svars->ref_count = 1;
  919. svars->cb = cb;
  920. svars->aux = aux;
  921. svars->ctx[0] = ctx[0];
  922. svars->ctx[1] = ctx[1];
  923. svars->chan = chan;
  924. svars->lfd = -1;
  925. svars->uidval[0] = svars->uidval[1] = UIDVAL_BAD;
  926. svars->srecadd = &svars->srecs;
  927. for (t = 0; t < 2; t++) {
  928. svars->orig_name[t] =
  929. (!names[t] || (ctx[t]->conf->map_inbox && !strcmp( ctx[t]->conf->map_inbox, names[t] ))) ?
  930. "INBOX" : names[t];
  931. if (!ctx[t]->conf->flat_delim[0]) {
  932. svars->box_name[t] = nfstrdup( svars->orig_name[t] );
  933. } else if (map_name( svars->orig_name[t], &svars->box_name[t], 0, "/", ctx[t]->conf->flat_delim ) < 0) {
  934. error( "Error: canonical mailbox name '%s' contains flattened hierarchy delimiter\n", svars->orig_name[t] );
  935. bail3:
  936. svars->ret = SYNC_FAIL;
  937. sync_bail3( svars );
  938. return;
  939. }
  940. svars->drv[t] = ctx[t]->driver;
  941. svars->drv[t]->set_bad_callback( ctx[t], store_bad, AUX );
  942. }
  943. /* Both boxes must be fully set up at this point, so that error exit paths
  944. * don't run into uninitialized variables. */
  945. for (t = 0; t < 2; t++) {
  946. switch (svars->drv[t]->select_box( ctx[t], svars->box_name[t] )) {
  947. case DRV_CANCELED:
  948. store_bad( AUX );
  949. return;
  950. case DRV_BOX_BAD:
  951. goto bail3;
  952. }
  953. }
  954. if (!prepare_state( svars )) {
  955. svars->ret = SYNC_FAIL;
  956. sync_bail2( svars );
  957. return;
  958. }
  959. if (!load_state( svars )) {
  960. svars->ret = SYNC_FAIL;
  961. sync_bail( svars );
  962. return;
  963. }
  964. sync_ref( svars );
  965. for (t = 0; ; t++) {
  966. info( "Opening %s box %s...\n", str_ms[t], svars->orig_name[t] );
  967. if (present[t] == BOX_ABSENT)
  968. box_confirmed2( svars, t );
  969. else
  970. svars->drv[t]->open_box( ctx[t], box_confirmed, AUX );
  971. if (t || check_cancel( svars ))
  972. break;
  973. }
  974. sync_deref( svars );
  975. }
  976. static void
  977. box_confirmed( int sts, int uidvalidity, void *aux )
  978. {
  979. DECL_SVARS;
  980. if (sts == DRV_CANCELED)
  981. return;
  982. INIT_SVARS(aux);
  983. if (check_cancel( svars ))
  984. return;
  985. if (sts == DRV_OK) {
  986. svars->state[t] |= ST_PRESENT;
  987. svars->newuidval[t] = uidvalidity;
  988. }
  989. box_confirmed2( svars, t );
  990. }
  991. static void
  992. box_confirmed2( sync_vars_t *svars, int t )
  993. {
  994. svars->state[t] |= ST_CONFIRMED;
  995. if (!(svars->state[1-t] & ST_CONFIRMED))
  996. return;
  997. sync_ref( svars );
  998. for (t = 0; ; t++) {
  999. if (!(svars->state[t] & ST_PRESENT)) {
  1000. if (!(svars->state[1-t] & ST_PRESENT)) {
  1001. if (!svars->existing) {
  1002. error( "Error: channel %s: both master %s and slave %s cannot be opened.\n",
  1003. svars->chan->name, svars->orig_name[M], svars->orig_name[S] );
  1004. bail:
  1005. svars->ret = SYNC_FAIL;
  1006. } else {
  1007. /* This can legitimately happen if a deletion propagation was interrupted.
  1008. * We have no place to record this transaction, so we just assume it.
  1009. * Of course this bears the danger of clearing the state if both mailboxes
  1010. * temorarily cannot be opened for some weird reason (while the stores can). */
  1011. delete_state( svars );
  1012. }
  1013. done:
  1014. sync_bail( svars );
  1015. break;
  1016. }
  1017. if (svars->existing) {
  1018. if (!(svars->chan->ops[1-t] & OP_REMOVE)) {
  1019. error( "Error: channel %s: %s %s cannot be opened.\n",
  1020. svars->chan->name, str_ms[t], svars->orig_name[t] );
  1021. goto bail;
  1022. }
  1023. if (svars->drv[1-t]->confirm_box_empty( svars->ctx[1-t] ) != DRV_OK) {
  1024. warn( "Warning: channel %s: %s %s cannot be opened and %s %s not empty.\n",
  1025. svars->chan->name, str_ms[t], svars->orig_name[t], str_ms[1-t], svars->orig_name[1-t] );
  1026. goto done;
  1027. }
  1028. info( "Deleting %s %s...\n", str_ms[1-t], svars->orig_name[1-t] );
  1029. svars->drv[1-t]->delete_box( svars->ctx[1-t], box_deleted, INV_AUX );
  1030. } else {
  1031. if (!(svars->chan->ops[t] & OP_CREATE)) {
  1032. box_opened( DRV_BOX_BAD, UIDVAL_BAD, AUX );
  1033. } else {
  1034. info( "Creating %s %s...\n", str_ms[t], svars->orig_name[t] );
  1035. svars->drv[t]->create_box( svars->ctx[t], box_created, AUX );
  1036. }
  1037. }
  1038. } else {
  1039. box_opened2( svars, t );
  1040. }
  1041. if (t || check_cancel( svars ))
  1042. break;
  1043. }
  1044. sync_deref( svars );
  1045. }
  1046. static void
  1047. box_deleted( int sts, void *aux )
  1048. {
  1049. DECL_SVARS;
  1050. if (check_ret( sts, aux ))
  1051. return;
  1052. INIT_SVARS(aux);
  1053. delete_state( svars );
  1054. svars->drv[t]->finish_delete_box( svars->ctx[t] );
  1055. sync_bail( svars );
  1056. }
  1057. static void
  1058. box_created( int sts, void *aux )
  1059. {
  1060. DECL_SVARS;
  1061. if (check_ret( sts, aux ))
  1062. return;
  1063. INIT_SVARS(aux);
  1064. svars->drv[t]->open_box( svars->ctx[t], box_opened, AUX );
  1065. }
  1066. static void
  1067. box_opened( int sts, int uidvalidity, void *aux )
  1068. {
  1069. DECL_SVARS;
  1070. if (sts == DRV_CANCELED)
  1071. return;
  1072. INIT_SVARS(aux);
  1073. if (check_cancel( svars ))
  1074. return;
  1075. if (sts == DRV_BOX_BAD) {
  1076. error( "Error: channel %s: %s %s cannot be opened.\n",
  1077. svars->chan->name, str_ms[t], svars->orig_name[t] );
  1078. svars->ret = SYNC_FAIL;
  1079. sync_bail( svars );
  1080. } else {
  1081. svars->newuidval[t] = uidvalidity;
  1082. box_opened2( svars, t );
  1083. }
  1084. }
  1085. static void
  1086. box_opened2( sync_vars_t *svars, int t )
  1087. {
  1088. store_t *ctx[2];
  1089. channel_conf_t *chan;
  1090. sync_rec_t *srec;
  1091. uint_array_alloc_t mexcs;
  1092. uint minwuid;
  1093. int opts[2], fails;
  1094. svars->state[t] |= ST_SELECTED;
  1095. if (!(svars->state[1-t] & ST_SELECTED))
  1096. return;
  1097. ctx[0] = svars->ctx[0];
  1098. ctx[1] = svars->ctx[1];
  1099. chan = svars->chan;
  1100. fails = 0;
  1101. for (t = 0; t < 2; t++)
  1102. if (svars->uidval[t] != UIDVAL_BAD && svars->uidval[t] != svars->newuidval[t])
  1103. fails++;
  1104. if (fails == 2) {
  1105. error( "Error: channel %s: UIDVALIDITY of both master and slave changed\n"
  1106. "(master got %u, expected %u; slave got %u, expected %u).\n",
  1107. svars->chan->name,
  1108. svars->newuidval[M], svars->uidval[M], svars->newuidval[S], svars->uidval[S] );
  1109. bail:
  1110. svars->ret = SYNC_FAIL;
  1111. sync_bail( svars );
  1112. return;
  1113. }
  1114. if (!lock_state( svars ))
  1115. goto bail;
  1116. if (!(svars->nfp = fopen( svars->nname, "w" ))) {
  1117. sys_error( "Error: cannot create new sync state %s", svars->nname );
  1118. goto bail;
  1119. }
  1120. if (!(svars->jfp = fopen( svars->jname, "a" ))) {
  1121. sys_error( "Error: cannot create journal %s", svars->jname );
  1122. fclose( svars->nfp );
  1123. goto bail;
  1124. }
  1125. setlinebuf( svars->jfp );
  1126. if (!svars->replayed)
  1127. jFprintf( svars, JOURNAL_VERSION "\n" );
  1128. opts[M] = opts[S] = 0;
  1129. if (fails)
  1130. opts[M] = opts[S] = OPEN_OLD|OPEN_OLD_IDS;
  1131. for (t = 0; t < 2; t++) {
  1132. if (chan->ops[t] & (OP_DELETE|OP_FLAGS)) {
  1133. opts[t] |= OPEN_SETFLAGS;
  1134. opts[1-t] |= OPEN_OLD;
  1135. if (chan->ops[t] & OP_FLAGS)
  1136. opts[1-t] |= OPEN_FLAGS;
  1137. }
  1138. if (chan->ops[t] & (OP_NEW|OP_RENEW)) {
  1139. opts[t] |= OPEN_APPEND;
  1140. if (chan->ops[t] & OP_RENEW)
  1141. opts[1-t] |= OPEN_OLD;
  1142. if (chan->ops[t] & OP_NEW)
  1143. opts[1-t] |= OPEN_NEW;
  1144. if (chan->ops[t] & OP_EXPUNGE)
  1145. opts[1-t] |= OPEN_FLAGS;
  1146. if (chan->stores[t]->max_size != INT_MAX) {
  1147. if (chan->ops[t] & OP_RENEW)
  1148. opts[1-t] |= OPEN_FLAGS|OPEN_OLD_SIZE;
  1149. if (chan->ops[t] & OP_NEW)
  1150. opts[1-t] |= OPEN_FLAGS|OPEN_NEW_SIZE;
  1151. }
  1152. }
  1153. if (chan->ops[t] & OP_EXPUNGE) {
  1154. opts[t] |= OPEN_EXPUNGE;
  1155. if (chan->stores[t]->trash) {
  1156. if (!chan->stores[t]->trash_only_new)
  1157. opts[t] |= OPEN_OLD;
  1158. opts[t] |= OPEN_NEW|OPEN_FLAGS;
  1159. } else if (chan->stores[1-t]->trash && chan->stores[1-t]->trash_remote_new)
  1160. opts[t] |= OPEN_NEW|OPEN_FLAGS;
  1161. }
  1162. }
  1163. if ((chan->ops[S] & (OP_NEW|OP_RENEW|OP_FLAGS)) && chan->max_messages)
  1164. opts[S] |= OPEN_OLD|OPEN_NEW|OPEN_FLAGS;
  1165. if (svars->replayed)
  1166. for (srec = svars->srecs; srec; srec = srec->next) {
  1167. if (srec->status & S_DEAD)
  1168. continue;
  1169. if (srec->tuid[0]) {
  1170. if (!srec->uid[M])
  1171. opts[M] |= OPEN_NEW|OPEN_FIND, svars->state[M] |= ST_FIND_OLD;
  1172. else if (!srec->uid[S])
  1173. opts[S] |= OPEN_NEW|OPEN_FIND, svars->state[S] |= ST_FIND_OLD;
  1174. else
  1175. warn( "Warning: sync record (%d,%d) has stray TUID. Ignoring.\n", srec->uid[M], srec->uid[S] );
  1176. }
  1177. }
  1178. svars->opts[M] = svars->drv[M]->prepare_load_box( ctx[M], opts[M] );
  1179. svars->opts[S] = svars->drv[S]->prepare_load_box( ctx[S], opts[S] );
  1180. ARRAY_INIT( &mexcs );
  1181. if (svars->opts[M] & OPEN_OLD) {
  1182. if (chan->max_messages) {
  1183. /* When messages have been expired on the slave, the master fetch is split into
  1184. * two ranges: The bulk fetch which corresponds with the most recent messages, and an
  1185. * exception list of messages which would have been expired if they weren't important. */
  1186. debug( "preparing master selection - max expired master uid is %u\n", svars->mmaxxuid );
  1187. /* First, find out the lower bound for the bulk fetch. */
  1188. minwuid = svars->mmaxxuid + 1;
  1189. /* Next, calculate the exception fetch. */
  1190. for (srec = svars->srecs; srec; srec = srec->next) {
  1191. if (srec->status & S_DEAD)
  1192. continue;
  1193. if (!srec->uid[M]) // No message; other state is irrelevant
  1194. continue;
  1195. if (minwuid > srec->uid[M] && (!(svars->opts[M] & OPEN_NEW) || svars->maxuid[M] >= srec->uid[M])) {
  1196. if (!srec->uid[S] && !(srec->status & S_PENDING)) // Only actually paired up messages matter
  1197. continue;
  1198. /* The pair is alive, but outside the bulk range. */
  1199. *uint_array_append( &mexcs ) = srec->uid[M];
  1200. }
  1201. }
  1202. sort_uint_array( mexcs.array );
  1203. } else {
  1204. minwuid = 1;
  1205. }
  1206. } else {
  1207. minwuid = UINT_MAX;
  1208. }
  1209. sync_ref( svars );
  1210. load_box( svars, M, minwuid, mexcs.array );
  1211. if (!check_cancel( svars ))
  1212. load_box( svars, S, (svars->opts[S] & OPEN_OLD) ? 1 : UINT_MAX, (uint_array_t){ 0, 0 } );
  1213. sync_deref( svars );
  1214. }
  1215. static int
  1216. get_seenuid( sync_vars_t *svars, int t )
  1217. {
  1218. uint seenuid = 0;
  1219. for (sync_rec_t *srec = svars->srecs; srec; srec = srec->next)
  1220. if (!(srec->status & S_DEAD) && seenuid < srec->uid[t])
  1221. seenuid = srec->uid[t];
  1222. return seenuid;
  1223. }
  1224. static void box_loaded( int sts, message_t *msgs, int total_msgs, int recent_msgs, void *aux );
  1225. static void
  1226. load_box( sync_vars_t *svars, int t, uint minwuid, uint_array_t mexcs )
  1227. {
  1228. uint maxwuid, seenuid;
  1229. if (svars->opts[t] & OPEN_NEW) {
  1230. if (minwuid > svars->maxuid[t] + 1)
  1231. minwuid = svars->maxuid[t] + 1;
  1232. maxwuid = UINT_MAX;
  1233. if (svars->opts[t] & (OPEN_OLD_IDS|OPEN_OLD_SIZE))
  1234. seenuid = get_seenuid( svars, t );
  1235. else
  1236. seenuid = 0;
  1237. } else if (svars->opts[t] & OPEN_OLD) {
  1238. maxwuid = seenuid = get_seenuid( svars, t );
  1239. } else
  1240. maxwuid = seenuid = 0;
  1241. if (seenuid < svars->maxuid[t]) {
  1242. /* We cannot rely on the maxuid, as uni-directional syncing does not update it.
  1243. * But if it is there, use it to avoid a possible gap in the fetched range. */
  1244. seenuid = svars->maxuid[t];
  1245. }
  1246. info( "Loading %s...\n", str_ms[t] );
  1247. svars->drv[t]->load_box( svars->ctx[t], minwuid, maxwuid, svars->newuid[t], seenuid, mexcs, box_loaded, AUX );
  1248. }
  1249. typedef struct {
  1250. void *aux;
  1251. sync_rec_t *srec;
  1252. int aflags, dflags;
  1253. } flag_vars_t;
  1254. typedef struct {
  1255. uint uid;
  1256. sync_rec_t *srec;
  1257. } sync_rec_map_t;
  1258. static void flags_set( int sts, void *aux );
  1259. static void flags_set_p2( sync_vars_t *svars, sync_rec_t *srec, int t );
  1260. static void msgs_flags_set( sync_vars_t *svars, int t );
  1261. static void msg_copied( int sts, uint uid, copy_vars_t *vars );
  1262. static void msgs_copied( sync_vars_t *svars, int t );
  1263. static void
  1264. box_loaded( int sts, message_t *msgs, int total_msgs, int recent_msgs, void *aux )
  1265. {
  1266. DECL_SVARS;
  1267. sync_rec_t *srec;
  1268. sync_rec_map_t *srecmap;
  1269. message_t *tmsg;
  1270. flag_vars_t *fv;
  1271. int no[2], del[2], alive, todel;
  1272. int sflags, nflags, aflags, dflags;
  1273. uint hashsz, idx;
  1274. if (check_ret( sts, aux ))
  1275. return;
  1276. INIT_SVARS(aux);
  1277. svars->state[t] |= ST_LOADED;
  1278. svars->msgs[t] = msgs;
  1279. info( "%s: %d messages, %d recent\n", str_ms[t], total_msgs, recent_msgs );
  1280. if (svars->state[t] & ST_FIND_OLD) {
  1281. debug( "matching previously copied messages on %s\n", str_ms[t] );
  1282. match_tuids( svars, t, msgs );
  1283. }
  1284. debug( "matching messages on %s against sync records\n", str_ms[t] );
  1285. hashsz = bucketsForSize( svars->nsrecs * 3 );
  1286. srecmap = nfcalloc( hashsz * sizeof(*srecmap) );
  1287. for (srec = svars->srecs; srec; srec = srec->next) {
  1288. if (srec->status & S_DEAD)
  1289. continue;
  1290. uint uid = srec->uid[t];
  1291. if (!uid)
  1292. continue;
  1293. idx = (uint)(uid * 1103515245U) % hashsz;
  1294. while (srecmap[idx].uid)
  1295. if (++idx == hashsz)
  1296. idx = 0;
  1297. srecmap[idx].uid = uid;
  1298. srecmap[idx].srec = srec;
  1299. }
  1300. for (tmsg = svars->msgs[t]; tmsg; tmsg = tmsg->next) {
  1301. if (tmsg->srec) /* found by TUID */
  1302. continue;
  1303. uint uid = tmsg->uid;
  1304. idx = (uint)(uid * 1103515245U) % hashsz;
  1305. while (srecmap[idx].uid) {
  1306. if (srecmap[idx].uid == uid) {
  1307. srec = srecmap[idx].srec;
  1308. goto found;
  1309. }
  1310. if (++idx == hashsz)
  1311. idx = 0;
  1312. }
  1313. continue;
  1314. found:
  1315. tmsg->srec = srec;
  1316. srec->msg[t] = tmsg;
  1317. }
  1318. free( srecmap );
  1319. if (!(svars->state[1-t] & ST_LOADED))
  1320. return;
  1321. for (t = 0; t < 2; t++) {
  1322. if (svars->uidval[t] != UIDVAL_BAD && svars->uidval[t] != svars->newuidval[t]) {
  1323. unsigned need = 0, got = 0;
  1324. debug( "trying to re-approve uid validity of %s\n", str_ms[t] );
  1325. for (srec = svars->srecs; srec; srec = srec->next) {
  1326. if (srec->status & S_DEAD)
  1327. continue;
  1328. if (!srec->msg[t])
  1329. continue; // Message disappeared.
  1330. need++; // Present paired messages require re-validation.
  1331. if (!srec->msg[t]->msgid)
  1332. continue; // Messages without ID are useless for re-validation.
  1333. if (!srec->msg[1-t])
  1334. continue; // Partner disappeared.
  1335. if (!srec->msg[1-t]->msgid || strcmp( srec->msg[M]->msgid, srec->msg[S]->msgid )) {
  1336. error( "Error: channel %s, %s %s: UIDVALIDITY genuinely changed (at UID %u).\n",
  1337. svars->chan->name, str_ms[t], svars->orig_name[t], srec->uid[t] );
  1338. uvchg:
  1339. svars->ret |= SYNC_FAIL;
  1340. cancel_sync( svars );
  1341. return;
  1342. }
  1343. got++;
  1344. }
  1345. if (got < 20 && got * 5 < need * 4) {
  1346. // Too few confirmed messages. This is very likely in the drafts folder.
  1347. // A proper fallback would be fetching more headers (which potentially need
  1348. // normalization) or the message body (which should be truncated for sanity)
  1349. // and comparing.
  1350. error( "Error: channel %s, %s %s: Unable to recover from UIDVALIDITY change\n"
  1351. "(got %u, expected %u).\n",
  1352. svars->chan->name, str_ms[t], svars->orig_name[t],
  1353. svars->newuidval[t], svars->uidval[t] );
  1354. goto uvchg;
  1355. }
  1356. notice( "Notice: channel %s, %s %s: Recovered from change of UIDVALIDITY.\n",
  1357. svars->chan->name, str_ms[t], svars->orig_name[t] );
  1358. svars->uidval[t] = UIDVAL_BAD;
  1359. }
  1360. }
  1361. if (svars->uidval[M] == UIDVAL_BAD || svars->uidval[S] == UIDVAL_BAD) {
  1362. svars->uidval[M] = svars->newuidval[M];
  1363. svars->uidval[S] = svars->newuidval[S];
  1364. jFprintf( svars, "| %u %u\n", svars->uidval[M], svars->uidval[S] );
  1365. }
  1366. info( "Synchronizing...\n" );
  1367. debug( "synchronizing old entries\n" );
  1368. for (srec = svars->srecs; srec; srec = srec->next) {
  1369. if (srec->status & S_DEAD)
  1370. continue;
  1371. debug( "pair (%u,%u)\n", srec->uid[M], srec->uid[S] );
  1372. assert( !srec->tuid[0] );
  1373. // no[] means that a message is known to be not there.
  1374. no[M] = !srec->msg[M] && (svars->opts[M] & OPEN_OLD);
  1375. no[S] = !srec->msg[S] && (svars->opts[S] & OPEN_OLD);
  1376. if (no[M] && no[S]) {
  1377. // It does not matter whether one side was already known to be missing
  1378. // (never stored [skipped or failed] or expunged [possibly expired]) -
  1379. // now both are missing, so the entry is superfluous.
  1380. debug( " vanished\n" );
  1381. srec->status = S_DEAD;
  1382. jFprintf( svars, "- %u %u\n", srec->uid[M], srec->uid[S] );
  1383. } else {
  1384. // del[] means that a message becomes known to have been expunged.
  1385. del[M] = no[M] && srec->uid[M];
  1386. del[S] = no[S] && srec->uid[S];
  1387. for (t = 0; t < 2; t++) {
  1388. srec->aflags[t] = srec->dflags[t] = 0;
  1389. if (srec->msg[t] && (srec->msg[t]->flags & F_DELETED))
  1390. srec->wstate |= W_DEL(t);
  1391. if (del[t]) {
  1392. // The target was newly expunged, so there is nothing to update.
  1393. // The deletion is propagated in the opposite iteration.
  1394. } else if (!srec->uid[t]) {
  1395. // The target was never stored, or was previously expunged, so there
  1396. // is nothing to update.
  1397. // Note: the opposite UID must be valid, as otherwise the entry would
  1398. // have been pruned already.
  1399. } else if (del[1-t]) {
  1400. // The source was newly expunged, so possibly propagate the deletion.
  1401. // The target may be in an unknown state (not fetched).
  1402. if ((t == M) && (srec->status & (S_EXPIRE|S_EXPIRED))) {
  1403. /* Don't propagate deletion resulting from expiration. */
  1404. debug( " slave expired, orphaning master\n" );
  1405. jFprintf( svars, "> %u %u 0\n", srec->uid[M], srec->uid[S] );
  1406. srec->uid[S] = 0;
  1407. } else {
  1408. if (srec->msg[t] && (srec->msg[t]->status & M_FLAGS) && srec->msg[t]->flags != srec->flags)
  1409. notice( "Notice: conflicting changes in (%u,%u)\n", srec->uid[M], srec->uid[S] );
  1410. if (svars->chan->ops[t] & OP_DELETE) {
  1411. debug( " %sing delete\n", str_hl[t] );
  1412. srec->aflags[t] = F_DELETED;
  1413. srec->wstate |= W_DELETE;
  1414. } else {
  1415. debug( " not %sing delete\n", str_hl[t] );
  1416. }
  1417. }
  1418. } else if (!srec->msg[1-t]) {
  1419. // We have no source to work with, because it was never stored,
  1420. // it was previously expunged, or we did not fetch it.
  1421. debug( " no %s\n", str_ms[1-t] );
  1422. } else {
  1423. // We have a source. The target may be in an unknown state.
  1424. if (svars->chan->ops[t] & OP_FLAGS) {
  1425. sflags = srec->msg[1-t]->flags;
  1426. if ((t == M) && (srec->status & (S_EXPIRE|S_EXPIRED))) {
  1427. /* Don't propagate deletion resulting from expiration. */
  1428. debug( " slave expiring\n" );
  1429. sflags &= ~F_DELETED;
  1430. }
  1431. srec->aflags[t] = sflags & ~srec->flags;
  1432. srec->dflags[t] = ~sflags & srec->flags;
  1433. if ((DFlags & DEBUG_SYNC) && (srec->aflags[t] || srec->dflags[t])) {
  1434. char afbuf[16], dfbuf[16]; /* enlarge when support for keywords is added */
  1435. make_flags( srec->aflags[t], afbuf );
  1436. make_flags( srec->dflags[t], dfbuf );
  1437. debug( " %sing flags: +%s -%s\n", str_hl[t], afbuf, dfbuf );
  1438. }
  1439. }
  1440. }
  1441. }
  1442. }
  1443. }
  1444. debug( "synchronizing new entries\n" );
  1445. for (t = 0; t < 2; t++) {
  1446. for (tmsg = svars->msgs[1-t]; tmsg; tmsg = tmsg->next) {
  1447. // If new have no srec, the message is always New. If we have a srec:
  1448. // - message is paired or expired => ignore
  1449. // - message was skipped => ReNew
  1450. // - message was attempted, but is still pending or failed => New
  1451. //
  1452. // If messages were previously ignored due to being excessive, they would now
  1453. // appear to be newer than the messages that got actually synced, so increment
  1454. // newmaxuid immediately to make sure we always look only at the newest ones.
  1455. // However, committing it to maxuid must be delayed until all messages were
  1456. // propagated, to ensure that all pending messages are still loaded next time
  1457. // in case of interruption - in particular skipping big messages would otherwise
  1458. // up the limit too early.
  1459. srec = tmsg->srec;
  1460. if (srec ? !srec->uid[t] &&
  1461. (((srec->status & S_PENDING) && (svars->chan->ops[t] & OP_NEW)) ||
  1462. ((srec->status & S_SKIPPED) && (svars->chan->ops[t] & OP_RENEW)))
  1463. : svars->newmaxuid[1-t] < tmsg->uid && (svars->chan->ops[t] & OP_NEW)) {
  1464. debug( "new message %u on %s\n", tmsg->uid, str_ms[1-t] );
  1465. if ((svars->chan->ops[t] & OP_EXPUNGE) && (tmsg->flags & F_DELETED)) {
  1466. debug( " -> not %sing - would be expunged anyway\n", str_hl[t] );
  1467. } else {
  1468. if (srec) {
  1469. debug( " -> pair(%u,%u) exists\n", srec->uid[M], srec->uid[S] );
  1470. } else {
  1471. srec = nfmalloc( sizeof(*srec) );
  1472. srec->next = 0;
  1473. *svars->srecadd = srec;
  1474. svars->srecadd = &srec->next;
  1475. svars->nsrecs++;
  1476. srec->status = S_PENDING;
  1477. srec->wstate = 0;
  1478. srec->flags = 0;
  1479. srec->tuid[0] = 0;
  1480. srec->uid[1-t] = tmsg->uid;
  1481. srec->uid[t] = 0;
  1482. srec->msg[1-t] = tmsg;
  1483. srec->msg[t] = 0;
  1484. tmsg->srec = srec;
  1485. if (svars->newmaxuid[1-t] < tmsg->uid)
  1486. svars->newmaxuid[1-t] = tmsg->uid;
  1487. jFprintf( svars, "+ %u %u\n", srec->uid[M], srec->uid[S] );
  1488. debug( " -> pair(%u,%u) created\n", srec->uid[M], srec->uid[S] );
  1489. }
  1490. if ((tmsg->flags & F_FLAGGED) || tmsg->size <= svars->chan->stores[t]->max_size) {
  1491. if (tmsg->flags != srec->flags) {
  1492. srec->flags = tmsg->flags;
  1493. jFprintf( svars, "* %u %u %u\n", srec->uid[M], srec->uid[S], srec->flags );
  1494. debug( " -> updated flags to %u\n", tmsg->flags );
  1495. }
  1496. if (srec->status != S_PENDING) {
  1497. debug( " -> not too big any more\n" );
  1498. srec->status = S_PENDING;
  1499. jFprintf( svars, "~ %d %d %u\n", srec->uid[M], srec->uid[S], srec->status );
  1500. }
  1501. } else {
  1502. if (srec->status == S_SKIPPED) {
  1503. debug( " -> not %sing - still too big\n", str_hl[t] );
  1504. } else {
  1505. debug( " -> not %sing - too big\n", str_hl[t] );
  1506. srec->status = S_SKIPPED;
  1507. jFprintf( svars, "~ %d %d %u\n", srec->uid[M], srec->uid[S], srec->status );
  1508. }
  1509. }
  1510. }
  1511. }
  1512. }
  1513. }
  1514. if ((svars->chan->ops[S] & (OP_NEW|OP_RENEW|OP_FLAGS)) && svars->chan->max_messages) {
  1515. /* Note: When this branch is entered, we have loaded all slave messages. */
  1516. /* Expire excess messages. Important (flagged, unread, or unpropagated) messages
  1517. * older than the first not expired message are not counted towards the total. */
  1518. debug( "preparing message expiration\n" );
  1519. alive = 0;
  1520. for (tmsg = svars->msgs[S]; tmsg; tmsg = tmsg->next) {
  1521. if (tmsg->status & M_DEAD)
  1522. continue;
  1523. if ((srec = tmsg->srec) && srec->uid[M] &&
  1524. ((tmsg->flags | srec->aflags[S]) & ~srec->dflags[S] & F_DELETED) &&
  1525. !(srec->status & (S_EXPIRE|S_EXPIRED))) {
  1526. /* Message was not propagated yet, or is deleted. */
  1527. } else {
  1528. alive++;
  1529. }
  1530. }
  1531. for (tmsg = svars->msgs[M]; tmsg; tmsg = tmsg->next) {
  1532. if ((srec = tmsg->srec) && (srec->status & S_PENDING) && !(tmsg->flags & F_DELETED))
  1533. alive++;
  1534. }
  1535. todel = alive - svars->chan->max_messages;
  1536. debug( "%d alive messages, %d excess - expiring\n", alive, todel );
  1537. alive = 0;
  1538. for (tmsg = svars->msgs[S]; tmsg; tmsg = tmsg->next) {
  1539. if (tmsg->status & M_DEAD)
  1540. continue;
  1541. if (!(srec = tmsg->srec) || !srec->uid[M]) {
  1542. /* We did not push the message, so it must be kept. */
  1543. debug( " message %u unpropagated\n", tmsg->uid );
  1544. todel--;
  1545. } else {
  1546. nflags = (tmsg->flags | srec->aflags[S]) & ~srec->dflags[S];
  1547. if (!(nflags & F_DELETED) || (srec->status & (S_EXPIRE|S_EXPIRED))) {
  1548. /* The message is not deleted, or is already (being) expired. */
  1549. if ((nflags & F_FLAGGED) || !((nflags & F_SEEN) || ((void)(todel > 0 && alive++), svars->chan->expire_unread > 0))) {
  1550. /* Important messages are always kept. */
  1551. debug( " old pair(%u,%u) important\n", srec->uid[M], srec->uid[S] );
  1552. todel--;
  1553. } else if (todel > 0 ||
  1554. ((srec->status & (S_EXPIRE|S_EXPIRED)) == (S_EXPIRE|S_EXPIRED)) ||
  1555. ((srec->status & (S_EXPIRE|S_EXPIRED)) && (tmsg->flags & F_DELETED))) {
  1556. /* The message is excess or was already (being) expired. */
  1557. srec->wstate |= W_NEXPIRE;
  1558. debug( " old pair(%u,%u) expired\n", srec->uid[M], srec->uid[S] );
  1559. if (svars->mmaxxuid < srec->uid[M])
  1560. svars->mmaxxuid = srec->uid[M];
  1561. todel--;
  1562. }
  1563. }
  1564. }
  1565. }
  1566. for (tmsg = svars->msgs[M]; tmsg; tmsg = tmsg->next) {
  1567. if ((srec = tmsg->srec) && (srec->status & S_PENDING)) {
  1568. nflags = tmsg->flags;
  1569. if (!(nflags & F_DELETED)) {
  1570. if ((nflags & F_FLAGGED) || !((nflags & F_SEEN) || ((void)(todel > 0 && alive++), svars->chan->expire_unread > 0))) {
  1571. /* Important messages are always fetched. */
  1572. debug( " new pair(%u,%u) important\n", srec->uid[M], srec->uid[S] );
  1573. todel--;
  1574. } else if (todel > 0) {
  1575. /* The message is excess. */
  1576. srec->wstate |= W_NEXPIRE;
  1577. todel--;
  1578. }
  1579. }
  1580. }
  1581. }
  1582. debug( "%d excess messages remain\n", todel );
  1583. if (svars->chan->expire_unread < 0 && (uint)alive * 2 > svars->chan->max_messages) {
  1584. error( "%s: %d unread messages in excess of MaxMessages (%d).\n"
  1585. "Please set ExpireUnread to decide outcome. Skipping mailbox.\n",
  1586. svars->orig_name[S], alive, svars->chan->max_messages );
  1587. svars->ret |= SYNC_FAIL;
  1588. cancel_sync( svars );
  1589. return;
  1590. }
  1591. for (srec = svars->srecs; srec; srec = srec->next) {
  1592. if (srec->status & S_DEAD)
  1593. continue;
  1594. if (!(srec->status & S_PENDING)) {
  1595. if (!srec->msg[S])
  1596. continue;
  1597. uint nex = (srec->wstate / W_NEXPIRE) & 1;
  1598. if (nex != ((srec->status / S_EXPIRED) & 1)) {
  1599. /* The record needs a state change ... */
  1600. if (nex != ((srec->status / S_EXPIRE) & 1)) {
  1601. /* ... and we need to start a transaction. */
  1602. debug( " pair(%u,%u): %u (pre)\n", srec->uid[M], srec->uid[S], nex );
  1603. srec->status = (srec->status & ~S_EXPIRE) | (nex * S_EXPIRE);
  1604. jFprintf( svars, "~ %u %u %u\n", srec->uid[M], srec->uid[S], srec->status );
  1605. } else {
  1606. /* ... but the "right" transaction is already pending. */
  1607. debug( " pair(%u,%u): %d (pending)\n", srec->uid[M], srec->uid[S], nex );
  1608. }
  1609. } else {
  1610. /* Note: the "wrong" transaction may be pending here,
  1611. * e.g.: W_NEXPIRE = 0, S_EXPIRE = 1, S_EXPIRED = 0. */
  1612. }
  1613. } else {
  1614. if (srec->wstate & W_NEXPIRE) {
  1615. jFprintf( svars, "= %u %u\n", srec->uid[M], srec->uid[S] );
  1616. debug( " pair(%u,%u): 1 (abort)\n", srec->uid[M], srec->uid[S] );
  1617. // If we have so many new messages that some of them are instantly expired,
  1618. // but some are still propagated because they are important, we need to
  1619. // ensure explicitly that the bulk fetch limit is upped.
  1620. svars->mmaxxuid = srec->uid[M];
  1621. srec->msg[M]->srec = 0;
  1622. srec->status = S_DEAD;
  1623. }
  1624. }
  1625. }
  1626. }
  1627. sync_ref( svars );
  1628. debug( "synchronizing flags\n" );
  1629. for (srec = svars->srecs; srec; srec = srec->next) {
  1630. if ((srec->status & S_DEAD) || !srec->uid[M] || !srec->uid[S])
  1631. continue;
  1632. for (t = 0; t < 2; t++) {
  1633. aflags = srec->aflags[t];
  1634. dflags = srec->dflags[t];
  1635. if (srec->wstate & W_DELETE) {
  1636. if (!aflags) {
  1637. /* This deletion propagation goes the other way round. */
  1638. continue;
  1639. }
  1640. } else {
  1641. /* The trigger is an expiration transaction being ongoing ... */
  1642. if ((t == S) && ((shifted_bit(srec->status, S_EXPIRE, S_EXPIRED) ^ srec->status) & S_EXPIRED)) {
  1643. /* ... but the actual action derives from the wanted state. */
  1644. if (srec->wstate & W_NEXPIRE)
  1645. aflags |= F_DELETED;
  1646. else
  1647. dflags |= F_DELETED;
  1648. }
  1649. }
  1650. if ((svars->chan->ops[t] & OP_EXPUNGE) && (((srec->msg[t] ? srec->msg[t]->flags : 0) | aflags) & ~dflags & F_DELETED) &&
  1651. (!svars->ctx[t]->conf->trash || svars->ctx[t]->conf->trash_only_new))
  1652. {
  1653. /* If the message is going to be expunged, don't propagate anything but the deletion. */
  1654. srec->aflags[t] &= F_DELETED;
  1655. aflags &= F_DELETED;
  1656. srec->dflags[t] = dflags = 0;
  1657. }
  1658. if (srec->msg[t] && (srec->msg[t]->status & M_FLAGS)) {
  1659. /* If we know the target message's state, optimize away non-changes. */
  1660. aflags &= ~srec->msg[t]->flags;
  1661. dflags &= srec->msg[t]->flags;
  1662. }
  1663. if (aflags | dflags) {
  1664. flags_total[t]++;
  1665. stats();
  1666. svars->flags_pending[t]++;
  1667. fv = nfmalloc( sizeof(*fv) );
  1668. fv->aux = AUX;
  1669. fv->srec = srec;
  1670. fv->aflags = aflags;
  1671. fv->dflags = dflags;
  1672. svars->drv[t]->set_msg_flags( svars->ctx[t], srec->msg[t], srec->uid[t], aflags, dflags, flags_set, fv );
  1673. if (check_cancel( svars ))
  1674. goto out;
  1675. } else
  1676. flags_set_p2( svars, srec, t );
  1677. }
  1678. }
  1679. for (t = 0; t < 2; t++) {
  1680. svars->drv[t]->commit_cmds( svars->ctx[t] );
  1681. svars->state[t] |= ST_SENT_FLAGS;
  1682. msgs_flags_set( svars, t );
  1683. if (check_cancel( svars ))
  1684. goto out;
  1685. }
  1686. debug( "propagating new messages\n" );
  1687. if (UseFSync)
  1688. fdatasync( fileno( svars->jfp ) );
  1689. for (t = 0; t < 2; t++) {
  1690. svars->newuid[t] = svars->drv[t]->get_uidnext( svars->ctx[t] );
  1691. jFprintf( svars, "F %d %u\n", t, svars->newuid[t] );
  1692. svars->new_msgs[t] = svars->msgs[1-t];
  1693. msgs_copied( svars, t );
  1694. if (check_cancel( svars ))
  1695. goto out;
  1696. }
  1697. out:
  1698. sync_deref( svars );
  1699. }
  1700. static void
  1701. msg_copied( int sts, uint uid, copy_vars_t *vars )
  1702. {
  1703. SVARS_CHECK_CANCEL_RET;
  1704. switch (sts) {
  1705. case SYNC_OK:
  1706. if (!uid) { // Stored to a non-UIDPLUS mailbox
  1707. svars->state[t] |= ST_FIND_NEW;
  1708. } else {
  1709. debug( " -> new UID %u on %s\n", uid, str_ms[t] );
  1710. jFprintf( svars, "%c %u %u %u\n", "<>"[t], vars->srec->uid[M], vars->srec->uid[S], uid );
  1711. vars->srec->uid[t] = uid;
  1712. vars->srec->status &= ~S_PENDING;
  1713. vars->srec->tuid[0] = 0;
  1714. }
  1715. break;
  1716. case SYNC_NOGOOD:
  1717. debug( " -> killing (%u,%u)\n", vars->srec->uid[M], vars->srec->uid[S] );
  1718. vars->srec->status = S_DEAD;
  1719. jFprintf( svars, "- %u %u\n", vars->srec->uid[M], vars->srec->uid[S] );
  1720. break;
  1721. default:
  1722. cancel_sync( svars );
  1723. free( vars );
  1724. return;
  1725. }
  1726. free( vars );
  1727. new_done[t]++;
  1728. stats();
  1729. svars->new_pending[t]--;
  1730. msgs_copied( svars, t );
  1731. }
  1732. static void msgs_found_new( int sts, message_t *msgs, void *aux );
  1733. static void msgs_new_done( sync_vars_t *svars, int t );
  1734. static void sync_close( sync_vars_t *svars, int t );
  1735. static void
  1736. msgs_copied( sync_vars_t *svars, int t )
  1737. {
  1738. message_t *tmsg;
  1739. sync_rec_t *srec;
  1740. copy_vars_t *cv;
  1741. if (svars->state[t] & ST_SENDING_NEW)
  1742. return;
  1743. sync_ref( svars );
  1744. if (!(svars->state[t] & ST_SENT_NEW)) {
  1745. for (tmsg = svars->new_msgs[t]; tmsg; tmsg = tmsg->next) {
  1746. if ((srec = tmsg->srec) && (srec->status & S_PENDING)) {
  1747. if (svars->drv[t]->get_memory_usage( svars->ctx[t] ) >= BufferLimit) {
  1748. svars->new_msgs[t] = tmsg;
  1749. goto out;
  1750. }
  1751. for (uint i = 0; i < TUIDL; i++) {
  1752. uchar c = arc4_getbyte() & 0x3f;
  1753. srec->tuid[i] = c < 26 ? c + 'A' : c < 52 ? c + 'a' - 26 : c < 62 ? c + '0' - 52 : c == 62 ? '+' : '/';
  1754. }
  1755. jFprintf( svars, "# %u %u %." stringify(TUIDL) "s\n", srec->uid[M], srec->uid[S], srec->tuid );
  1756. debug( "%sing message %u, TUID %." stringify(TUIDL) "s\n", str_hl[t], tmsg->uid, srec->tuid );
  1757. new_total[t]++;
  1758. stats();
  1759. svars->new_pending[t]++;
  1760. svars->state[t] |= ST_SENDING_NEW;
  1761. cv = nfmalloc( sizeof(*cv) );
  1762. cv->cb = msg_copied;
  1763. cv->aux = AUX;
  1764. cv->srec = srec;
  1765. cv->msg = tmsg;
  1766. copy_msg( cv );
  1767. svars->state[t] &= ~ST_SENDING_NEW;
  1768. if (check_cancel( svars ))
  1769. goto out;
  1770. }
  1771. }
  1772. svars->state[t] |= ST_SENT_NEW;
  1773. }
  1774. if (svars->new_pending[t])
  1775. goto out;
  1776. if (svars->maxuid[1-t] != svars->newmaxuid[1-t]) {
  1777. svars->maxuid[1-t] = svars->newmaxuid[1-t];
  1778. jFprintf( svars, "S %d\n", 1-t );
  1779. }
  1780. sync_close( svars, 1-t );
  1781. if (check_cancel( svars ))
  1782. goto out;
  1783. if (svars->state[t] & ST_FIND_NEW) {
  1784. debug( "finding just copied messages on %s\n", str_ms[t] );
  1785. svars->drv[t]->find_new_msgs( svars->ctx[t], svars->newuid[t], msgs_found_new, AUX );
  1786. } else {
  1787. msgs_new_done( svars, t );
  1788. }
  1789. out:
  1790. sync_deref( svars );
  1791. }
  1792. static void
  1793. msgs_found_new( int sts, message_t *msgs, void *aux )
  1794. {
  1795. SVARS_CHECK_RET;
  1796. switch (sts) {
  1797. case DRV_OK:
  1798. debug( "matching just copied messages on %s\n", str_ms[t] );
  1799. break;
  1800. default:
  1801. warn( "Warning: cannot find newly stored messages on %s.\n", str_ms[t] );
  1802. break;
  1803. }
  1804. match_tuids( svars, t, msgs );
  1805. msgs_new_done( svars, t );
  1806. }
  1807. static void
  1808. msgs_new_done( sync_vars_t *svars, int t )
  1809. {
  1810. svars->state[t] |= ST_FOUND_NEW;
  1811. sync_close( svars, t );
  1812. }
  1813. static void
  1814. flags_set( int sts, void *aux )
  1815. {
  1816. SVARS_CHECK_RET_VARS(flag_vars_t);
  1817. switch (sts) {
  1818. case DRV_OK:
  1819. if (vars->aflags & F_DELETED)
  1820. vars->srec->wstate |= W_DEL(t);
  1821. else if (vars->dflags & F_DELETED)
  1822. vars->srec->wstate &= ~W_DEL(t);
  1823. flags_set_p2( svars, vars->srec, t );
  1824. break;
  1825. }
  1826. free( vars );
  1827. flags_done[t]++;
  1828. stats();
  1829. svars->flags_pending[t]--;
  1830. msgs_flags_set( svars, t );
  1831. }
  1832. static void
  1833. flags_set_p2( sync_vars_t *svars, sync_rec_t *srec, int t )
  1834. {
  1835. if (srec->wstate & W_DELETE) {
  1836. debug( " pair(%u,%u): resetting %s UID\n", srec->uid[M], srec->uid[S], str_ms[1-t] );
  1837. jFprintf( svars, "%c %u %u 0\n", "><"[t], srec->uid[M], srec->uid[S] );
  1838. srec->uid[1-t] = 0;
  1839. } else {
  1840. uint nflags = (srec->flags | srec->aflags[t]) & ~srec->dflags[t];
  1841. if (srec->flags != nflags) {
  1842. debug( " pair(%u,%u): updating flags (%u -> %u; %sed)\n", srec->uid[M], srec->uid[S], srec->flags, nflags, str_hl[t] );
  1843. srec->flags = nflags;
  1844. jFprintf( svars, "* %u %u %u\n", srec->uid[M], srec->uid[S], nflags );
  1845. }
  1846. if (t == S) {
  1847. uint nex = (srec->wstate / W_NEXPIRE) & 1;
  1848. if (nex != ((srec->status / S_EXPIRED) & 1)) {
  1849. debug( " pair(%u,%u): expired %d (commit)\n", srec->uid[M], srec->uid[S], nex );
  1850. srec->status = (srec->status & ~S_EXPIRED) | (nex * S_EXPIRED);
  1851. jFprintf( svars, "~ %u %u %u\n", srec->uid[M], srec->uid[S], srec->status );
  1852. } else if (nex != ((srec->status / S_EXPIRE) & 1)) {
  1853. debug( " pair(%u,%u): expire %d (cancel)\n", srec->uid[M], srec->uid[S], nex );
  1854. srec->status = (srec->status & ~S_EXPIRE) | (nex * S_EXPIRE);
  1855. jFprintf( svars, "~ %u %u %u\n", srec->uid[M], srec->uid[S], srec->status );
  1856. }
  1857. }
  1858. }
  1859. }
  1860. typedef struct {
  1861. void *aux;
  1862. message_t *msg;
  1863. } trash_vars_t;
  1864. static void msg_trashed( int sts, void *aux );
  1865. static void msg_rtrashed( int sts, uint uid, copy_vars_t *vars );
  1866. static void
  1867. msgs_flags_set( sync_vars_t *svars, int t )
  1868. {
  1869. message_t *tmsg;
  1870. trash_vars_t *tv;
  1871. copy_vars_t *cv;
  1872. if (!(svars->state[t] & ST_SENT_FLAGS) || svars->flags_pending[t])
  1873. return;
  1874. sync_ref( svars );
  1875. if ((svars->chan->ops[t] & OP_EXPUNGE) &&
  1876. (svars->ctx[t]->conf->trash || (svars->ctx[1-t]->conf->trash && svars->ctx[1-t]->conf->trash_remote_new))) {
  1877. debug( "trashing in %s\n", str_ms[t] );
  1878. for (tmsg = svars->msgs[t]; tmsg; tmsg = tmsg->next)
  1879. if ((tmsg->flags & F_DELETED) && !find_uint_array( svars->trashed_msgs[t].array, tmsg->uid ) &&
  1880. (t == M || !tmsg->srec || !(tmsg->srec->status & (S_EXPIRE|S_EXPIRED)))) {
  1881. if (svars->ctx[t]->conf->trash) {
  1882. if (!svars->ctx[t]->conf->trash_only_new || !tmsg->srec || (tmsg->srec->status & (S_PENDING | S_SKIPPED))) {
  1883. debug( "%s: trashing message %u\n", str_ms[t], tmsg->uid );
  1884. trash_total[t]++;
  1885. stats();
  1886. svars->trash_pending[t]++;
  1887. tv = nfmalloc( sizeof(*tv) );
  1888. tv->aux = AUX;
  1889. tv->msg = tmsg;
  1890. svars->drv[t]->trash_msg( svars->ctx[t], tmsg, msg_trashed, tv );
  1891. if (check_cancel( svars ))
  1892. goto out;
  1893. } else
  1894. debug( "%s: not trashing message %u - not new\n", str_ms[t], tmsg->uid );
  1895. } else {
  1896. if (!tmsg->srec || (tmsg->srec->status & (S_PENDING | S_SKIPPED))) {
  1897. if (tmsg->size <= svars->ctx[1-t]->conf->max_size) {
  1898. debug( "%s: remote trashing message %u\n", str_ms[t], tmsg->uid );
  1899. trash_total[t]++;
  1900. stats();
  1901. svars->trash_pending[t]++;
  1902. cv = nfmalloc( sizeof(*cv) );
  1903. cv->cb = msg_rtrashed;
  1904. cv->aux = INV_AUX;
  1905. cv->srec = 0;
  1906. cv->msg = tmsg;
  1907. copy_msg( cv );
  1908. if (check_cancel( svars ))
  1909. goto out;
  1910. } else
  1911. debug( "%s: not remote trashing message %u - too big\n", str_ms[t], tmsg->uid );
  1912. } else
  1913. debug( "%s: not remote trashing message %u - not new\n", str_ms[t], tmsg->uid );
  1914. }
  1915. }
  1916. }
  1917. svars->state[t] |= ST_SENT_TRASH;
  1918. sync_close( svars, t );
  1919. out:
  1920. sync_deref( svars );
  1921. }
  1922. static void
  1923. msg_trashed( int sts, void *aux )
  1924. {
  1925. trash_vars_t *vars = (trash_vars_t *)aux;
  1926. DECL_SVARS;
  1927. if (sts == DRV_MSG_BAD)
  1928. sts = DRV_BOX_BAD;
  1929. if (check_ret( sts, vars->aux ))
  1930. return;
  1931. INIT_SVARS(vars->aux);
  1932. debug( " -> trashed %s %u\n", str_ms[t], vars->msg->uid );
  1933. jFprintf( svars, "T %d %u\n", t, vars->msg->uid );
  1934. free( vars );
  1935. trash_done[t]++;
  1936. stats();
  1937. svars->trash_pending[t]--;
  1938. sync_close( svars, t );
  1939. }
  1940. static void
  1941. msg_rtrashed( int sts, uint uid ATTR_UNUSED, copy_vars_t *vars )
  1942. {
  1943. SVARS_CHECK_CANCEL_RET;
  1944. switch (sts) {
  1945. case SYNC_OK:
  1946. case SYNC_NOGOOD: /* the message is gone or heavily busted */
  1947. break;
  1948. default:
  1949. cancel_sync( svars );
  1950. free( vars );
  1951. return;
  1952. }
  1953. t ^= 1;
  1954. debug( " -> remote trashed %s %u\n", str_ms[t], vars->msg->uid );
  1955. jFprintf( svars, "T %d %u\n", t, vars->msg->uid );
  1956. free( vars );
  1957. trash_done[t]++;
  1958. stats();
  1959. svars->trash_pending[t]--;
  1960. sync_close( svars, t );
  1961. }
  1962. static void box_closed( int sts, void *aux );
  1963. static void box_closed_p2( sync_vars_t *svars, int t );
  1964. static void
  1965. sync_close( sync_vars_t *svars, int t )
  1966. {
  1967. if ((~svars->state[t] & (ST_FOUND_NEW|ST_SENT_TRASH)) || svars->trash_pending[t] ||
  1968. !(svars->state[1-t] & ST_SENT_NEW) || svars->new_pending[1-t])
  1969. return;
  1970. if (svars->state[t] & ST_CLOSING)
  1971. return;
  1972. svars->state[t] |= ST_CLOSING;
  1973. if ((svars->chan->ops[t] & OP_EXPUNGE) /*&& !(svars->state[t] & ST_TRASH_BAD)*/) {
  1974. debug( "expunging %s\n", str_ms[t] );
  1975. svars->drv[t]->close_box( svars->ctx[t], box_closed, AUX );
  1976. } else {
  1977. box_closed_p2( svars, t );
  1978. }
  1979. }
  1980. static void
  1981. box_closed( int sts, void *aux )
  1982. {
  1983. SVARS_CHECK_RET;
  1984. svars->state[t] |= ST_DID_EXPUNGE;
  1985. box_closed_p2( svars, t );
  1986. }
  1987. static void
  1988. box_closed_p2( sync_vars_t *svars, int t )
  1989. {
  1990. sync_rec_t *srec;
  1991. svars->state[t] |= ST_CLOSED;
  1992. if (!(svars->state[1-t] & ST_CLOSED))
  1993. return;
  1994. // All the journalling done in this function is merely for the autotest -
  1995. // the operations are idempotent, and we're about to commit the new state
  1996. // right afterwards anyway.
  1997. if (((svars->state[M] | svars->state[S]) & ST_DID_EXPUNGE) || svars->chan->max_messages) {
  1998. debug( "purging obsolete entries\n" );
  1999. for (srec = svars->srecs; srec; srec = srec->next) {
  2000. if (srec->status & S_DEAD)
  2001. continue;
  2002. if (!srec->uid[S] || ((srec->wstate & W_DEL(S)) && (svars->state[S] & ST_DID_EXPUNGE))) {
  2003. if (!srec->uid[M] || ((srec->wstate & W_DEL(M)) && (svars->state[M] & ST_DID_EXPUNGE)) ||
  2004. ((srec->status & S_EXPIRED) && svars->maxuid[M] >= srec->uid[M] && svars->mmaxxuid >= srec->uid[M])) {
  2005. debug( " -> killing (%u,%u)\n", srec->uid[M], srec->uid[S] );
  2006. jFprintf( svars, "- %u %u\n", srec->uid[M], srec->uid[S] );
  2007. srec->status = S_DEAD;
  2008. } else if (srec->uid[S]) {
  2009. debug( " -> orphaning (%u,[%u])\n", srec->uid[M], srec->uid[S] );
  2010. jFprintf( svars, "> %u %u 0\n", srec->uid[M], srec->uid[S] );
  2011. srec->uid[S] = 0;
  2012. }
  2013. } else if (srec->uid[M] && ((srec->wstate & W_DEL(M)) && (svars->state[M] & ST_DID_EXPUNGE))) {
  2014. debug( " -> orphaning ([%u],%u)\n", srec->uid[M], srec->uid[S] );
  2015. jFprintf( svars, "< %u %u 0\n", srec->uid[M], srec->uid[S] );
  2016. srec->uid[M] = 0;
  2017. }
  2018. }
  2019. }
  2020. // This is just an optimization, so it needs no journaling of intermediate states.
  2021. // However, doing it before the entry purge would require ensuring that the
  2022. // exception list includes all relevant messages.
  2023. debug( "max expired uid on master is now %d\n", svars->mmaxxuid );
  2024. jFprintf( svars, "! %d\n", svars->mmaxxuid );
  2025. save_state( svars );
  2026. sync_bail( svars );
  2027. }
  2028. static void
  2029. sync_bail( sync_vars_t *svars )
  2030. {
  2031. sync_rec_t *srec, *nsrec;
  2032. free( svars->trashed_msgs[M].array.data );
  2033. free( svars->trashed_msgs[S].array.data );
  2034. for (srec = svars->srecs; srec; srec = nsrec) {
  2035. nsrec = srec->next;
  2036. free( srec );
  2037. }
  2038. if (svars->lfd >= 0) {
  2039. unlink( svars->lname );
  2040. close( svars->lfd );
  2041. }
  2042. sync_bail2( svars );
  2043. }
  2044. static void
  2045. sync_bail2( sync_vars_t *svars )
  2046. {
  2047. free( svars->lname );
  2048. free( svars->nname );
  2049. free( svars->jname );
  2050. free( svars->dname );
  2051. sync_bail3( svars );
  2052. }
  2053. static void
  2054. sync_bail3( sync_vars_t *svars )
  2055. {
  2056. free( svars->box_name[M] );
  2057. free( svars->box_name[S] );
  2058. sync_deref( svars );
  2059. }
  2060. static void
  2061. sync_deref( sync_vars_t *svars )
  2062. {
  2063. if (!--svars->ref_count) {
  2064. void (*cb)( int sts, void *aux ) = svars->cb;
  2065. void *aux = svars->aux;
  2066. int ret = svars->ret;
  2067. free( svars );
  2068. cb( ret, aux );
  2069. }
  2070. }