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