sync.c 65 KB

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