]> Pileus Git - ~andy/fetchmail/blob - uid.c
afc49678bdfde63fa1f356c27b26d46cb7d59b03
[~andy/fetchmail] / uid.c
1 /*
2  * uid.c -- UIDL handling for POP3 servers without LAST
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 #if defined(STDC_HEADERS)
14 #include <stdlib.h>
15 #include <string.h>
16 #endif
17 #if defined(HAVE_UNISTD_H)
18 #include <unistd.h>
19 #endif
20
21 #include "fetchmail.h"
22 #include "i18n.h"
23
24 /*
25  * Machinery for handling UID lists live here.  This is mainly to support
26  * RFC1725/RFC1939-conformant POP3 servers without a LAST command, but may also
27  * be useful for making the IMAP4 querying logic UID-oriented, if a future
28  * revision of IMAP forces me to.
29  *
30  * These functions are also used by the rest of the code to maintain
31  * string lists.
32  *
33  * Here's the theory:
34  *
35  * At start of a query, we have a (possibly empty) list of UIDs to be
36  * considered seen in `oldsaved'.  These are messages that were left in
37  * the mailbox and *not deleted* on previous queries (we don't need to
38  * remember the UIDs of deleted messages because ... well, they're gone!)
39  * This list is initially set up by initialize_saved_list() from the
40  * .fetchids file.
41  *
42  * Early in the query, during the execution of the protocol-specific
43  * getrange code, the driver expects that the host's `newsaved' member
44  * will be filled with a list of UIDs and message numbers representing
45  * the mailbox state.  If this list is empty, the server did
46  * not respond to the request for a UID listing.
47  *
48  * Each time a message is fetched, we can check its UID against the
49  * `oldsaved' list to see if it is old.
50  *
51  * Each time a message-id is seen, we mark it with MARK_SEEN.
52  *
53  * Each time a message is deleted, we mark its id UID_DELETED in the
54  * `newsaved' member.  When we want to assert that an expunge has been
55  * done on the server, we call expunge_uid() to register that all
56  * deleted messages are gone by marking them UID_EXPUNGED.
57  *
58  * At the end of the query, the `newsaved' member becomes the
59  * `oldsaved' list.  The old `oldsaved' list is freed.
60  *
61  * At the end of the fetchmail run, seen and non-EXPUNGED members of all
62  * current `oldsaved' lists are flushed out to the .fetchids file to
63  * be picked up by the next run.  If there are no un-expunged
64  * messages, the file is deleted.
65  *
66  * Note: some comparisons (those used for DNS address lists) are caseblind!
67  */
68
69 /* UIDs associated with un-queried hosts */
70 static struct idlist *scratchlist;
71
72 #ifdef POP3_ENABLE
73 void initialize_saved_lists(struct query *hostlist, const char *idfile)
74 /* read file of saved IDs and attach to each host */
75 {
76     struct stat statbuf;
77     FILE        *tmpfp;
78     struct query *ctl;
79
80     /* make sure lists are initially empty */
81     for (ctl = hostlist; ctl; ctl = ctl->next) {
82         ctl->skipped = (struct idlist *)NULL;
83         ctl->oldsaved = (struct idlist *)NULL;
84         ctl->newsaved = (struct idlist *)NULL;
85         ctl->oldsavedend = &ctl->oldsaved;
86     }
87
88     errno = 0;
89
90     /*
91      * Croak if the uidl directory does not exist.
92      * This probably means an NFS mount failed and we can't
93      * see a uidl file that ought to be there.
94      * Question: is this a portable check? It's not clear
95      * that all implementations of lstat() will return ENOTDIR
96      * rather than plain ENOENT in this case...
97      */
98     if (lstat(idfile, &statbuf) < 0) {
99         if (errno == ENOTDIR)
100         {
101             report(stderr, GT_("lstat: %s: %s\n"), idfile, strerror(errno));
102             exit(PS_IOERR);
103         }
104     }
105
106     /* let's get stored message UIDs from previous queries */
107     if ((tmpfp = fopen(idfile, "r")) != (FILE *)NULL)
108     {
109         char buf[POPBUFSIZE+1];
110         char *host = NULL;      /* pacify -Wall */
111         char *user;
112         char *id;
113         char *atsign;   /* temp pointer used in parsing user and host */
114         char *delimp1;
115         char saveddelim1;
116         char *delimp2;
117         char saveddelim2 = '\0';        /* pacify -Wall */
118
119         while (fgets(buf, POPBUFSIZE, tmpfp) != (char *)NULL)
120         {
121             /*
122              * At this point, we assume the bug has two fields -- a user@host 
123              * part, and an ID part. Either field may contain spurious @ signs.
124              * The previous version of this code presumed one could split at 
125              * the rightmost '@'.  This is not correct, as InterMail puts an 
126              * '@' in the UIDL.
127              */
128           
129             /* first, skip leading spaces */
130             user = buf + strspn(buf, " \t");
131
132             /*
133              * First, we split the buf into a userhost part and an id
134              * part ... but id doesn't necessarily start with a '<',
135              * espescially if the POP server returns an X-UIDL header
136              * instead of a Message-ID, as GMX's (www.gmx.net) POP3
137              * StreamProxy V1.0 does.
138              *
139              * this is one other trick. The userhost part 
140              * may contain ' ' in the user part, at least in
141              * the lotus notes case.
142              * So we start looking for the '@' after which the
143              * host will follow with the ' ' seperator finaly id.
144              */
145             if ((delimp1 = strchr(user, '@')) != NULL &&
146                 (id = strchr(delimp1,' ')) != NULL)
147             {
148                 for (delimp1 = id; delimp1 >= user; delimp1--)
149                     if ((*delimp1 != ' ') && (*delimp1 != '\t'))
150                         break;
151
152                 /* 
153                  * It should be safe to assume that id starts after
154                  * the " " - after all, we're writing the " "
155                  * ourselves in write_saved_lists() :-)
156                  */
157                 id = id + strspn(id, " ");
158
159                 delimp1++; /* but what if there is only white space ?!? */
160                 saveddelim1 = *delimp1; /* save char after token */
161                 *delimp1 = '\0';                /* delimit token with \0 */
162                 if (id != NULL) 
163                 {
164                     /* now remove trailing white space chars from id */
165                     if ((delimp2 = strpbrk(id, " \t\n")) != NULL ) {
166                         saveddelim2 = *delimp2;
167                         *delimp2 = '\0';
168                     }
169                     atsign = strrchr(user, '@');
170                     if (atsign) {
171                         *atsign = '\0';
172                         host = atsign + 1;
173
174                     }
175                     for (ctl = hostlist; ctl; ctl = ctl->next) {
176                         if (strcasecmp(host, ctl->server.queryname) == 0
177                             && strcasecmp(user, ctl->remotename) == 0) {
178         
179                             save_str(&ctl->oldsaved, id, UID_SEEN);
180                             break;
181                         }
182                     }
183                     /* 
184                      * If it's not in a host we're querying,
185                      * save it anyway.  Otherwise we'd lose UIDL
186                      * information any time we queried an explicit
187                      * subset of hosts.
188                      */
189                     if (ctl == (struct query *)NULL) {
190                                 /* restore string */
191                         *delimp1 = saveddelim1;
192                         *atsign = '@';
193                         if (delimp2 != NULL) {
194                             *delimp2 = saveddelim2;
195                         }
196                         save_str(&scratchlist, buf, UID_SEEN);
197                     }
198                 }
199             }
200         }
201         fclose(tmpfp);  /* not checking should be safe, mode was "r" */
202     }
203
204     if (outlevel >= O_DEBUG)
205     {
206         struct idlist   *idp;
207         int uidlcount = 0;
208
209         for (ctl = hostlist; ctl; ctl = ctl->next)
210             if (ctl->server.uidl)
211             {
212                 report_build(stdout, GT_("Old UID list from %s:"), 
213                              ctl->server.pollname);
214                 for (idp = ctl->oldsaved; idp; idp = idp->next)
215                     report_build(stdout, " %s", idp->id);
216                 if (!idp)
217                     report_build(stdout, GT_(" <empty>"));
218                 report_complete(stdout, "\n");
219                 uidlcount++;
220             }
221
222         if (uidlcount)
223         {
224             report_build(stdout, GT_("Scratch list of UIDs:"));
225             for (idp = scratchlist; idp; idp = idp->next)
226                 report_build(stdout, " %s", idp->id);
227             if (!idp)
228                 report_build(stdout, GT_(" <empty>"));
229             report_complete(stdout, "\n");
230         }
231     }
232 }
233 #endif /* POP3_ENABLE */
234
235 /* return a pointer to the last element of the list to help the quick,
236  * constant-time addition to the list, NOTE: this function does not dup
237  * the string, the caller must do that. */
238 /*@shared@*/ struct idlist **save_str_quick(/*@shared@*/ struct idlist **idl,
239                                /*@only@*/ char *str, flag status)
240 /* save a number/UID pair on the given UID list */
241 {
242     struct idlist **end;
243
244     /* do it nonrecursively so the list is in the right order */
245     for (end = idl; *end; end = &(*end)->next)
246         continue;
247
248     *end = (struct idlist *)xmalloc(sizeof(struct idlist));
249     (*end)->val.status.mark = status;
250     (*end)->id = (unsigned char *)str;
251     (*end)->next = NULL;
252
253     return end;
254 }
255
256 /* return the end list element for direct modification */
257 struct idlist *save_str(struct idlist **idl, const char *str, flag st)
258 {
259     return *save_str_quick(idl, str ? xstrdup(str) : NULL,
260                            st);
261 }
262
263 void free_str_list(struct idlist **idl)
264 /* free the given UID list */
265 {
266     if (*idl == (struct idlist *)NULL)
267         return;
268
269     free_str_list(&(*idl)->next);
270     free ((*idl)->id);
271     free(*idl);
272     *idl = (struct idlist *)NULL;
273 }
274
275 void save_str_pair(struct idlist **idl, const char *str1, const char *str2)
276 /* save an ID pair on the given list */
277 {
278     struct idlist **end;
279
280     /* do it nonrecursively so the list is in the right order */
281     for (end = idl; *end; end = &(*end)->next)
282         continue;
283
284     *end = (struct idlist *)xmalloc(sizeof(struct idlist));
285     (*end)->id = str1 ? xstrdup(str1) : (char *)NULL;
286     if (str2)
287         (*end)->val.id2 = xstrdup(str2);
288     else
289         (*end)->val.id2 = (char *)NULL;
290     (*end)->next = (struct idlist *)NULL;
291 }
292
293 #ifdef __UNUSED__
294 void free_str_pair_list(struct idlist **idl)
295 /* free the given ID pair list */
296 {
297     if (*idl == (struct idlist *)NULL)
298         return;
299
300     free_idpair_list(&(*idl)->next);
301     free ((*idl)->id);
302     free ((*idl)->val.id2);
303     free(*idl);
304     *idl = (struct idlist *)NULL;
305 }
306 #endif
307
308 int str_in_list(struct idlist **idl, const char *str, const flag caseblind)
309 /* is a given ID in the given list? (comparison may be caseblind) */
310 {
311     struct idlist *walk;
312     if (caseblind) {
313         for( walk = *idl; walk; walk = walk->next )
314             if( strcasecmp( str, (char *)walk->id) == 0 )
315                 return 1;
316     } else {
317         for( walk = *idl; walk; walk = walk->next )
318             if( strcmp( str, (char *)walk->id) == 0 )
319                 return 1;
320     }
321     return 0;
322 }
323
324 int str_nr_in_list( struct idlist **idl, const char *str )
325   /* return the position of str in idl */
326 {
327     int nr;
328     struct idlist *walk;
329     if ( !str )
330         return -1;
331     for( walk = *idl, nr = 0; walk; nr ++, walk = walk->next )
332         if( strcmp( str, walk->id) == 0 )
333             return nr;
334     return -1;
335 }
336
337 int str_nr_last_in_list( struct idlist **idl, const char *str)
338 /* return the last position of str in idl */
339 {
340     int nr, ret = -1;
341     struct idlist *walk;
342     if ( !str )
343         return -1;
344     for( walk = *idl, nr = 0; walk; nr ++, walk = walk->next )
345         if( strcmp( str, walk->id) == 0 )
346             ret = nr;
347     return ret;
348 }
349
350 void str_set_mark( struct idlist **idl, const char *str, const flag val)
351 /* update the mark on an of an id to given value */
352 {
353     int nr;
354     struct idlist *walk;
355     if (!str)
356         return;
357     for(walk = *idl, nr = 0; walk; nr ++, walk = walk->next)
358         if (strcmp(str, walk->id) == 0)
359             walk->val.status.mark = val;
360 }
361
362 int count_list( struct idlist **idl)
363 /* count the number of elements in the list */
364 {
365   if( !*idl )
366     return 0;
367   return 1 + count_list( &(*idl)->next );
368 }
369
370 /*@null@*/ char *str_from_nr_list(struct idlist **idl, long number)
371 /* return the number'th string in idl */
372 {
373     if( !*idl  || number < 0)
374         return 0;
375     if( number == 0 )
376         return (*idl)->id;
377     return str_from_nr_list(&(*idl)->next, number-1);
378 }
379
380
381 char *str_find(struct idlist **idl, long number)
382 /* return the id of the given number in the given list. */
383 {
384     if (*idl == (struct idlist *) 0)
385         return((char *) 0);
386     else if (number == (*idl)->val.status.num)
387         return((*idl)->id);
388     else
389         return(str_find(&(*idl)->next, number));
390 }
391
392 char *idpair_find(struct idlist **idl, const char *id)
393 /* return the id of the given id in the given list (caseblind comparison) */
394 {
395     if (*idl == (struct idlist *) 0)
396         return((char *) 0);
397     else if (strcasecmp(id, (*idl)->id) == 0)
398         return((*idl)->val.id2 ? (*idl)->val.id2 : (*idl)->id);
399     else
400         return(idpair_find(&(*idl)->next, id));
401 }
402
403 int delete_str(struct idlist **idl, long num)
404 /* delete given message from given list */
405 {
406     struct idlist       *idp;
407
408     for (idp = *idl; idp; idp = idp->next)
409         if (idp->val.status.num == num)
410         {
411             idp->val.status.mark = UID_DELETED;
412             return(1);
413         }
414     return(0);
415 }
416
417 struct idlist *copy_str_list(struct idlist *idl)
418 /* copy the given UID list */
419 {
420     struct idlist *newnode ;
421
422     if (idl == (struct idlist *)NULL)
423         return(NULL);
424     else
425     {
426         newnode = (struct idlist *)xmalloc(sizeof(struct idlist));
427         memcpy(newnode, idl, sizeof(struct idlist));
428         newnode->next = copy_str_list(idl->next);
429         return(newnode);
430     }
431 }
432
433 void append_str_list(struct idlist **idl, struct idlist **nidl)
434 /* append nidl to idl (does not copy *) */
435 {
436     if ((*nidl) == (struct idlist *)NULL || *nidl == *idl)
437         return;
438     else if ((*idl) == (struct idlist *)NULL)
439         *idl = *nidl;
440     else if ((*idl)->next == (struct idlist *)NULL)
441         (*idl)->next = *nidl;
442     else if ((*idl)->next != *nidl)
443         append_str_list(&(*idl)->next, nidl);
444 }
445
446 #ifdef POP3_ENABLE
447 void expunge_uids(struct query *ctl)
448 /* assert that all UIDs marked deleted have actually been expunged */
449 {
450     struct idlist *idl;
451
452     for (idl = ctl->newsaved; idl; idl = idl->next)
453         if (idl->val.status.mark == UID_DELETED)
454             idl->val.status.mark = UID_EXPUNGED;
455 }
456
457 void uid_swap_lists(struct query *ctl) 
458 /* finish a query */
459 {
460     /* debugging code */
461     if (ctl->server.uidl && outlevel >= O_DEBUG)
462     {
463         struct idlist *idp;
464
465         report_build(stdout, GT_("New UID list from %s:"), ctl->server.pollname);
466         for (idp = ctl->newsaved; idp; idp = idp->next)
467             report_build(stdout, " %s = %d", idp->id, idp->val.status.mark);
468         if (!idp)
469             report_build(stdout, GT_(" <empty>"));
470         report_complete(stdout, "\n");
471     }
472
473     /*
474      * Don't swap UID lists unless we've actually seen UIDLs.
475      * This is necessary in order to keep UIDL information
476      * from being heedlessly deleted later on.
477      *
478      * Older versions of fetchmail did
479      *
480      *     free_str_list(&scratchlist);
481      *
482      * after swap.  This was wrong; we need to preserve the UIDL information
483      * from unqueried hosts.  Unfortunately, not doing this means that
484      * under some circumstances UIDLs can end up being stored forever --
485      * specifically, if a user description is removed from .fetchmailrc
486      * with UIDLs from that account in .fetchids, there is no way for
487      * them to ever get garbage-collected.
488      */
489     if (ctl->newsaved)
490     {
491         /* old state of mailbox may now be irrelevant */
492         if (outlevel >= O_DEBUG)
493             report(stdout, GT_("swapping UID lists\n"));
494         free_str_list(&ctl->oldsaved);
495         ctl->oldsaved = ctl->newsaved;
496         ctl->newsaved = (struct idlist *) NULL;
497     }
498     else if (outlevel >= O_DEBUG)
499         report(stdout, GT_("not swapping UID lists, no UIDs seen this query\n"));
500 }
501
502 void write_saved_lists(struct query *hostlist, const char *idfile)
503 /* perform end-of-run write of seen-messages list */
504 {
505     long        idcount;
506     FILE        *tmpfp;
507     struct query *ctl;
508     struct idlist *idp;
509
510     /* if all lists are empty, nuke the file */
511     idcount = 0;
512     for (ctl = hostlist; ctl; ctl = ctl->next) {
513         for (idp = ctl->oldsaved; idp; idp = idp->next)
514             if (idp->val.status.mark == UID_SEEN
515                     || idp->val.status.mark == UID_DELETED)
516                 idcount++;
517     }
518
519     /* either nuke the file or write updated last-seen IDs */
520     if (!idcount && !scratchlist)
521     {
522         if (outlevel >= O_DEBUG)
523             report(stdout, GT_("Deleting fetchids file.\n"));
524         unlink(idfile);
525     }
526     else
527     {
528         if (outlevel >= O_DEBUG)
529             report(stdout, GT_("Writing fetchids file.\n"));
530         /* FIXME: do not overwrite the old idfile */
531         if ((tmpfp = fopen(idfile, "w")) != (FILE *)NULL) {
532             for (ctl = hostlist; ctl; ctl = ctl->next) {
533                 for (idp = ctl->oldsaved; idp; idp = idp->next)
534                     if (idp->val.status.mark == UID_SEEN
535                                 || idp->val.status.mark == UID_DELETED)
536                         fprintf(tmpfp, "%s@%s %s\n", 
537                             ctl->remotename, ctl->server.queryname, idp->id);
538             }
539             for (idp = scratchlist; idp; idp = idp->next)
540                 fputs(idp->id, tmpfp);
541             fclose(tmpfp);
542         }
543     }
544 }
545 #endif /* POP3_ENABLE */
546
547 /* uid.c ends here */