2 * \file uid.c -- UID list handling (currently, only for POP3)
4 * For license terms, see the file COPYING in this directory.
17 #include "fetchmail.h"
22 * Machinery for handling UID lists live here. This is currently used
23 * by POP3, but may also be useful for making the IMAP4 querying logic
26 * These functions are also used by the rest of the code to maintain
31 * At start of a query, we have a (possibly empty) list of UIDs to be
32 * considered seen in `oldsaved'. These are messages that were left in
33 * the mailbox and *not deleted* on previous queries (we don't need to
34 * remember the UIDs of deleted messages because ... well, they're gone!)
35 * This list is initially set up by initialize_saved_list() from the
38 * Early in the query, during the execution of the protocol-specific
39 * getrange code, the driver expects that the host's `newsaved' member
40 * will be filled with a list of UIDs and message numbers representing
41 * the mailbox state. If this list is empty, the server did
42 * not respond to the request for a UID listing.
44 * Each time a message is fetched, we can check its UID against the
45 * `oldsaved' list to see if it is old.
47 * Each time a message-id is seen, we mark it with MARK_SEEN.
49 * Each time a message is deleted, we mark its id UID_DELETED in the
50 * `newsaved' member. When we want to assert that an expunge has been
51 * done on the server, we call expunge_uid() to register that all
52 * deleted messages are gone by marking them UID_EXPUNGED.
54 * At the end of the query, the `newsaved' member becomes the
55 * `oldsaved' list. The old `oldsaved' list is freed.
57 * At the end of the fetchmail run, seen and non-EXPUNGED members of all
58 * current `oldsaved' lists are flushed out to the .fetchids file to
59 * be picked up by the next run. If there are no un-expunged
60 * messages, the file is deleted.
62 * One disadvantage of UIDL is that all the UIDs have to be downloaded
63 * before a search for new messages can be done. Typically, new messages
64 * are appended to mailboxes. Hence, downloading all UIDs just to download
65 * a few new mails is a waste of bandwidth. If new messages are always at
66 * the end of the mailbox, fast UIDL will decrease the time required to
69 * During fast UIDL, the UIDs of all messages are not downloaded! The first
70 * unseen message is searched for by using a binary search on UIDs. UIDs
71 * after the first unseen message are downloaded as and when needed.
73 * The advantages of fast UIDL are (this is noticeable only when the
74 * mailbox has too many mails):
76 * - There is no need to download the UIDs of all mails right at the start.
77 * - There is no need to save all the UIDs in memory separately in
79 * - There is no need to download the UIDs of seen mail (except for the
80 * first binary search).
81 * - The first new mail is downloaded considerably faster.
83 * The disadvantages are:
85 * - Since all UIDs are not downloaded, it is not possible to swap old and
86 * new list. The current state of the mailbox is essentially a merged state
87 * of old and new mails.
88 * - If an intermediate mail has been temporarily refused (say, due to 4xx
89 * code from the smtp server), this mail may not get downloaded.
90 * - If 'flush' is used, such intermediate mails will also get deleted.
92 * The first two disadvantages can be overcome by doing a linear search
93 * once in a while (say, every 10th poll). Also, with flush, fast UIDL
96 * Note: some comparisons (those used for DNS address lists) are caseblind!
102 /** UIDs associated with un-queried hosts */
103 static struct idlist *scratchlist;
105 /** Read saved IDs from \a idfile and attach to each host in \a hostlist. */
106 static int dump_saved_uid(struct uid_db_record *rec, void *unused)
112 t = sdump(rec->id, rec->id_len);
113 report_build(stdout, " %s", t);
119 void initialize_saved_lists(struct query *hostlist, const char *idfile)
125 /* make sure lists are initially empty */
126 for (ctl = hostlist; ctl; ctl = ctl->next) {
127 ctl->skipped = (struct idlist *)NULL;
129 init_uid_db(&ctl->oldsaved);
130 init_uid_db(&ctl->newsaved);
136 * Croak if the uidl directory does not exist.
137 * This probably means an NFS mount failed and we can't
138 * see a uidl file that ought to be there.
139 * Question: is this a portable check? It's not clear
140 * that all implementations of lstat() will return ENOTDIR
141 * rather than plain ENOENT in this case...
143 if (lstat(idfile, &statbuf) < 0) {
144 if (errno == ENOTDIR)
146 report(stderr, "lstat: %s: %s\n", idfile, strerror(errno));
151 /* let's get stored message UIDs from previous queries */
152 if ((tmpfp = fopen(idfile, "r")) != (FILE *)NULL)
154 char buf[POPBUFSIZE+1];
155 char *host = NULL; /* pacify -Wall */
158 char *atsign; /* temp pointer used in parsing user and host */
162 char saveddelim2 = '\0'; /* pacify -Wall */
164 while (fgets(buf, POPBUFSIZE, tmpfp) != (char *)NULL)
167 * At this point, we assume the bug has two fields -- a user@host
168 * part, and an ID part. Either field may contain spurious @ signs.
169 * The previous version of this code presumed one could split at
170 * the rightmost '@'. This is not correct, as InterMail puts an
174 /* first, skip leading spaces */
175 user = buf + strspn(buf, " \t");
178 * First, we split the buf into a userhost part and an id
179 * part ... but id doesn't necessarily start with a '<',
180 * espescially if the POP server returns an X-UIDL header
181 * instead of a Message-ID, as GMX's (www.gmx.net) POP3
182 * StreamProxy V1.0 does.
184 * this is one other trick. The userhost part
185 * may contain ' ' in the user part, at least in
186 * the lotus notes case.
187 * So we start looking for the '@' after which the
188 * host will follow with the ' ' separator with the id.
190 * XXX FIXME: There is a case this code cannot handle:
191 * the user name cannot have blanks after a '@'.
193 if ((delimp1 = strchr(user, '@')) != NULL &&
194 (id = strchr(delimp1,' ')) != NULL)
196 for (delimp1 = id; delimp1 >= user; delimp1--)
197 if ((*delimp1 != ' ') && (*delimp1 != '\t'))
201 * It should be safe to assume that id starts after
202 * the " " - after all, we're writing the " "
203 * ourselves in write_saved_lists() :-)
205 id = id + strspn(id, " ");
207 delimp1++; /* but what if there is only white space ?!? */
208 /* we have at least one @, else we are not in this branch */
209 saveddelim1 = *delimp1; /* save char after token */
210 *delimp1 = '\0'; /* delimit token with \0 */
212 /* now remove trailing white space chars from id */
213 if ((delimp2 = strpbrk(id, " \t\n")) != NULL ) {
214 saveddelim2 = *delimp2;
218 atsign = strrchr(user, '@');
219 /* we have at least one @, else we are not in this branch */
223 /* find uidl db and save it */
224 for (ctl = hostlist; ctl; ctl = ctl->next) {
225 if (strcasecmp(host, ctl->server.queryname) == 0
226 && strcasecmp(user, ctl->remotename) == 0) {
227 uid_db_insert(&ctl->oldsaved, id, UID_SEEN);
232 * If it's not in a host we're querying,
233 * save it anyway. Otherwise we'd lose UIDL
234 * information any time we queried an explicit
237 if (ctl == (struct query *)NULL) {
239 *delimp1 = saveddelim1;
241 if (delimp2 != NULL) {
242 *delimp2 = saveddelim2;
244 save_str(&scratchlist, buf, UID_SEEN);
248 fclose(tmpfp); /* not checking should be safe, mode was "r" */
251 if (outlevel >= O_DEBUG)
255 for (ctl = hostlist; ctl; ctl = ctl->next)
257 report_build(stdout, GT_("Old UID list from %s:"),
258 ctl->server.pollname);
260 if (!uid_db_n_records(&ctl->oldsaved))
261 report_build(stdout, GT_(" <empty>"));
263 traverse_uid_db(&ctl->oldsaved, dump_saved_uid, NULL);
265 report_complete(stdout, "\n");
268 report_build(stdout, GT_("Scratch list of UIDs:"));
270 report_build(stdout, GT_(" <empty>"));
271 else for (idp = scratchlist; idp; idp = idp->next) {
272 char *t = sdump(idp->id, strlen(idp->id)-1);
273 report_build(stdout, " %s\n", t);
276 report_complete(stdout, "\n");
280 /** Assert that all UIDs marked deleted in query \a ctl have actually been
282 static int mark_as_expunged_if(struct uid_db_record *rec, void *unused)
286 if (rec->status == UID_DELETED) rec->status = UID_EXPUNGED;
290 void expunge_uids(struct query *ctl)
292 traverse_uid_db(dofastuidl ? &ctl->oldsaved : &ctl->newsaved,
293 mark_as_expunged_if, NULL);
296 static const char *str_uidmark(int mark)
310 if (snprintf(buf, sizeof(buf), "MARK=%d", mark) < 0)
317 static int dump_uid_db_record(struct uid_db_record *rec, void *arg)
322 n_recs = (unsigned int *)arg;
325 t = sdump(rec->id, rec->id_len);
326 report_build(stdout, " %s = %s%s", t, str_uidmark(rec->status), *n_recs ? "," : "");
332 static void dump_uid_db(struct uid_db *db)
336 n_recs = uid_db_n_records(db);
338 report_build(stdout, GT_(" <empty>"));
342 traverse_uid_db(db, dump_uid_db_record, &n_recs);
346 void uid_swap_lists(struct query *ctl)
349 if (outlevel >= O_DEBUG)
352 report_build(stdout, GT_("Merged UID list from %s:"), ctl->server.pollname);
353 dump_uid_db(&ctl->oldsaved);
355 report_build(stdout, GT_("New UID list from %s:"), ctl->server.pollname);
356 dump_uid_db(&ctl->newsaved);
358 report_complete(stdout, "\n");
362 * Don't swap UID lists unless we've actually seen UIDLs.
363 * This is necessary in order to keep UIDL information
364 * from being heedlessly deleted later on.
366 * Older versions of fetchmail did
368 * free_str_list(&scratchlist);
370 * after swap. This was wrong; we need to preserve the UIDL information
371 * from unqueried hosts. Unfortunately, not doing this means that
372 * under some circumstances UIDLs can end up being stored forever --
373 * specifically, if a user description is removed from .fetchmailrc
374 * with UIDLs from that account in .fetchids, there is no way for
375 * them to ever get garbage-collected.
377 if (uid_db_n_records(&ctl->newsaved))
379 swap_uid_db_data(&ctl->newsaved, &ctl->oldsaved);
380 clear_uid_db(&ctl->newsaved);
382 /* in fast uidl, there is no need to swap lists: the old state of
383 * mailbox cannot be discarded! */
384 else if (outlevel >= O_DEBUG && !dofastuidl)
385 report(stdout, GT_("not swapping UID lists, no UIDs seen this query\n"));
388 /* finish a query which had errors */
389 void uid_discard_new_list(struct query *ctl)
392 if (outlevel >= O_DEBUG)
394 /* this is now a merged list! the mails which were seen in this
395 * poll are marked here. */
396 report_build(stdout, GT_("Merged UID list from %s:"), ctl->server.pollname);
397 dump_uid_db(&ctl->oldsaved);
398 report_complete(stdout, "\n");
401 if (uid_db_n_records(&ctl->newsaved))
403 /* new state of mailbox is not reliable */
404 if (outlevel >= O_DEBUG)
405 report(stdout, GT_("discarding new UID list\n"));
406 clear_uid_db(&ctl->newsaved);
410 /** Reset the number associated with each id */
411 void uid_reset_num(struct query *ctl)
413 reset_uid_db_nums(&ctl->oldsaved);
416 /** Write list of seen messages, at end of run. */
417 static int count_seen_deleted(struct uid_db_record *rec, void *arg)
419 if (rec->status == UID_SEEN || rec->status == UID_DELETED)
424 struct write_saved_info {
429 static int write_uid_db_record(struct uid_db_record *rec, void *arg)
431 struct write_saved_info *info;
434 if (!(rec->status == UID_SEEN || rec->status == UID_DELETED))
437 info = (struct write_saved_info *)arg;
438 rc = fprintf(info->fp, "%s@%s %s\n",
439 info->ctl->remotename, info->ctl->server.queryname,
441 return rc < 0 ? -1 : 0;
444 void write_saved_lists(struct query *hostlist, const char *idfile)
451 /* if all lists are empty, nuke the file */
453 for (ctl = hostlist; ctl; ctl = ctl->next)
454 traverse_uid_db(&ctl->oldsaved, count_seen_deleted, &idcount);
456 /* either nuke the file or write updated last-seen IDs */
457 if (!idcount && !scratchlist)
459 if (outlevel >= O_DEBUG) {
460 if (access(idfile, F_OK) == 0)
461 report(stdout, GT_("Deleting fetchids file.\n"));
463 if (unlink(idfile) && errno != ENOENT)
464 report(stderr, GT_("Error deleting %s: %s\n"), idfile, strerror(errno));
466 char *newnam = (char *)xmalloc(strlen(idfile) + 2);
467 strcpy(newnam, idfile);
469 if (outlevel >= O_DEBUG)
470 report(stdout, GT_("Writing fetchids file.\n"));
471 (void)unlink(newnam); /* remove file/link first */
472 if ((tmpfp = fopen(newnam, "w")) != (FILE *)NULL) {
473 struct write_saved_info info;
478 for (ctl = hostlist; ctl; ctl = ctl->next) {
481 if (traverse_uid_db(&ctl->oldsaved, write_uid_db_record, &info) < 0) {
483 report(stderr, GT_("Write error on fetchids file %s: %s\n"), newnam, strerror(e));
489 for (idp = scratchlist; idp; idp = idp->next)
490 if (EOF == fputs(idp->id, tmpfp)) {
492 report(stderr, GT_("Write error on fetchids file %s: %s\n"), newnam, strerror(e));
498 (void)fflush(tmpfp); /* return code ignored, we check ferror instead */
499 errflg |= ferror(tmpfp);
501 /* if we could write successfully, move into place;
504 report(stderr, GT_("Error writing to fetchids file %s, old file left in place.\n"), newnam);
507 if (rename(newnam, idfile)) {
508 report(stderr, GT_("Cannot rename fetchids file %s to %s: %s\n"), newnam, idfile, strerror(errno));
512 report(stderr, GT_("Cannot open fetchids file %s for writing: %s\n"), newnam, strerror(errno));
517 #endif /* POP3_ENABLE */
519 /* uid.c ends here */