sync.c 65 KB

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