sync.c 66 KB

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