sync.c 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171
  1. /*
  2. * mbsync - mailbox synchronizer
  3. * Copyright (C) 2000-2002 Michael R. Elkins <me@mutt.org>
  4. * Copyright (C) 2002-2006,2010-2013 Oswald Buddenhagen <ossi@users.sf.net>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. *
  19. * As a special exception, mbsync may be linked with the OpenSSL library,
  20. * despite that library's more restrictive license.
  21. */
  22. #include "sync.h"
  23. #include <assert.h>
  24. #include <stdio.h>
  25. #include <limits.h>
  26. #include <stdlib.h>
  27. #include <stddef.h>
  28. #include <unistd.h>
  29. #include <time.h>
  30. #include <fcntl.h>
  31. #include <ctype.h>
  32. #include <string.h>
  33. #include <errno.h>
  34. #include <sys/stat.h>
  35. #if !defined(_POSIX_SYNCHRONIZED_IO) || _POSIX_SYNCHRONIZED_IO <= 0
  36. # define fdatasync fsync
  37. #endif
  38. channel_conf_t global_conf;
  39. channel_conf_t *channels;
  40. group_conf_t *groups;
  41. const char *str_ms[] = { "master", "slave" }, *str_hl[] = { "push", "pull" };
  42. static void ATTR_PRINTFLIKE(1, 2)
  43. debug( const char *msg, ... )
  44. {
  45. va_list va;
  46. va_start( va, msg );
  47. vdebug( DEBUG_SYNC, msg, va );
  48. va_end( va );
  49. }
  50. static void ATTR_PRINTFLIKE(1, 2)
  51. debugn( const char *msg, ... )
  52. {
  53. va_list va;
  54. va_start( va, msg );
  55. vdebugn( DEBUG_SYNC, msg, va );
  56. va_end( va );
  57. }
  58. void
  59. Fclose( FILE *f, int safe )
  60. {
  61. if ((safe && (fflush( f ) || (UseFSync && fdatasync( fileno( f ) )))) || fclose( f ) == EOF) {
  62. sys_error( "Error: cannot close file" );
  63. exit( 1 );
  64. }
  65. }
  66. void
  67. Fprintf( FILE *f, const char *msg, ... )
  68. {
  69. int r;
  70. va_list va;
  71. va_start( va, msg );
  72. r = vfprintf( f, msg, va );
  73. va_end( va );
  74. if (r < 0) {
  75. sys_error( "Error: cannot write file" );
  76. exit( 1 );
  77. }
  78. }
  79. static const char Flags[] = { 'D', 'F', 'R', 'S', 'T' };
  80. static int
  81. parse_flags( const char *buf )
  82. {
  83. uint flags, i, d;
  84. for (flags = i = d = 0; i < as(Flags); i++)
  85. if (buf[d] == Flags[i]) {
  86. flags |= (1 << i);
  87. d++;
  88. }
  89. return flags;
  90. }
  91. static int
  92. make_flags( int flags, char *buf )
  93. {
  94. uint i, d;
  95. for (i = d = 0; i < as(Flags); i++)
  96. if (flags & (1 << i))
  97. buf[d++] = Flags[i];
  98. buf[d] = 0;
  99. return d;
  100. }
  101. #define S_DEAD (1<<0) /* ephemeral: the entry was killed and should be ignored */
  102. #define S_DEL(ms) (1<<(2+(ms))) /* ephemeral: m/s message would be subject to expunge */
  103. #define S_EXPIRED (1<<4) /* the entry is expired (slave message removal confirmed) */
  104. #define S_EXPIRE (1<<5) /* the entry is being expired (slave message removal scheduled) */
  105. #define S_NEXPIRE (1<<6) /* temporary: new expiration state */
  106. #define S_DELETE (1<<7) /* ephemeral: flags propagation is a deletion */
  107. typedef struct sync_rec {
  108. struct sync_rec *next;
  109. /* string_list_t *keywords; */
  110. int uid[2]; /* -2 = pending (use tuid), -1 = skipped (too big), 0 = expired */
  111. message_t *msg[2];
  112. uchar status, flags, aflags[2], dflags[2];
  113. char tuid[TUIDL];
  114. } sync_rec_t;
  115. /* cases:
  116. a) both non-null
  117. b) only master null
  118. b.1) uid[M] 0
  119. b.2) uid[M] -1
  120. b.3) master not scanned
  121. b.4) master gone
  122. c) only slave null
  123. c.1) uid[S] 0
  124. c.2) uid[S] -1
  125. c.3) slave not scanned
  126. c.4) slave gone
  127. d) both null
  128. d.1) both gone
  129. d.2) uid[M] 0, slave not scanned
  130. d.3) uid[M] -1, slave not scanned
  131. d.4) master gone, slave not scanned
  132. d.5) uid[M] 0, slave gone
  133. d.6) uid[M] -1, slave gone
  134. d.7) uid[S] 0, master not scanned
  135. d.8) uid[S] -1, master not scanned
  136. d.9) slave gone, master not scanned
  137. d.10) uid[S] 0, master gone
  138. d.11) uid[S] -1, master gone
  139. impossible cases: both uid[M] & uid[S] 0 or -1, both not scanned
  140. */
  141. typedef struct {
  142. int t[2];
  143. void (*cb)( int sts, void *aux ), *aux;
  144. char *dname, *jname, *nname, *lname, *box_name[2];
  145. FILE *jfp, *nfp;
  146. sync_rec_t *srecs, **srecadd;
  147. channel_conf_t *chan;
  148. store_t *ctx[2];
  149. driver_t *drv[2];
  150. const char *orig_name[2];
  151. message_t *new_msgs[2];
  152. int_array_alloc_t trashed_msgs[2];
  153. int state[2], ref_count, nsrecs, ret, lfd, existing, replayed;
  154. int new_pending[2], flags_pending[2], trash_pending[2];
  155. int maxuid[2]; /* highest UID that was already propagated */
  156. int newmaxuid[2]; /* highest UID that is currently being propagated */
  157. int uidval[2]; /* UID validity value */
  158. int newuid[2]; /* TUID lookup makes sense only for UIDs >= this */
  159. int mmaxxuid; /* highest expired UID on master during new message propagation */
  160. int smaxxuid; /* highest expired UID on slave */
  161. } sync_vars_t;
  162. static void sync_ref( sync_vars_t *svars ) { ++svars->ref_count; }
  163. static void sync_deref( sync_vars_t *svars );
  164. static int check_cancel( sync_vars_t *svars );
  165. #define AUX &svars->t[t]
  166. #define INV_AUX &svars->t[1-t]
  167. #define DECL_SVARS \
  168. int t; \
  169. sync_vars_t *svars
  170. #define INIT_SVARS(aux) \
  171. t = *(int *)aux; \
  172. svars = (sync_vars_t *)(((char *)(&((int *)aux)[-t])) - offsetof(sync_vars_t, t))
  173. #define DECL_INIT_SVARS(aux) \
  174. int t = *(int *)aux; \
  175. sync_vars_t *svars = (sync_vars_t *)(((char *)(&((int *)aux)[-t])) - offsetof(sync_vars_t, t))
  176. /* operation dependencies:
  177. select(x): -
  178. load(x): select(x)
  179. new(M), new(S), flags(M), flags(S): load(M) & load(S)
  180. find_new(x): new(x)
  181. trash(x): flags(x)
  182. close(x): trash(x) & find_new(x) & new(!x) // with expunge
  183. cleanup: close(M) & close(S)
  184. */
  185. #define ST_LOADED (1<<0)
  186. #define ST_FIND_OLD (1<<1)
  187. #define ST_SENT_NEW (1<<2)
  188. #define ST_FIND_NEW (1<<3)
  189. #define ST_FOUND_NEW (1<<4)
  190. #define ST_SENT_FLAGS (1<<5)
  191. #define ST_SENT_TRASH (1<<6)
  192. #define ST_CLOSED (1<<7)
  193. #define ST_SENT_CANCEL (1<<8)
  194. #define ST_CANCELED (1<<9)
  195. #define ST_SELECTED (1<<10)
  196. #define ST_DID_EXPUNGE (1<<11)
  197. #define ST_CLOSING (1<<12)
  198. #define ST_CONFIRMED (1<<13)
  199. #define ST_PRESENT (1<<14)
  200. #define ST_SENDING_NEW (1<<15)
  201. static void
  202. match_tuids( sync_vars_t *svars, int t )
  203. {
  204. sync_rec_t *srec;
  205. message_t *tmsg, *ntmsg = 0;
  206. const char *diag;
  207. int num_lost = 0;
  208. for (srec = svars->srecs; srec; srec = srec->next) {
  209. if (srec->status & S_DEAD)
  210. continue;
  211. if (srec->uid[t] == -2 && srec->tuid[0]) {
  212. debug( " pair(%d,%d): lookup %s, TUID %." stringify(TUIDL) "s\n", srec->uid[M], srec->uid[S], str_ms[t], srec->tuid );
  213. for (tmsg = ntmsg; tmsg; tmsg = tmsg->next) {
  214. if (tmsg->status & M_DEAD)
  215. continue;
  216. if (tmsg->tuid[0] && !memcmp( tmsg->tuid, srec->tuid, TUIDL )) {
  217. diag = (tmsg == ntmsg) ? "adjacently" : "after gap";
  218. goto mfound;
  219. }
  220. }
  221. for (tmsg = svars->ctx[t]->msgs; tmsg != ntmsg; tmsg = tmsg->next) {
  222. if (tmsg->status & M_DEAD)
  223. continue;
  224. if (tmsg->tuid[0] && !memcmp( tmsg->tuid, srec->tuid, TUIDL )) {
  225. diag = "after reset";
  226. goto mfound;
  227. }
  228. }
  229. debug( " -> TUID lost\n" );
  230. Fprintf( svars->jfp, "& %d %d\n", srec->uid[M], srec->uid[S] );
  231. srec->flags = 0;
  232. srec->tuid[0] = 0;
  233. num_lost++;
  234. continue;
  235. mfound:
  236. debug( " -> new UID %d %s\n", tmsg->uid, diag );
  237. Fprintf( svars->jfp, "%c %d %d %d\n", "<>"[t], srec->uid[M], srec->uid[S], tmsg->uid );
  238. tmsg->srec = srec;
  239. srec->msg[t] = tmsg;
  240. ntmsg = tmsg->next;
  241. srec->uid[t] = tmsg->uid;
  242. srec->tuid[0] = 0;
  243. }
  244. }
  245. if (num_lost)
  246. warn( "Warning: lost track of %d %sed message(s)\n", num_lost, str_hl[t] );
  247. }
  248. typedef struct copy_vars {
  249. void (*cb)( int sts, int uid, struct copy_vars *vars );
  250. void *aux;
  251. sync_rec_t *srec; /* also ->tuid */
  252. message_t *msg;
  253. msg_data_t data;
  254. } copy_vars_t;
  255. static void msg_fetched( int sts, void *aux );
  256. static void
  257. copy_msg( copy_vars_t *vars )
  258. {
  259. DECL_INIT_SVARS(vars->aux);
  260. t ^= 1;
  261. vars->data.flags = vars->msg->flags;
  262. vars->data.date = svars->chan->use_internal_date ? -1 : 0;
  263. svars->drv[t]->fetch_msg( svars->ctx[t], vars->msg, &vars->data, msg_fetched, vars );
  264. }
  265. static void msg_stored( int sts, int uid, void *aux );
  266. static void
  267. copy_msg_bytes( char **out_ptr, const char *in_buf, int *in_idx, int in_len, int in_cr, int out_cr )
  268. {
  269. char *out = *out_ptr;
  270. int idx = *in_idx;
  271. if (out_cr != in_cr) {
  272. char c;
  273. if (out_cr) {
  274. for (; idx < in_len; idx++) {
  275. if ((c = in_buf[idx]) != '\r') {
  276. if (c == '\n')
  277. *out++ = '\r';
  278. *out++ = c;
  279. }
  280. }
  281. } else {
  282. for (; idx < in_len; idx++) {
  283. if ((c = in_buf[idx]) != '\r')
  284. *out++ = c;
  285. }
  286. }
  287. } else {
  288. memcpy( out, in_buf + idx, in_len - idx );
  289. out += in_len - idx;
  290. idx = in_len;
  291. }
  292. *out_ptr = out;
  293. *in_idx = idx;
  294. }
  295. static void
  296. msg_fetched( int sts, void *aux )
  297. {
  298. copy_vars_t *vars = (copy_vars_t *)aux;
  299. DECL_SVARS;
  300. char *fmap, *buf;
  301. int i, len, extra, scr, tcr, lcrs, hcrs, bcrs, lines;
  302. int start, sbreak = 0, ebreak = 0;
  303. char c;
  304. switch (sts) {
  305. case DRV_OK:
  306. INIT_SVARS(vars->aux);
  307. if (check_cancel( svars )) {
  308. free( vars->data.data );
  309. vars->cb( SYNC_CANCELED, 0, vars );
  310. return;
  311. }
  312. vars->msg->flags = vars->data.flags;
  313. scr = (svars->drv[1-t]->flags / DRV_CRLF) & 1;
  314. tcr = (svars->drv[t]->flags / DRV_CRLF) & 1;
  315. if (vars->srec || scr != tcr) {
  316. fmap = vars->data.data;
  317. len = vars->data.len;
  318. extra = lines = hcrs = bcrs = i = 0;
  319. if (vars->srec) {
  320. nloop:
  321. start = i;
  322. lcrs = 0;
  323. while (i < len) {
  324. c = fmap[i++];
  325. if (c == '\r')
  326. lcrs++;
  327. else if (c == '\n') {
  328. if (starts_with_upper( fmap + start, len - start, "X-TUID: ", 8 )) {
  329. extra = (sbreak = start) - (ebreak = i);
  330. goto oke;
  331. }
  332. lines++;
  333. hcrs += lcrs;
  334. if (i - lcrs - 1 == start) {
  335. sbreak = ebreak = start;
  336. goto oke;
  337. }
  338. goto nloop;
  339. }
  340. }
  341. /* invalid message */
  342. warn( "Warning: message %d from %s has incomplete header.\n",
  343. vars->msg->uid, str_ms[1-t] );
  344. free( fmap );
  345. vars->cb( SYNC_NOGOOD, 0, vars );
  346. return;
  347. oke:
  348. extra += 8 + TUIDL + 1 + (tcr && (!scr || hcrs));
  349. }
  350. if (tcr != scr) {
  351. for (; i < len; i++) {
  352. c = fmap[i];
  353. if (c == '\r')
  354. bcrs++;
  355. else if (c == '\n')
  356. lines++;
  357. }
  358. extra -= hcrs + bcrs;
  359. if (tcr)
  360. extra += lines;
  361. }
  362. vars->data.len = len + extra;
  363. buf = vars->data.data = nfmalloc( vars->data.len );
  364. i = 0;
  365. if (vars->srec) {
  366. copy_msg_bytes( &buf, fmap, &i, sbreak, scr, tcr );
  367. memcpy( buf, "X-TUID: ", 8 );
  368. buf += 8;
  369. memcpy( buf, vars->srec->tuid, TUIDL );
  370. buf += TUIDL;
  371. if (tcr && (!scr || hcrs))
  372. *buf++ = '\r';
  373. *buf++ = '\n';
  374. i = ebreak;
  375. }
  376. copy_msg_bytes( &buf, fmap, &i, len, scr, tcr );
  377. free( fmap );
  378. }
  379. svars->drv[t]->store_msg( svars->ctx[t], &vars->data, !vars->srec, msg_stored, vars );
  380. break;
  381. case DRV_CANCELED:
  382. vars->cb( SYNC_CANCELED, 0, vars );
  383. break;
  384. case DRV_MSG_BAD:
  385. vars->cb( SYNC_NOGOOD, 0, vars );
  386. break;
  387. default:
  388. vars->cb( SYNC_FAIL, 0, vars );
  389. break;
  390. }
  391. }
  392. static void
  393. msg_stored( int sts, int uid, void *aux )
  394. {
  395. copy_vars_t *vars = (copy_vars_t *)aux;
  396. DECL_SVARS;
  397. switch (sts) {
  398. case DRV_OK:
  399. vars->cb( SYNC_OK, uid, vars );
  400. break;
  401. case DRV_CANCELED:
  402. vars->cb( SYNC_CANCELED, 0, vars );
  403. break;
  404. case DRV_MSG_BAD:
  405. INIT_SVARS(vars->aux);
  406. (void)svars;
  407. warn( "Warning: %s refuses to store message %d from %s.\n",
  408. str_ms[t], vars->msg->uid, str_ms[1-t] );
  409. vars->cb( SYNC_NOGOOD, 0, vars );
  410. break;
  411. default:
  412. vars->cb( SYNC_FAIL, 0, vars );
  413. break;
  414. }
  415. }
  416. static void sync_bail( sync_vars_t *svars );
  417. static void sync_bail2( sync_vars_t *svars );
  418. static void sync_bail3( sync_vars_t *svars );
  419. static void cancel_done( void *aux );
  420. static void
  421. cancel_sync( sync_vars_t *svars )
  422. {
  423. int t;
  424. for (t = 0; t < 2; t++) {
  425. int other_state = svars->state[1-t];
  426. if (svars->ret & SYNC_BAD(t)) {
  427. cancel_done( AUX );
  428. } else if (!(svars->state[t] & ST_SENT_CANCEL)) {
  429. /* ignore subsequent failures from in-flight commands */
  430. svars->state[t] |= ST_SENT_CANCEL;
  431. svars->drv[t]->cancel_cmds( svars->ctx[t], cancel_done, AUX );
  432. }
  433. if (other_state & ST_CANCELED)
  434. break;
  435. }
  436. }
  437. static void
  438. cancel_done( void *aux )
  439. {
  440. DECL_INIT_SVARS(aux);
  441. svars->state[t] |= ST_CANCELED;
  442. if (svars->state[1-t] & ST_CANCELED) {
  443. if (svars->nfp) {
  444. Fclose( svars->nfp, 0 );
  445. Fclose( svars->jfp, 0 );
  446. }
  447. sync_bail( svars );
  448. }
  449. }
  450. static void
  451. store_bad( void *aux )
  452. {
  453. DECL_INIT_SVARS(aux);
  454. svars->drv[t]->cancel_store( svars->ctx[t] );
  455. svars->ret |= SYNC_BAD(t);
  456. cancel_sync( svars );
  457. }
  458. static int
  459. check_cancel( sync_vars_t *svars )
  460. {
  461. return (svars->state[M] | svars->state[S]) & (ST_SENT_CANCEL | ST_CANCELED);
  462. }
  463. static int
  464. check_ret( int sts, void *aux )
  465. {
  466. DECL_SVARS;
  467. if (sts == DRV_CANCELED)
  468. return 1;
  469. INIT_SVARS(aux);
  470. if (sts == DRV_BOX_BAD) {
  471. svars->ret |= SYNC_FAIL;
  472. cancel_sync( svars );
  473. return 1;
  474. }
  475. return check_cancel( svars );
  476. }
  477. #define SVARS_CHECK_RET \
  478. DECL_SVARS; \
  479. if (check_ret( sts, aux )) \
  480. return; \
  481. INIT_SVARS(aux)
  482. #define SVARS_CHECK_RET_VARS(type) \
  483. type *vars = (type *)aux; \
  484. DECL_SVARS; \
  485. if (check_ret( sts, vars->aux )) { \
  486. free( vars ); \
  487. return; \
  488. } \
  489. INIT_SVARS(vars->aux)
  490. #define SVARS_CHECK_CANCEL_RET \
  491. DECL_SVARS; \
  492. if (sts == SYNC_CANCELED) { \
  493. free( vars ); \
  494. return; \
  495. } \
  496. INIT_SVARS(vars->aux)
  497. static char *
  498. clean_strdup( const char *s )
  499. {
  500. char *cs;
  501. int i;
  502. cs = nfstrdup( s );
  503. for (i = 0; cs[i]; i++)
  504. if (cs[i] == '/')
  505. cs[i] = '!';
  506. return cs;
  507. }
  508. #define JOURNAL_VERSION "2"
  509. static int
  510. prepare_state( sync_vars_t *svars )
  511. {
  512. char *s, *cmname, *csname;
  513. channel_conf_t *chan;
  514. chan = svars->chan;
  515. if (!strcmp( chan->sync_state ? chan->sync_state : global_conf.sync_state, "*" )) {
  516. if (!svars->ctx[S]->path) {
  517. error( "Error: store '%s' does not support in-box sync state\n", chan->stores[S]->name );
  518. return 0;
  519. }
  520. nfasprintf( &svars->dname, "%s/." EXE "state", svars->ctx[S]->path );
  521. } else {
  522. csname = clean_strdup( svars->box_name[S] );
  523. if (chan->sync_state)
  524. nfasprintf( &svars->dname, "%s%s", chan->sync_state, csname );
  525. else {
  526. char c = FieldDelimiter;
  527. cmname = clean_strdup( svars->box_name[M] );
  528. nfasprintf( &svars->dname, "%s%c%s%c%s_%c%s%c%s", global_conf.sync_state,
  529. c, chan->stores[M]->name, c, cmname, c, chan->stores[S]->name, c, csname );
  530. free( cmname );
  531. }
  532. free( csname );
  533. if (!(s = strrchr( svars->dname, '/' ))) {
  534. error( "Error: invalid SyncState location '%s'\n", svars->dname );
  535. return 0;
  536. }
  537. *s = 0;
  538. if (mkdir( svars->dname, 0700 ) && errno != EEXIST) {
  539. sys_error( "Error: cannot create SyncState directory '%s'", svars->dname );
  540. return 0;
  541. }
  542. *s = '/';
  543. }
  544. nfasprintf( &svars->jname, "%s.journal", svars->dname );
  545. nfasprintf( &svars->nname, "%s.new", svars->dname );
  546. nfasprintf( &svars->lname, "%s.lock", svars->dname );
  547. return 1;
  548. }
  549. static int
  550. lock_state( sync_vars_t *svars )
  551. {
  552. struct flock lck;
  553. if (svars->lfd >= 0)
  554. return 1;
  555. memset( &lck, 0, sizeof(lck) );
  556. #if SEEK_SET != 0
  557. lck.l_whence = SEEK_SET;
  558. #endif
  559. #if F_WRLCK != 0
  560. lck.l_type = F_WRLCK;
  561. #endif
  562. if ((svars->lfd = open( svars->lname, O_WRONLY|O_CREAT, 0666 )) < 0) {
  563. sys_error( "Error: cannot create lock file %s", svars->lname );
  564. return 0;
  565. }
  566. if (fcntl( svars->lfd, F_SETLK, &lck )) {
  567. error( "Error: channel :%s:%s-:%s:%s is locked\n",
  568. svars->chan->stores[M]->name, svars->orig_name[M], svars->chan->stores[S]->name, svars->orig_name[S] );
  569. close( svars->lfd );
  570. svars->lfd = -1;
  571. return 0;
  572. }
  573. return 1;
  574. }
  575. static void
  576. save_state( sync_vars_t *svars )
  577. {
  578. sync_rec_t *srec;
  579. char fbuf[16]; /* enlarge when support for keywords is added */
  580. Fprintf( svars->nfp,
  581. "MasterUidValidity %d\nSlaveUidValidity %d\nMaxPulledUid %d\nMaxPushedUid %d\n",
  582. svars->uidval[M], svars->uidval[S], svars->maxuid[M], svars->maxuid[S] );
  583. if (svars->smaxxuid)
  584. Fprintf( svars->nfp, "MaxExpiredSlaveUid %d\n", svars->smaxxuid );
  585. Fprintf( svars->nfp, "\n" );
  586. for (srec = svars->srecs; srec; srec = srec->next) {
  587. if (srec->status & S_DEAD)
  588. continue;
  589. make_flags( srec->flags, fbuf );
  590. Fprintf( svars->nfp, "%d %d %s%s\n", srec->uid[M], srec->uid[S],
  591. srec->status & S_EXPIRED ? "X" : "", fbuf );
  592. }
  593. Fclose( svars->nfp, 1 );
  594. Fclose( svars->jfp, 0 );
  595. if (!(DFlags & KEEPJOURNAL)) {
  596. /* order is important! */
  597. if (rename( svars->nname, svars->dname ))
  598. warn( "Warning: cannot commit sync state %s\n", svars->dname );
  599. else if (unlink( svars->jname ))
  600. warn( "Warning: cannot delete journal %s\n", svars->jname );
  601. }
  602. }
  603. static int
  604. load_state( sync_vars_t *svars )
  605. {
  606. sync_rec_t *srec, *nsrec;
  607. char *s;
  608. FILE *jfp;
  609. int line, t, t1, t2, t3;
  610. char c;
  611. struct stat st;
  612. char fbuf[16]; /* enlarge when support for keywords is added */
  613. char buf[128], buf1[64], buf2[64];
  614. if ((jfp = fopen( svars->dname, "r" ))) {
  615. if (!lock_state( svars ))
  616. goto jbail;
  617. debug( "reading sync state %s ...\n", svars->dname );
  618. line = 0;
  619. while (fgets( buf, sizeof(buf), jfp )) {
  620. line++;
  621. if (!(t = strlen( buf )) || buf[t - 1] != '\n') {
  622. error( "Error: incomplete sync state header entry at %s:%d\n", svars->dname, line );
  623. jbail:
  624. fclose( jfp );
  625. return 0;
  626. }
  627. if (t == 1)
  628. goto gothdr;
  629. if (line == 1 && isdigit( buf[0] )) {
  630. if (sscanf( buf, "%63s %63s", buf1, buf2 ) != 2 ||
  631. sscanf( buf1, "%d:%d", &svars->uidval[M], &svars->maxuid[M] ) < 2 ||
  632. sscanf( buf2, "%d:%d:%d", &svars->uidval[S], &svars->smaxxuid, &svars->maxuid[S] ) < 3) {
  633. error( "Error: invalid sync state header in %s\n", svars->dname );
  634. goto jbail;
  635. }
  636. goto gothdr;
  637. }
  638. if (sscanf( buf, "%63s %d", buf1, &t1 ) != 2) {
  639. error( "Error: malformed sync state header entry at %s:%d\n", svars->dname, line );
  640. goto jbail;
  641. }
  642. if (!strcmp( buf1, "MasterUidValidity" ))
  643. svars->uidval[M] = t1;
  644. else if (!strcmp( buf1, "SlaveUidValidity" ))
  645. svars->uidval[S] = t1;
  646. else if (!strcmp( buf1, "MaxPulledUid" ))
  647. svars->maxuid[M] = t1;
  648. else if (!strcmp( buf1, "MaxPushedUid" ))
  649. svars->maxuid[S] = t1;
  650. else if (!strcmp( buf1, "MaxExpiredSlaveUid" ))
  651. svars->smaxxuid = t1;
  652. else {
  653. error( "Error: unrecognized sync state header entry at %s:%d\n", svars->dname, line );
  654. goto jbail;
  655. }
  656. }
  657. error( "Error: unterminated sync state header in %s\n", svars->dname );
  658. goto jbail;
  659. gothdr:
  660. while (fgets( buf, sizeof(buf), jfp )) {
  661. line++;
  662. if (!(t = strlen( buf )) || buf[--t] != '\n') {
  663. error( "Error: incomplete sync state entry at %s:%d\n", svars->dname, line );
  664. goto jbail;
  665. }
  666. buf[t] = 0;
  667. fbuf[0] = 0;
  668. if (sscanf( buf, "%d %d %15s", &t1, &t2, fbuf ) < 2) {
  669. error( "Error: invalid sync state entry at %s:%d\n", svars->dname, line );
  670. goto jbail;
  671. }
  672. srec = nfmalloc( sizeof(*srec) );
  673. srec->uid[M] = t1;
  674. srec->uid[S] = t2;
  675. s = fbuf;
  676. if (*s == 'X') {
  677. s++;
  678. srec->status = S_EXPIRE | S_EXPIRED;
  679. } else
  680. srec->status = 0;
  681. srec->flags = parse_flags( s );
  682. debug( " entry (%d,%d,%u,%s)\n", srec->uid[M], srec->uid[S], srec->flags, srec->status & S_EXPIRED ? "X" : "" );
  683. srec->msg[M] = srec->msg[S] = 0;
  684. srec->tuid[0] = 0;
  685. srec->next = 0;
  686. *svars->srecadd = srec;
  687. svars->srecadd = &srec->next;
  688. svars->nsrecs++;
  689. }
  690. fclose( jfp );
  691. svars->existing = 1;
  692. } else {
  693. if (errno != ENOENT) {
  694. sys_error( "Error: cannot read sync state %s", svars->dname );
  695. return 0;
  696. }
  697. svars->existing = 0;
  698. }
  699. svars->newmaxuid[M] = svars->maxuid[M];
  700. svars->newmaxuid[S] = svars->maxuid[S];
  701. svars->mmaxxuid = INT_MAX;
  702. line = 0;
  703. if ((jfp = fopen( svars->jname, "r" ))) {
  704. if (!lock_state( svars ))
  705. goto jbail;
  706. if (!stat( svars->nname, &st ) && fgets( buf, sizeof(buf), jfp )) {
  707. debug( "recovering journal ...\n" );
  708. if (!(t = strlen( buf )) || buf[--t] != '\n') {
  709. error( "Error: incomplete journal header in %s\n", svars->jname );
  710. goto jbail;
  711. }
  712. buf[t] = 0;
  713. if (!equals( buf, t, JOURNAL_VERSION, strlen(JOURNAL_VERSION) )) {
  714. error( "Error: incompatible journal version "
  715. "(got %s, expected " JOURNAL_VERSION ")\n", buf );
  716. goto jbail;
  717. }
  718. srec = 0;
  719. line = 1;
  720. while (fgets( buf, sizeof(buf), jfp )) {
  721. line++;
  722. if (!(t = strlen( buf )) || buf[--t] != '\n') {
  723. error( "Error: incomplete journal entry at %s:%d\n", svars->jname, line );
  724. goto jbail;
  725. }
  726. buf[t] = 0;
  727. if ((c = buf[0]) == '#' ?
  728. (t3 = 0, (sscanf( buf + 2, "%d %d %n", &t1, &t2, &t3 ) < 2) || !t3 || (t - t3 != TUIDL + 2)) :
  729. c == '(' || c == ')' || c == '{' || c == '}' || c == '[' || c == ']' || c == '!' ?
  730. (sscanf( buf + 2, "%d", &t1 ) != 1) :
  731. c == '+' || c == '&' || c == '-' || c == '|' || c == '/' || c == '\\' ?
  732. (sscanf( buf + 2, "%d %d", &t1, &t2 ) != 2) :
  733. (sscanf( buf + 2, "%d %d %d", &t1, &t2, &t3 ) != 3))
  734. {
  735. error( "Error: malformed journal entry at %s:%d\n", svars->jname, line );
  736. goto jbail;
  737. }
  738. if (c == '(')
  739. svars->maxuid[M] = t1;
  740. else if (c == ')')
  741. svars->maxuid[S] = t1;
  742. else if (c == '{')
  743. svars->newuid[M] = t1;
  744. else if (c == '}')
  745. svars->newuid[S] = t1;
  746. else if (c == '[')
  747. *int_array_append( &svars->trashed_msgs[M] ) = t1;
  748. else if (c == ']')
  749. *int_array_append( &svars->trashed_msgs[S] ) = t1;
  750. else if (c == '!')
  751. svars->smaxxuid = t1;
  752. else if (c == '|') {
  753. svars->uidval[M] = t1;
  754. svars->uidval[S] = t2;
  755. } else if (c == '+') {
  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 (c) {
  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. memcpy( srec->tuid, buf + t3 + 2, TUIDL );
  792. debug( "TUID now %." stringify(TUIDL) "s\n", srec->tuid );
  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_array_t mexcs );
  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. bail3:
  898. svars->ret = SYNC_FAIL;
  899. sync_bail3( svars );
  900. return;
  901. }
  902. ctx[t]->uidvalidity = -1;
  903. set_bad_callback( ctx[t], store_bad, AUX );
  904. svars->drv[t] = ctx[t]->conf->driver;
  905. }
  906. /* Both boxes must be fully set up at this point, so that error exit paths
  907. * don't run into uninitialized variables. */
  908. for (t = 0; t < 2; t++) {
  909. switch (svars->drv[t]->select_box( ctx[t], svars->box_name[t] )) {
  910. case DRV_CANCELED:
  911. store_bad( AUX );
  912. return;
  913. case DRV_BOX_BAD:
  914. goto bail3;
  915. }
  916. }
  917. if (!prepare_state( svars )) {
  918. svars->ret = SYNC_FAIL;
  919. sync_bail2( svars );
  920. return;
  921. }
  922. if (!load_state( svars )) {
  923. svars->ret = SYNC_FAIL;
  924. sync_bail( svars );
  925. return;
  926. }
  927. sync_ref( svars );
  928. for (t = 0; ; t++) {
  929. info( "Opening %s box %s...\n", str_ms[t], svars->orig_name[t] );
  930. if (present[t] == BOX_ABSENT)
  931. box_confirmed2( svars, t );
  932. else
  933. svars->drv[t]->open_box( ctx[t], box_confirmed, AUX );
  934. if (t || check_cancel( svars ))
  935. break;
  936. }
  937. sync_deref( svars );
  938. }
  939. static void
  940. box_confirmed( int sts, void *aux )
  941. {
  942. DECL_SVARS;
  943. if (sts == DRV_CANCELED)
  944. return;
  945. INIT_SVARS(aux);
  946. if (check_cancel( svars ))
  947. return;
  948. if (sts == DRV_OK)
  949. svars->state[t] |= ST_PRESENT;
  950. box_confirmed2( svars, t );
  951. }
  952. static void
  953. box_confirmed2( sync_vars_t *svars, int t )
  954. {
  955. svars->state[t] |= ST_CONFIRMED;
  956. if (!(svars->state[1-t] & ST_CONFIRMED))
  957. return;
  958. sync_ref( svars );
  959. for (t = 0; ; t++) {
  960. if (!(svars->state[t] & ST_PRESENT)) {
  961. if (!(svars->state[1-t] & ST_PRESENT)) {
  962. if (!svars->existing) {
  963. error( "Error: channel %s: both master %s and slave %s cannot be opened.\n",
  964. svars->chan->name, svars->orig_name[M], svars->orig_name[S] );
  965. bail:
  966. svars->ret = SYNC_FAIL;
  967. } else {
  968. /* This can legitimately happen if a deletion propagation was interrupted.
  969. * We have no place to record this transaction, so we just assume it.
  970. * Of course this bears the danger of clearing the state if both mailboxes
  971. * temorarily cannot be opened for some weird reason (while the stores can). */
  972. delete_state( svars );
  973. }
  974. done:
  975. sync_bail( svars );
  976. break;
  977. }
  978. if (svars->existing) {
  979. if (!(svars->chan->ops[1-t] & OP_REMOVE)) {
  980. error( "Error: channel %s: %s %s cannot be opened.\n",
  981. svars->chan->name, str_ms[t], svars->orig_name[t] );
  982. goto bail;
  983. }
  984. if (svars->drv[1-t]->confirm_box_empty( svars->ctx[1-t] ) != DRV_OK) {
  985. warn( "Warning: channel %s: %s %s cannot be opened and %s %s not empty.\n",
  986. svars->chan->name, str_ms[t], svars->orig_name[t], str_ms[1-t], svars->orig_name[1-t] );
  987. goto done;
  988. }
  989. info( "Deleting %s %s...\n", str_ms[1-t], svars->orig_name[1-t] );
  990. svars->drv[1-t]->delete_box( svars->ctx[1-t], box_deleted, INV_AUX );
  991. } else {
  992. if (!(svars->chan->ops[t] & OP_CREATE)) {
  993. box_opened( DRV_BOX_BAD, AUX );
  994. } else {
  995. info( "Creating %s %s...\n", str_ms[t], svars->orig_name[t] );
  996. svars->drv[t]->create_box( svars->ctx[t], box_created, AUX );
  997. }
  998. }
  999. } else {
  1000. box_opened2( svars, t );
  1001. }
  1002. if (t || check_cancel( svars ))
  1003. break;
  1004. }
  1005. sync_deref( svars );
  1006. }
  1007. static void
  1008. box_deleted( int sts, void *aux )
  1009. {
  1010. DECL_SVARS;
  1011. if (check_ret( sts, aux ))
  1012. return;
  1013. INIT_SVARS(aux);
  1014. delete_state( svars );
  1015. svars->drv[t]->finish_delete_box( svars->ctx[t] );
  1016. sync_bail( svars );
  1017. }
  1018. static void
  1019. box_created( int sts, void *aux )
  1020. {
  1021. DECL_SVARS;
  1022. if (check_ret( sts, aux ))
  1023. return;
  1024. INIT_SVARS(aux);
  1025. svars->drv[t]->open_box( svars->ctx[t], box_opened, AUX );
  1026. }
  1027. static void
  1028. box_opened( int sts, void *aux )
  1029. {
  1030. DECL_SVARS;
  1031. if (sts == DRV_CANCELED)
  1032. return;
  1033. INIT_SVARS(aux);
  1034. if (check_cancel( svars ))
  1035. return;
  1036. if (sts == DRV_BOX_BAD) {
  1037. error( "Error: channel %s: %s %s cannot be opened.\n",
  1038. svars->chan->name, str_ms[t], svars->orig_name[t] );
  1039. svars->ret = SYNC_FAIL;
  1040. sync_bail( svars );
  1041. } else {
  1042. box_opened2( svars, t );
  1043. }
  1044. }
  1045. static void
  1046. box_opened2( sync_vars_t *svars, int t )
  1047. {
  1048. store_t *ctx[2];
  1049. channel_conf_t *chan;
  1050. sync_rec_t *srec;
  1051. int_array_alloc_t mexcs;
  1052. int opts[2], fails, minwuid;
  1053. svars->state[t] |= ST_SELECTED;
  1054. if (!(svars->state[1-t] & ST_SELECTED))
  1055. return;
  1056. ctx[0] = svars->ctx[0];
  1057. ctx[1] = svars->ctx[1];
  1058. chan = svars->chan;
  1059. fails = 0;
  1060. for (t = 0; t < 2; t++)
  1061. if (svars->uidval[t] >= 0 && svars->uidval[t] != ctx[t]->uidvalidity) {
  1062. error( "Error: UIDVALIDITY of %s changed (got %d, expected %d)\n",
  1063. str_ms[t], ctx[t]->uidvalidity, svars->uidval[t] );
  1064. fails++;
  1065. }
  1066. if (fails) {
  1067. bail:
  1068. svars->ret = SYNC_FAIL;
  1069. sync_bail( svars );
  1070. return;
  1071. }
  1072. if (!lock_state( svars ))
  1073. goto bail;
  1074. if (!(svars->nfp = fopen( svars->nname, "w" ))) {
  1075. sys_error( "Error: cannot create new sync state %s", svars->nname );
  1076. goto bail;
  1077. }
  1078. if (!(svars->jfp = fopen( svars->jname, "a" ))) {
  1079. sys_error( "Error: cannot create journal %s", svars->jname );
  1080. fclose( svars->nfp );
  1081. goto bail;
  1082. }
  1083. setlinebuf( svars->jfp );
  1084. if (!svars->replayed)
  1085. Fprintf( svars->jfp, JOURNAL_VERSION "\n" );
  1086. opts[M] = opts[S] = 0;
  1087. for (t = 0; t < 2; t++) {
  1088. if (chan->ops[t] & (OP_DELETE|OP_FLAGS)) {
  1089. opts[t] |= OPEN_SETFLAGS;
  1090. opts[1-t] |= OPEN_OLD;
  1091. if (chan->ops[t] & OP_FLAGS)
  1092. opts[1-t] |= OPEN_FLAGS;
  1093. }
  1094. if (chan->ops[t] & (OP_NEW|OP_RENEW)) {
  1095. opts[t] |= OPEN_APPEND;
  1096. if (chan->ops[t] & OP_RENEW)
  1097. opts[1-t] |= OPEN_OLD;
  1098. if (chan->ops[t] & OP_NEW)
  1099. opts[1-t] |= OPEN_NEW;
  1100. if (chan->ops[t] & OP_EXPUNGE)
  1101. opts[1-t] |= OPEN_FLAGS;
  1102. if (chan->stores[t]->max_size != INT_MAX)
  1103. opts[1-t] |= OPEN_SIZE;
  1104. }
  1105. if (chan->ops[t] & OP_EXPUNGE) {
  1106. opts[t] |= OPEN_EXPUNGE;
  1107. if (chan->stores[t]->trash) {
  1108. if (!chan->stores[t]->trash_only_new)
  1109. opts[t] |= OPEN_OLD;
  1110. opts[t] |= OPEN_NEW|OPEN_FLAGS;
  1111. } else if (chan->stores[1-t]->trash && chan->stores[1-t]->trash_remote_new)
  1112. opts[t] |= OPEN_NEW|OPEN_FLAGS;
  1113. }
  1114. }
  1115. if ((chan->ops[S] & (OP_NEW|OP_RENEW|OP_FLAGS)) && chan->max_messages)
  1116. opts[S] |= OPEN_OLD|OPEN_NEW|OPEN_FLAGS;
  1117. if (svars->replayed)
  1118. for (srec = svars->srecs; srec; srec = srec->next) {
  1119. if (srec->status & S_DEAD)
  1120. continue;
  1121. if (srec->tuid[0]) {
  1122. if (srec->uid[M] == -2)
  1123. opts[M] |= OPEN_NEW|OPEN_FIND, svars->state[M] |= ST_FIND_OLD;
  1124. else if (srec->uid[S] == -2)
  1125. opts[S] |= OPEN_NEW|OPEN_FIND, svars->state[S] |= ST_FIND_OLD;
  1126. else
  1127. assert( !"sync record with stray TUID" );
  1128. }
  1129. }
  1130. svars->drv[M]->prepare_load_box( ctx[M], opts[M] );
  1131. svars->drv[S]->prepare_load_box( ctx[S], opts[S] );
  1132. ARRAY_INIT( &mexcs );
  1133. if (svars->ctx[M]->opts & OPEN_OLD) {
  1134. if (chan->max_messages) {
  1135. /* When messages have been expired on the slave, the master fetch is split into
  1136. * two ranges: The bulk fetch which corresponds with the most recent messages, and an
  1137. * exception list of messages which would have been expired if they weren't important. */
  1138. debug( "preparing master selection - max expired slave uid is %d\n", svars->smaxxuid );
  1139. /* First, find out the lower bound for the bulk fetch. */
  1140. minwuid = INT_MAX;
  1141. for (srec = svars->srecs; srec; srec = srec->next) {
  1142. if ((srec->status & S_DEAD) || srec->uid[M] <= 0)
  1143. continue;
  1144. if (srec->status & S_EXPIRED) {
  1145. if (!srec->uid[S]) {
  1146. /* The expired message was already gone. */
  1147. continue;
  1148. }
  1149. /* The expired message was not expunged yet, so re-examine it.
  1150. * This will happen en masse, so just extend the bulk fetch. */
  1151. } else {
  1152. if (svars->smaxxuid >= srec->uid[S]) {
  1153. /* The non-expired message is in the generally expired range, so don't
  1154. * make it contribute to the bulk fetch. */
  1155. continue;
  1156. }
  1157. /* Usual non-expired message. */
  1158. }
  1159. if (minwuid > srec->uid[M])
  1160. minwuid = srec->uid[M];
  1161. }
  1162. debug( " min non-orphaned master uid is %d\n", minwuid );
  1163. /* Next, calculate the exception fetch. */
  1164. for (srec = svars->srecs; srec; srec = srec->next) {
  1165. if (srec->status & S_DEAD)
  1166. continue;
  1167. if (srec->uid[M] > 0 && srec->uid[S] > 0 && minwuid > srec->uid[M] &&
  1168. (!(svars->ctx[M]->opts & OPEN_NEW) || svars->maxuid[M] >= srec->uid[M])) {
  1169. /* The pair is alive, but outside the bulk range. */
  1170. *int_array_append( &mexcs ) = srec->uid[M];
  1171. }
  1172. }
  1173. debugn( " exception list is:" );
  1174. for (t = 0; t < mexcs.array.size; t++)
  1175. debugn( " %d", mexcs.array.data[t] );
  1176. debug( "\n" );
  1177. } else {
  1178. minwuid = 1;
  1179. }
  1180. } else {
  1181. minwuid = INT_MAX;
  1182. }
  1183. sync_ref( svars );
  1184. sort_int_array( mexcs.array );
  1185. load_box( svars, M, minwuid, mexcs.array );
  1186. if (!check_cancel( svars ))
  1187. load_box( svars, S, (ctx[S]->opts & OPEN_OLD) ? 1 : INT_MAX, (int_array_t){ 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_array_t mexcs )
  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, 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_SYNC) {
  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. notice( "Notice: 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_SYNC) {
  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) && ((shifted_bit(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. flags_total[t]++;
  1581. stats();
  1582. svars->flags_pending[t]++;
  1583. fv = nfmalloc( sizeof(*fv) );
  1584. fv->aux = AUX;
  1585. fv->srec = srec;
  1586. fv->aflags = aflags;
  1587. fv->dflags = dflags;
  1588. svars->drv[t]->set_msg_flags( svars->ctx[t], srec->msg[t], srec->uid[t], aflags, dflags, flags_set, fv );
  1589. if (check_cancel( svars ))
  1590. goto out;
  1591. } else
  1592. flags_set_p2( svars, srec, t );
  1593. }
  1594. }
  1595. for (t = 0; t < 2; t++) {
  1596. svars->drv[t]->commit_cmds( svars->ctx[t] );
  1597. svars->state[t] |= ST_SENT_FLAGS;
  1598. msgs_flags_set( svars, t );
  1599. if (check_cancel( svars ))
  1600. goto out;
  1601. }
  1602. debug( "propagating new messages\n" );
  1603. if (UseFSync)
  1604. fdatasync( fileno( svars->jfp ) );
  1605. for (t = 0; t < 2; t++) {
  1606. svars->newuid[t] = svars->ctx[t]->uidnext;
  1607. Fprintf( svars->jfp, "%c %d\n", "{}"[t], svars->newuid[t] );
  1608. svars->new_msgs[t] = svars->ctx[1-t]->msgs;
  1609. msgs_copied( svars, t );
  1610. if (check_cancel( svars ))
  1611. goto out;
  1612. }
  1613. out:
  1614. sync_deref( svars );
  1615. }
  1616. static void
  1617. msg_copied( int sts, int uid, copy_vars_t *vars )
  1618. {
  1619. SVARS_CHECK_CANCEL_RET;
  1620. switch (sts) {
  1621. case SYNC_OK:
  1622. if (uid < 0)
  1623. svars->state[t] |= ST_FIND_NEW;
  1624. msg_copied_p2( svars, vars->srec, t, uid );
  1625. break;
  1626. case SYNC_NOGOOD:
  1627. debug( " -> killing (%d,%d)\n", vars->srec->uid[M], vars->srec->uid[S] );
  1628. vars->srec->status = S_DEAD;
  1629. Fprintf( svars->jfp, "- %d %d\n", vars->srec->uid[M], vars->srec->uid[S] );
  1630. break;
  1631. default:
  1632. cancel_sync( svars );
  1633. free( vars );
  1634. return;
  1635. }
  1636. free( vars );
  1637. new_done[t]++;
  1638. stats();
  1639. svars->new_pending[t]--;
  1640. msgs_copied( svars, t );
  1641. }
  1642. static void
  1643. msg_copied_p2( sync_vars_t *svars, sync_rec_t *srec, int t, int uid )
  1644. {
  1645. /* Possible previous UIDs:
  1646. * - -2 when the entry is new
  1647. * - -1 when re-newing an entry
  1648. * Possible new UIDs:
  1649. * - a real UID when storing a message to a UIDPLUS mailbox
  1650. * - -2 when storing a message to a dumb mailbox
  1651. * - -1 when not actually storing a message */
  1652. if (srec->uid[t] != uid) {
  1653. debug( " -> new UID %d on %s\n", uid, str_ms[t] );
  1654. Fprintf( svars->jfp, "%c %d %d %d\n", "<>"[t], srec->uid[M], srec->uid[S], uid );
  1655. srec->uid[t] = uid;
  1656. srec->tuid[0] = 0;
  1657. }
  1658. if (t == S && svars->mmaxxuid < srec->uid[M]) {
  1659. /* If we have so many new messages that some of them are instantly expired,
  1660. * but some are still propagated because they are important, we need to
  1661. * ensure explicitly that the bulk fetch limit is upped. */
  1662. svars->mmaxxuid = INT_MAX;
  1663. if (svars->smaxxuid < srec->uid[S] - 1) {
  1664. svars->smaxxuid = srec->uid[S] - 1;
  1665. Fprintf( svars->jfp, "! %d\n", svars->smaxxuid );
  1666. }
  1667. }
  1668. }
  1669. static void msgs_found_new( int sts, void *aux );
  1670. static void msgs_new_done( sync_vars_t *svars, int t );
  1671. static void sync_close( sync_vars_t *svars, int t );
  1672. static void
  1673. msgs_copied( sync_vars_t *svars, int t )
  1674. {
  1675. message_t *tmsg;
  1676. sync_rec_t *srec;
  1677. copy_vars_t *cv;
  1678. if (svars->state[t] & ST_SENDING_NEW)
  1679. return;
  1680. sync_ref( svars );
  1681. if (!(svars->state[t] & ST_SENT_NEW)) {
  1682. for (tmsg = svars->new_msgs[t]; tmsg; tmsg = tmsg->next) {
  1683. if ((srec = tmsg->srec) && srec->tuid[0]) {
  1684. if (svars->drv[t]->memory_usage( svars->ctx[t] ) >= BufferLimit) {
  1685. svars->new_msgs[t] = tmsg;
  1686. goto out;
  1687. }
  1688. new_total[t]++;
  1689. stats();
  1690. svars->new_pending[t]++;
  1691. svars->state[t] |= ST_SENDING_NEW;
  1692. cv = nfmalloc( sizeof(*cv) );
  1693. cv->cb = msg_copied;
  1694. cv->aux = AUX;
  1695. cv->srec = srec;
  1696. cv->msg = tmsg;
  1697. copy_msg( cv );
  1698. svars->state[t] &= ~ST_SENDING_NEW;
  1699. if (check_cancel( svars ))
  1700. goto out;
  1701. }
  1702. }
  1703. svars->state[t] |= ST_SENT_NEW;
  1704. }
  1705. if (svars->new_pending[t])
  1706. goto out;
  1707. Fprintf( svars->jfp, "%c %d\n", ")("[t], svars->maxuid[1-t] );
  1708. sync_close( svars, 1-t );
  1709. if (check_cancel( svars ))
  1710. goto out;
  1711. if (svars->state[t] & ST_FIND_NEW) {
  1712. debug( "finding just copied messages on %s\n", str_ms[t] );
  1713. svars->drv[t]->find_new_msgs( svars->ctx[t], svars->newuid[t], msgs_found_new, AUX );
  1714. } else {
  1715. msgs_new_done( svars, t );
  1716. }
  1717. out:
  1718. sync_deref( svars );
  1719. }
  1720. static void
  1721. msgs_found_new( int sts, void *aux )
  1722. {
  1723. SVARS_CHECK_RET;
  1724. switch (sts) {
  1725. case DRV_OK:
  1726. debug( "matching just copied messages on %s\n", str_ms[t] );
  1727. break;
  1728. default:
  1729. warn( "Warning: cannot find newly stored messages on %s.\n", str_ms[t] );
  1730. break;
  1731. }
  1732. match_tuids( svars, t );
  1733. msgs_new_done( svars, t );
  1734. }
  1735. static void
  1736. msgs_new_done( sync_vars_t *svars, int t )
  1737. {
  1738. svars->state[t] |= ST_FOUND_NEW;
  1739. sync_close( svars, t );
  1740. }
  1741. static void
  1742. flags_set( int sts, void *aux )
  1743. {
  1744. SVARS_CHECK_RET_VARS(flag_vars_t);
  1745. switch (sts) {
  1746. case DRV_OK:
  1747. if (vars->aflags & F_DELETED)
  1748. vars->srec->status |= S_DEL(t);
  1749. else if (vars->dflags & F_DELETED)
  1750. vars->srec->status &= ~S_DEL(t);
  1751. flags_set_p2( svars, vars->srec, t );
  1752. break;
  1753. }
  1754. free( vars );
  1755. flags_done[t]++;
  1756. stats();
  1757. svars->flags_pending[t]--;
  1758. msgs_flags_set( svars, t );
  1759. }
  1760. static void
  1761. flags_set_p2( sync_vars_t *svars, sync_rec_t *srec, int t )
  1762. {
  1763. if (srec->status & S_DELETE) {
  1764. debug( " pair(%d,%d): resetting %s UID\n", srec->uid[M], srec->uid[S], str_ms[1-t] );
  1765. Fprintf( svars->jfp, "%c %d %d 0\n", "><"[t], srec->uid[M], srec->uid[S] );
  1766. srec->uid[1-t] = 0;
  1767. } else {
  1768. int nflags = (srec->flags | srec->aflags[t]) & ~srec->dflags[t];
  1769. if (srec->flags != nflags) {
  1770. debug( " pair(%d,%d): updating flags (%u -> %u; %sed)\n", srec->uid[M], srec->uid[S], srec->flags, nflags, str_hl[t] );
  1771. srec->flags = nflags;
  1772. Fprintf( svars->jfp, "* %d %d %u\n", srec->uid[M], srec->uid[S], nflags );
  1773. }
  1774. if (t == S) {
  1775. int nex = (srec->status / S_NEXPIRE) & 1;
  1776. if (nex != ((srec->status / S_EXPIRED) & 1)) {
  1777. if (nex && (svars->smaxxuid < srec->uid[S]))
  1778. svars->smaxxuid = srec->uid[S];
  1779. Fprintf( svars->jfp, "/ %d %d\n", srec->uid[M], srec->uid[S] );
  1780. debug( " pair(%d,%d): expired %d (commit)\n", srec->uid[M], srec->uid[S], nex );
  1781. srec->status = (srec->status & ~S_EXPIRED) | (nex * S_EXPIRED);
  1782. } else if (nex != ((srec->status / S_EXPIRE) & 1)) {
  1783. Fprintf( svars->jfp, "\\ %d %d\n", srec->uid[M], srec->uid[S] );
  1784. debug( " pair(%d,%d): expire %d (cancel)\n", srec->uid[M], srec->uid[S], nex );
  1785. srec->status = (srec->status & ~S_EXPIRE) | (nex * S_EXPIRE);
  1786. }
  1787. }
  1788. }
  1789. }
  1790. typedef struct {
  1791. void *aux;
  1792. message_t *msg;
  1793. } trash_vars_t;
  1794. static void msg_trashed( int sts, void *aux );
  1795. static void msg_rtrashed( int sts, int uid, copy_vars_t *vars );
  1796. static void
  1797. msgs_flags_set( sync_vars_t *svars, int t )
  1798. {
  1799. message_t *tmsg;
  1800. trash_vars_t *tv;
  1801. copy_vars_t *cv;
  1802. if (!(svars->state[t] & ST_SENT_FLAGS) || svars->flags_pending[t])
  1803. return;
  1804. sync_ref( svars );
  1805. if ((svars->chan->ops[t] & OP_EXPUNGE) &&
  1806. (svars->ctx[t]->conf->trash || (svars->ctx[1-t]->conf->trash && svars->ctx[1-t]->conf->trash_remote_new))) {
  1807. debug( "trashing in %s\n", str_ms[t] );
  1808. for (tmsg = svars->ctx[t]->msgs; tmsg; tmsg = tmsg->next)
  1809. if ((tmsg->flags & F_DELETED) && !find_int_array( svars->trashed_msgs[t].array, tmsg->uid ) &&
  1810. (t == M || !tmsg->srec || !(tmsg->srec->status & (S_EXPIRE|S_EXPIRED)))) {
  1811. if (svars->ctx[t]->conf->trash) {
  1812. if (!svars->ctx[t]->conf->trash_only_new || !tmsg->srec || tmsg->srec->uid[1-t] < 0) {
  1813. debug( "%s: trashing message %d\n", str_ms[t], tmsg->uid );
  1814. trash_total[t]++;
  1815. stats();
  1816. svars->trash_pending[t]++;
  1817. tv = nfmalloc( sizeof(*tv) );
  1818. tv->aux = AUX;
  1819. tv->msg = tmsg;
  1820. svars->drv[t]->trash_msg( svars->ctx[t], tmsg, msg_trashed, tv );
  1821. if (check_cancel( svars ))
  1822. goto out;
  1823. } else
  1824. debug( "%s: not trashing message %d - not new\n", str_ms[t], tmsg->uid );
  1825. } else {
  1826. if (!tmsg->srec || tmsg->srec->uid[1-t] < 0) {
  1827. if (tmsg->size <= svars->ctx[1-t]->conf->max_size) {
  1828. debug( "%s: remote trashing message %d\n", str_ms[t], tmsg->uid );
  1829. trash_total[t]++;
  1830. stats();
  1831. svars->trash_pending[t]++;
  1832. cv = nfmalloc( sizeof(*cv) );
  1833. cv->cb = msg_rtrashed;
  1834. cv->aux = INV_AUX;
  1835. cv->srec = 0;
  1836. cv->msg = tmsg;
  1837. copy_msg( cv );
  1838. if (check_cancel( svars ))
  1839. goto out;
  1840. } else
  1841. debug( "%s: not remote trashing message %d - too big\n", str_ms[t], tmsg->uid );
  1842. } else
  1843. debug( "%s: not remote trashing message %d - not new\n", str_ms[t], tmsg->uid );
  1844. }
  1845. }
  1846. }
  1847. svars->state[t] |= ST_SENT_TRASH;
  1848. sync_close( svars, t );
  1849. out:
  1850. sync_deref( svars );
  1851. }
  1852. static void
  1853. msg_trashed( int sts, void *aux )
  1854. {
  1855. trash_vars_t *vars = (trash_vars_t *)aux;
  1856. DECL_SVARS;
  1857. if (sts == DRV_MSG_BAD)
  1858. sts = DRV_BOX_BAD;
  1859. if (check_ret( sts, vars->aux ))
  1860. return;
  1861. INIT_SVARS(vars->aux);
  1862. debug( " -> trashed %s %d\n", str_ms[t], vars->msg->uid );
  1863. Fprintf( svars->jfp, "%c %d\n", "[]"[t], vars->msg->uid );
  1864. free( vars );
  1865. trash_done[t]++;
  1866. stats();
  1867. svars->trash_pending[t]--;
  1868. sync_close( svars, t );
  1869. }
  1870. static void
  1871. msg_rtrashed( int sts, int uid ATTR_UNUSED, copy_vars_t *vars )
  1872. {
  1873. SVARS_CHECK_CANCEL_RET;
  1874. switch (sts) {
  1875. case SYNC_OK:
  1876. case SYNC_NOGOOD: /* the message is gone or heavily busted */
  1877. break;
  1878. default:
  1879. cancel_sync( svars );
  1880. free( vars );
  1881. return;
  1882. }
  1883. t ^= 1;
  1884. debug( " -> remote trashed %s %d\n", str_ms[t], vars->msg->uid );
  1885. Fprintf( svars->jfp, "%c %d\n", "[]"[t], vars->msg->uid );
  1886. free( vars );
  1887. trash_done[t]++;
  1888. stats();
  1889. svars->trash_pending[t]--;
  1890. sync_close( svars, t );
  1891. }
  1892. static void box_closed( int sts, void *aux );
  1893. static void box_closed_p2( sync_vars_t *svars, int t );
  1894. static void
  1895. sync_close( sync_vars_t *svars, int t )
  1896. {
  1897. if ((~svars->state[t] & (ST_FOUND_NEW|ST_SENT_TRASH)) || svars->trash_pending[t] ||
  1898. !(svars->state[1-t] & ST_SENT_NEW) || svars->new_pending[1-t])
  1899. return;
  1900. if (svars->state[t] & ST_CLOSING)
  1901. return;
  1902. svars->state[t] |= ST_CLOSING;
  1903. if ((svars->chan->ops[t] & OP_EXPUNGE) /*&& !(svars->state[t] & ST_TRASH_BAD)*/) {
  1904. debug( "expunging %s\n", str_ms[t] );
  1905. svars->drv[t]->close_box( svars->ctx[t], box_closed, AUX );
  1906. } else {
  1907. box_closed_p2( svars, t );
  1908. }
  1909. }
  1910. static void
  1911. box_closed( int sts, void *aux )
  1912. {
  1913. SVARS_CHECK_RET;
  1914. svars->state[t] |= ST_DID_EXPUNGE;
  1915. box_closed_p2( svars, t );
  1916. }
  1917. static void
  1918. box_closed_p2( sync_vars_t *svars, int t )
  1919. {
  1920. sync_rec_t *srec;
  1921. int minwuid;
  1922. svars->state[t] |= ST_CLOSED;
  1923. if (!(svars->state[1-t] & ST_CLOSED))
  1924. return;
  1925. if (((svars->state[M] | svars->state[S]) & ST_DID_EXPUNGE) || svars->chan->max_messages) {
  1926. debug( "purging obsolete entries\n" );
  1927. minwuid = INT_MAX;
  1928. if (svars->chan->max_messages) {
  1929. debug( " max expired slave uid is %d\n", svars->smaxxuid );
  1930. for (srec = svars->srecs; srec; srec = srec->next) {
  1931. if (srec->status & S_DEAD)
  1932. continue;
  1933. if (!((srec->uid[S] <= 0 || ((srec->status & S_DEL(S)) && (svars->state[S] & ST_DID_EXPUNGE))) &&
  1934. (srec->uid[M] <= 0 || ((srec->status & S_DEL(M)) && (svars->state[M] & ST_DID_EXPUNGE)) || (srec->status & S_EXPIRED))) &&
  1935. svars->smaxxuid < srec->uid[S] && minwuid > srec->uid[M])
  1936. minwuid = srec->uid[M];
  1937. }
  1938. debug( " min non-orphaned master uid is %d\n", minwuid );
  1939. }
  1940. for (srec = svars->srecs; srec; srec = srec->next) {
  1941. if (srec->status & S_DEAD)
  1942. continue;
  1943. if (srec->uid[S] <= 0 || ((srec->status & S_DEL(S)) && (svars->state[S] & ST_DID_EXPUNGE))) {
  1944. if (srec->uid[M] <= 0 || ((srec->status & S_DEL(M)) && (svars->state[M] & ST_DID_EXPUNGE)) ||
  1945. ((srec->status & S_EXPIRED) && svars->maxuid[M] >= srec->uid[M] && minwuid > srec->uid[M])) {
  1946. debug( " -> killing (%d,%d)\n", srec->uid[M], srec->uid[S] );
  1947. srec->status = S_DEAD;
  1948. Fprintf( svars->jfp, "- %d %d\n", srec->uid[M], srec->uid[S] );
  1949. } else if (srec->uid[S] > 0) {
  1950. debug( " -> orphaning (%d,[%d])\n", srec->uid[M], srec->uid[S] );
  1951. Fprintf( svars->jfp, "> %d %d 0\n", srec->uid[M], srec->uid[S] );
  1952. srec->uid[S] = 0;
  1953. }
  1954. } else if (srec->uid[M] > 0 && ((srec->status & S_DEL(M)) && (svars->state[M] & ST_DID_EXPUNGE))) {
  1955. debug( " -> orphaning ([%d],%d)\n", srec->uid[M], srec->uid[S] );
  1956. Fprintf( svars->jfp, "< %d %d 0\n", srec->uid[M], srec->uid[S] );
  1957. srec->uid[M] = 0;
  1958. }
  1959. }
  1960. }
  1961. save_state( svars );
  1962. sync_bail( svars );
  1963. }
  1964. static void
  1965. sync_bail( sync_vars_t *svars )
  1966. {
  1967. sync_rec_t *srec, *nsrec;
  1968. free( svars->trashed_msgs[M].array.data );
  1969. free( svars->trashed_msgs[S].array.data );
  1970. for (srec = svars->srecs; srec; srec = nsrec) {
  1971. nsrec = srec->next;
  1972. free( srec );
  1973. }
  1974. if (svars->lfd >= 0) {
  1975. unlink( svars->lname );
  1976. close( svars->lfd );
  1977. }
  1978. sync_bail2( svars );
  1979. }
  1980. static void
  1981. sync_bail2( sync_vars_t *svars )
  1982. {
  1983. free( svars->lname );
  1984. free( svars->nname );
  1985. free( svars->jname );
  1986. free( svars->dname );
  1987. sync_bail3( svars );
  1988. }
  1989. static void
  1990. sync_bail3( sync_vars_t *svars )
  1991. {
  1992. free( svars->box_name[M] );
  1993. free( svars->box_name[S] );
  1994. sync_deref( svars );
  1995. }
  1996. static void
  1997. sync_deref( sync_vars_t *svars )
  1998. {
  1999. if (!--svars->ref_count) {
  2000. void (*cb)( int sts, void *aux ) = svars->cb;
  2001. void *aux = svars->aux;
  2002. int ret = svars->ret;
  2003. free( svars );
  2004. cb( ret, aux );
  2005. }
  2006. }