]> Pileus Git - ~andy/fetchmail/blob - uid.c
Remove zsh-completion. Way outdated.
[~andy/fetchmail] / uid.c
1 /**
2  * \file uid.c -- UID list handling (currently, only for POP3)
3  *
4  * For license terms, see the file COPYING in this directory.
5  */
6
7 #include "config.h"
8
9 #include <sys/stat.h>
10 #include <errno.h>
11 #include <stdio.h>
12 #include <limits.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <unistd.h>
16
17 #include "fetchmail.h"
18 #include "gettext.h"
19 #include "sdump.h"
20
21 /*
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
24  * UID-oriented.
25  *
26  * These functions are also used by the rest of the code to maintain
27  * string lists.
28  *
29  * Here's the theory:
30  *
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
36  * .fetchids file.
37  *
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.
43  *
44  * Each time a message is fetched, we can check its UID against the
45  * `oldsaved' list to see if it is old.
46  *
47  * Each time a message-id is seen, we mark it with MARK_SEEN.
48  *
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.
53  *
54  * At the end of the query, the `newsaved' member becomes the
55  * `oldsaved' list.  The old `oldsaved' list is freed.
56  *
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.
61  *
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
67  * download new mails.
68  *
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.
72  *
73  * The advantages of fast UIDL are (this is noticeable only when the
74  * mailbox has too many mails):
75  *
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
78  * `newsaved' list.
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.
82  *
83  * The disadvantages are:
84  *
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.
91  *
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
94  * should be disabled.
95  *
96  * Note: some comparisons (those used for DNS address lists) are caseblind!
97  */
98
99 int dofastuidl = 0;
100
101 #ifdef POP3_ENABLE
102 /** UIDs associated with un-queried hosts */
103 static struct idlist *scratchlist;
104
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)
107 {
108     char *t;
109
110     (void)unused;
111
112     t = sdump(rec->id, rec->id_len);
113     report_build(stdout, " %s", t);
114     free(t);
115
116     return 0;
117 }
118
119 void initialize_saved_lists(struct query *hostlist, const char *idfile)
120 {
121     struct stat statbuf;
122     FILE        *tmpfp;
123     struct query *ctl;
124
125     /* make sure lists are initially empty */
126     for (ctl = hostlist; ctl; ctl = ctl->next) {
127         ctl->skipped = (struct idlist *)NULL;
128
129         init_uid_db(&ctl->oldsaved);
130         init_uid_db(&ctl->newsaved);
131     }
132
133     errno = 0;
134
135     /*
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...
142      */
143     if (lstat(idfile, &statbuf) < 0) {
144         if (errno == ENOTDIR)
145         {
146             report(stderr, "lstat: %s: %s\n", idfile, strerror(errno));
147             exit(PS_IOERR);
148         }
149     }
150
151     /* let's get stored message UIDs from previous queries */
152     if ((tmpfp = fopen(idfile, "r")) != (FILE *)NULL)
153     {
154         char buf[POPBUFSIZE+1];
155         char *host = NULL;      /* pacify -Wall */
156         char *user;
157         char *id;
158         char *atsign;   /* temp pointer used in parsing user and host */
159         char *delimp1;
160         char saveddelim1;
161         char *delimp2;
162         char saveddelim2 = '\0';        /* pacify -Wall */
163
164         while (fgets(buf, POPBUFSIZE, tmpfp) != (char *)NULL)
165         {
166             /*
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
171              * '@' in the UIDL.
172              */
173
174             /* first, skip leading spaces */
175             user = buf + strspn(buf, " \t");
176
177             /*
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.
183              *
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.
189              *
190              * XXX FIXME: There is a case this code cannot handle:
191              * the user name cannot have blanks after a '@'.
192              */
193             if ((delimp1 = strchr(user, '@')) != NULL &&
194                 (id = strchr(delimp1,' ')) != NULL)
195             {
196                 for (delimp1 = id; delimp1 >= user; delimp1--)
197                     if ((*delimp1 != ' ') && (*delimp1 != '\t'))
198                         break;
199
200                 /*
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() :-)
204                  */
205                 id = id + strspn(id, " ");
206
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 */
211
212                 /* now remove trailing white space chars from id */
213                 if ((delimp2 = strpbrk(id, " \t\n")) != NULL ) {
214                     saveddelim2 = *delimp2;
215                     *delimp2 = '\0';
216                 }
217
218                 atsign = strrchr(user, '@');
219                 /* we have at least one @, else we are not in this branch */
220                 *atsign = '\0';
221                 host = atsign + 1;
222
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);
228                         break;
229                     }
230                 }
231                 /*
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
235                  * subset of hosts.
236                  */
237                 if (ctl == (struct query *)NULL) {
238                     /* restore string */
239                     *delimp1 = saveddelim1;
240                     *atsign = '@';
241                     if (delimp2 != NULL) {
242                         *delimp2 = saveddelim2;
243                     }
244                     save_str(&scratchlist, buf, UID_SEEN);
245                 }
246             }
247         }
248         fclose(tmpfp);  /* not checking should be safe, mode was "r" */
249     }
250
251     if (outlevel >= O_DEBUG)
252     {
253         struct idlist   *idp;
254
255         for (ctl = hostlist; ctl; ctl = ctl->next)
256             {
257                 report_build(stdout, GT_("Old UID list from %s:"),
258                              ctl->server.pollname);
259
260                 if (!uid_db_n_records(&ctl->oldsaved))
261                     report_build(stdout, GT_(" <empty>"));
262                 else
263                     traverse_uid_db(&ctl->oldsaved, dump_saved_uid, NULL);
264
265                 report_complete(stdout, "\n");
266             }
267
268         report_build(stdout, GT_("Scratch list of UIDs:"));
269         if (!scratchlist)
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);
274                 free(t);
275         }
276         report_complete(stdout, "\n");
277     }
278 }
279
280 /** Assert that all UIDs marked deleted in query \a ctl have actually been
281 expunged. */
282 static int mark_as_expunged_if(struct uid_db_record *rec, void *unused)
283 {
284     (void)unused;
285
286     if (rec->status == UID_DELETED) rec->status = UID_EXPUNGED;
287     return 0;
288 }
289
290 void expunge_uids(struct query *ctl)
291 {
292     traverse_uid_db(dofastuidl ? &ctl->oldsaved : &ctl->newsaved,
293                      mark_as_expunged_if, NULL);
294 }
295
296 static const char *str_uidmark(int mark)
297 {
298         static char buf[20];
299
300         switch(mark) {
301                 case UID_UNSEEN:
302                         return "UNSEEN";
303                 case UID_SEEN:
304                         return "SEEN";
305                 case UID_EXPUNGED:
306                         return "EXPUNGED";
307                 case UID_DELETED:
308                         return "DELETED";
309                 default:
310                         if (snprintf(buf, sizeof(buf), "MARK=%d", mark) < 0)
311                                 return "ERROR";
312                         else
313                                 return buf;
314         }
315 }
316
317 static int dump_uid_db_record(struct uid_db_record *rec, void *arg)
318 {
319         unsigned *n_recs;
320         char *t;
321
322         n_recs = (unsigned int *)arg;
323         --*n_recs;
324
325         t = sdump(rec->id, rec->id_len);
326         report_build(stdout, " %s = %s%s", t, str_uidmark(rec->status), *n_recs ? "," : "");
327         free(t);
328
329         return 0;
330 }
331
332 static void dump_uid_db(struct uid_db *db)
333 {
334         unsigned n_recs;
335
336         n_recs = uid_db_n_records(db);
337         if (!n_recs) {
338                 report_build(stdout, GT_(" <empty>"));
339                 return;
340         }
341
342         traverse_uid_db(db, dump_uid_db_record, &n_recs);
343 }
344
345 /* finish a query */
346 void uid_swap_lists(struct query *ctl)
347 {
348     /* debugging code */
349     if (outlevel >= O_DEBUG)
350     {
351         if (dofastuidl) {
352             report_build(stdout, GT_("Merged UID list from %s:"), ctl->server.pollname);
353             dump_uid_db(&ctl->oldsaved);
354         } else {
355             report_build(stdout, GT_("New UID list from %s:"), ctl->server.pollname);
356             dump_uid_db(&ctl->newsaved);
357         }
358         report_complete(stdout, "\n");
359     }
360
361     /*
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.
365      *
366      * Older versions of fetchmail did
367      *
368      *     free_str_list(&scratchlist);
369      *
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.
376      */
377     if (uid_db_n_records(&ctl->newsaved))
378     {
379         swap_uid_db_data(&ctl->newsaved, &ctl->oldsaved);
380         clear_uid_db(&ctl->newsaved);
381     }
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"));
386 }
387
388 /* finish a query which had errors */
389 void uid_discard_new_list(struct query *ctl)
390 {
391     /* debugging code */
392     if (outlevel >= O_DEBUG)
393     {
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");
399     }
400
401     if (uid_db_n_records(&ctl->newsaved))
402     {
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);
407     }
408 }
409
410 /** Reset the number associated with each id */
411 void uid_reset_num(struct query *ctl)
412 {
413     reset_uid_db_nums(&ctl->oldsaved);
414 }
415
416 /** Write list of seen messages, at end of run. */
417 static int count_seen_deleted(struct uid_db_record *rec, void *arg)
418 {
419     if (rec->status == UID_SEEN || rec->status == UID_DELETED)
420         ++*(long *)arg;
421     return 0;
422 }
423
424 struct write_saved_info {
425     struct query *ctl;
426     FILE *fp;
427 };
428
429 static int write_uid_db_record(struct uid_db_record *rec, void *arg)
430 {
431     struct write_saved_info *info;
432     int rc;
433
434     if (!(rec->status == UID_SEEN || rec->status == UID_DELETED))
435         return 0;
436
437     info = (struct write_saved_info *)arg;
438     rc = fprintf(info->fp, "%s@%s %s\n",
439                  info->ctl->remotename, info->ctl->server.queryname,
440                  rec->id);
441     return rc < 0 ? -1 : 0;
442 }
443
444 void write_saved_lists(struct query *hostlist, const char *idfile)
445 {
446     long        idcount;
447     FILE        *tmpfp;
448     struct query *ctl;
449     struct idlist *idp;
450
451     /* if all lists are empty, nuke the file */
452     idcount = 0;
453     for (ctl = hostlist; ctl; ctl = ctl->next)
454         traverse_uid_db(&ctl->oldsaved, count_seen_deleted, &idcount);
455
456     /* either nuke the file or write updated last-seen IDs */
457     if (!idcount && !scratchlist)
458     {
459         if (outlevel >= O_DEBUG) {
460             if (access(idfile, F_OK) == 0)
461                     report(stdout, GT_("Deleting fetchids file.\n"));
462         }
463         if (unlink(idfile) && errno != ENOENT)
464             report(stderr, GT_("Error deleting %s: %s\n"), idfile, strerror(errno));
465     } else {
466         char *newnam = (char *)xmalloc(strlen(idfile) + 2);
467         strcpy(newnam, idfile);
468         strcat(newnam, "_");
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;
474             int errflg = 0;
475
476             info.fp = tmpfp;
477
478             for (ctl = hostlist; ctl; ctl = ctl->next) {
479                 info.ctl = ctl;
480
481                 if (traverse_uid_db(&ctl->oldsaved, write_uid_db_record, &info) < 0) {
482                     int e = errno;
483                     report(stderr, GT_("Write error on fetchids file %s: %s\n"), newnam, strerror(e));
484                     errflg = 1;
485                     goto bailout;
486                 }
487             }
488
489             for (idp = scratchlist; idp; idp = idp->next)
490                 if (EOF == fputs(idp->id, tmpfp)) {
491                             int e = errno;
492                             report(stderr, GT_("Write error on fetchids file %s: %s\n"), newnam, strerror(e));
493                             errflg = 1;
494                             goto bailout;
495                 }
496
497 bailout:
498             (void)fflush(tmpfp); /* return code ignored, we check ferror instead */
499             errflg |= ferror(tmpfp);
500             fclose(tmpfp);
501             /* if we could write successfully, move into place;
502              * otherwise, drop */
503             if (errflg) {
504                 report(stderr, GT_("Error writing to fetchids file %s, old file left in place.\n"), newnam);
505                 unlink(newnam);
506             } else {
507                 if (rename(newnam, idfile)) {
508                     report(stderr, GT_("Cannot rename fetchids file %s to %s: %s\n"), newnam, idfile, strerror(errno));
509                 }
510             }
511         } else {
512             report(stderr, GT_("Cannot open fetchids file %s for writing: %s\n"), newnam, strerror(errno));
513         }
514         free(newnam);
515     }
516 }
517 #endif /* POP3_ENABLE */
518
519 /* uid.c ends here */