sync.c 61 KB

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