Rocco Rutte:
[apps/madmutt.git] / buffy.c
1 /* 
2  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
3  * 
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  * 
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  * 
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */
18
19 #if HAVE_CONFIG_H
20 # include "config.h"
21 #endif
22
23 #include "mutt.h"
24 #include "buffy.h"
25 #include "mailbox.h"
26 #include "mx.h"
27 #include "sidebar.h"
28
29 #include "mutt_curses.h"
30
31 #ifdef USE_IMAP
32 #include "imap.h"
33 #endif
34
35 #include <string.h>
36 #include <sys/stat.h>
37 #include <dirent.h>
38 #include <utime.h>
39 #include <ctype.h>
40 #include <unistd.h>
41
42 #include <stdio.h>
43
44 static time_t BuffyTime = 0;            /* last time we started checking for mail */
45 #ifdef USE_IMAP
46 static time_t ImapBuffyTime = 0;        /* last time we started checking for mail */
47 #endif
48 static short BuffyCount = 0;            /* how many boxes with new mail */
49 static short BuffyNotify = 0;           /* # of unnotified new boxes */
50
51 #ifdef BUFFY_SIZE
52
53 /* Find the last message in the file. 
54  * upon success return 0. If no message found - return -1 */
55
56 int fseek_last_message (FILE * f)
57 {
58   long int pos;
59   char buffer[BUFSIZ + 9];      /* 7 for "\n\nFrom " */
60   int bytes_read;
61   int i;                        /* Index into `buffer' for scanning.  */
62
63   memset (buffer, 0, sizeof(buffer));
64   fseek (f, 0, SEEK_END);
65   pos = ftell (f);
66
67   /* Set `bytes_read' to the size of the last, probably partial, buffer; 0 <
68    * `bytes_read' <= `BUFSIZ'.  */
69   bytes_read = pos % BUFSIZ;
70   if (bytes_read == 0)
71     bytes_read = BUFSIZ;
72   /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
73    * reads will be on block boundaries, which might increase efficiency.  */
74   while ((pos -= bytes_read) >= 0)
75   {
76     /* we save in the buffer at the end the first 7 chars from the last read */
77     strncpy (buffer + BUFSIZ, buffer, 5+2); /* 2 == 2 * mutt_strlen(CRLF) */
78     fseek (f, pos, SEEK_SET);
79     bytes_read = fread (buffer, sizeof (char), bytes_read, f);
80     if (bytes_read == -1)
81       return -1;
82     for (i = bytes_read; --i >= 0;)
83       if (!mutt_strncmp (buffer + i, "\n\nFrom ", mutt_strlen ("\n\nFrom ")))
84       {                         /* found it - go to the beginning of the From */
85         fseek (f, pos + i + 2, SEEK_SET);
86         return 0;
87       }
88     bytes_read = BUFSIZ;
89   }
90
91   /* here we are at the beginning of the file */
92   if (!mutt_strncmp ("From ", buffer, 5))
93   {
94     fseek (f, 0, 0);
95     return (0);
96   }
97
98   return (-1);
99 }
100
101 /* Return 1 if the last message is new */
102 int test_last_status_new (FILE * f)
103 {
104   HEADER *hdr;
105   ENVELOPE* tmp_envelope;
106   int result = 0;
107
108   if (fseek_last_message (f) == -1)
109     return (0);
110
111   hdr = mutt_new_header ();
112   tmp_envelope = mutt_read_rfc822_header (f, hdr, 0, 0);
113   if (!(hdr->read || hdr->old))
114     result = 1;
115
116   mutt_free_envelope(&tmp_envelope);
117   mutt_free_header (&hdr);
118
119   return result;
120 }
121
122 int test_new_folder (const char *path)
123 {
124   FILE *f;
125   int rc = 0;
126   int typ;
127
128   typ = mx_get_magic (path);
129
130   if (typ != M_MBOX && typ != M_MMDF)
131     return 0;
132
133   if ((f = fopen (path, "rb")))
134   {
135     rc = test_last_status_new (f);
136     fclose (f);
137   }
138
139   return rc;
140 }
141
142 BUFFY *mutt_find_mailbox (const char *path)
143 {
144   BUFFY *tmp = NULL;
145   struct stat sb;
146   struct stat tmp_sb;
147   
148   if (stat (path,&sb) != 0)
149     return NULL;
150
151   for (tmp = Incoming; tmp; tmp = tmp->next)
152   {
153     if (stat (tmp->path,&tmp_sb) ==0 && 
154         sb.st_dev == tmp_sb.st_dev && sb.st_ino == tmp_sb.st_ino)
155       break;
156   }
157   return tmp;
158 }
159
160 void mutt_update_mailbox (BUFFY * b)
161 {
162   struct stat sb;
163
164   if (!b)
165     return;
166
167   if (stat (b->path, &sb) == 0)
168     b->size = (long) sb.st_size;
169   else
170     b->size = 0;
171   return;
172 }
173 #endif
174
175 int mutt_parse_mailboxes (BUFFER *path, BUFFER *s, unsigned long data, BUFFER *err)
176 {
177   BUFFY **tmp,*tmp1;
178   char buf[_POSIX_PATH_MAX];
179 #ifdef BUFFY_SIZE
180   struct stat sb;
181 #endif /* BUFFY_SIZE */
182
183   while (MoreArgs (s))
184   {
185     mutt_extract_token (path, s, 0);
186     strfcpy (buf, path->data, sizeof (buf));
187
188     if(data == M_UNMAILBOXES && mutt_strcmp(buf,"*") == 0)
189     {
190       for (tmp = &Incoming; *tmp;)
191       {
192         FREE (&((*tmp)->path));
193         tmp1=(*tmp)->next;
194         FREE (tmp);
195         *tmp=tmp1;
196       }
197       return 0;
198     }
199
200     mutt_expand_path (buf, sizeof (buf));
201
202     /* Skip empty tokens. */
203     if(!*buf) continue;
204
205     /* simple check to avoid duplicates */
206     for (tmp = &Incoming; *tmp; tmp = &((*tmp)->next))
207     {
208       if (mutt_strcmp (buf, (*tmp)->path) == 0)
209         break;
210     }
211
212     if(data == M_UNMAILBOXES)
213     {
214       if(*tmp)
215       {
216         FREE (&((*tmp)->path));
217         tmp1=(*tmp)->next;
218         FREE (tmp);
219         *tmp=tmp1;
220       }
221       continue;
222     }
223
224     if (!*tmp)
225     {
226       *tmp = (BUFFY *) safe_calloc (1, sizeof (BUFFY));
227       (*tmp)->path = safe_strdup (buf);
228       (*tmp)->next = NULL;
229       /* it is tempting to set magic right here */
230       (*tmp)->magic = 0;
231       
232     }
233
234     (*tmp)->new = 0;
235     (*tmp)->notified = 1;
236     (*tmp)->newly_created = 0;
237
238 #ifdef BUFFY_SIZE
239     /* for buffy_size, it is important that if the folder is new (tested by
240      * reading it), the size is set to 0 so that later when we check we see
241      * that it increased .  without buffy_size we probably don't care.
242      */
243     if (stat ((*tmp)->path, &sb) == 0 && !test_new_folder ((*tmp)->path))
244     {
245       /* some systems out there don't have an off_t type */
246       (*tmp)->size = (long) sb.st_size;
247     }
248     else
249       (*tmp)->size = 0;
250 #endif /* BUFFY_SIZE */
251   }
252   return 0;
253 }
254
255 #ifdef BUFFY_SIZE
256 /* people use buffy_size on systems where modified time attributes are BADLY
257  * broken. Ignore them.
258  */
259 #define STAT_CHECK (sb.st_size > tmp->size)
260 #else
261 #define STAT_CHECK (sb.st_mtime > sb.st_atime || (tmp->newly_created && sb.st_ctime == sb.st_mtime && sb.st_ctime == sb.st_atime))
262 #endif /* BUFFY_SIZE */
263
264 /* values for force:
265  * 0    don't force any checks + update sidebar
266  * 1    force all checks + update sidebar
267  * 2    force all checks + _don't_ update sidebar
268  */
269 int mutt_buffy_check (int force)
270 {
271   BUFFY *tmp;
272   struct stat sb;
273   struct dirent *de;
274   DIR *dirp;
275   char path[_POSIX_PATH_MAX];
276   struct stat contex_sb;
277   time_t now, last1, last2;
278   CONTEXT *ctx;
279 #ifdef USE_IMAP
280   /* update postponed count as well, on force */
281   if (force != 0)
282     mutt_update_num_postponed ();
283 #endif
284
285   /* fastest return if there are no mailboxes */
286   if (!Incoming)
287     return 0;
288   now = time (NULL);
289   if (force == 0 && (now - BuffyTime < BuffyTimeout)
290 #ifdef USE_IMAP
291       && (now - ImapBuffyTime < ImapBuffyTimeout))
292 #else
293       )
294 #endif
295     return BuffyCount;
296
297   last1 = BuffyTime;
298   if (force != 0 || now - BuffyTime >= BuffyTimeout)
299     BuffyTime = now;
300 #ifdef USE_IMAP
301   last2 = ImapBuffyTime;
302   if (force != 0 || now - ImapBuffyTime >= ImapBuffyTimeout)
303     ImapBuffyTime = now;
304 #endif
305   BuffyCount = 0;
306   BuffyNotify = 0;
307
308 #ifdef USE_IMAP
309   if (!Context || Context->magic != M_IMAP)
310 #endif
311 #ifdef USE_POP
312   if (!Context || Context->magic != M_POP)
313 #endif
314 #ifdef USE_NNTP
315   if (!Context || Context->magic != M_NNTP)
316 #endif
317   /* check device ID and serial number instead of comparing paths */
318   if (!Context || !Context->path || stat (Context->path, &contex_sb) != 0)
319   {
320     contex_sb.st_dev=0;
321     contex_sb.st_ino=0;
322   }
323   
324   for (tmp = Incoming; tmp; tmp = tmp->next)
325   {
326 #ifdef USE_IMAP
327     if (mx_is_imap (tmp->path))
328       tmp->magic = M_IMAP;
329     else
330 #endif
331 #ifdef USE_POP
332     if (mx_is_pop (tmp->path))
333       tmp->magic = M_POP;
334     else
335 #endif
336 #ifdef USE_NNTP
337     if ((tmp->magic == M_NNTP) || mx_is_nntp (tmp->path))
338       tmp->magic = M_NNTP;
339     else
340 #endif
341     if (stat (tmp->path, &sb) != 0 || sb.st_size == 0 ||
342        (!tmp->magic && (tmp->magic = mx_get_magic (tmp->path)) <= 0))
343     {
344       /* if the mailbox still doesn't exist, set the newly created flag to
345        * be ready for when it does. */
346       tmp->newly_created = 1;
347       tmp->magic = 0;
348 #ifdef BUFFY_SIZE
349       tmp->size = 0;
350 #endif
351       continue;
352     }
353
354     /* check to see if the folder is the currently selected folder
355      * before polling */
356     if (!Context || !Context->path ||
357          (
358            (0
359 #ifdef USE_IMAP
360             || tmp->magic == M_IMAP
361 #endif
362 #ifdef USE_POP
363             || tmp->magic == M_POP
364 #endif
365 #ifdef USE_NNTP
366             || tmp->magic == M_NNTP
367 #endif
368            ) ? mutt_strcmp (tmp->path, Context->path) :
369                (sb.st_dev != contex_sb.st_dev || sb.st_ino != contex_sb.st_ino)
370          )
371        )
372     {
373       switch (tmp->magic)
374       {
375       case M_MBOX:
376       case M_MMDF:
377         /* only check on force or $mail_check reached */
378         if (force != 0 || (now - last1 >= BuffyTimeout)) {
379           if (SidebarWidth == 0 || !option (OPTMBOXPANE)) {
380             if (STAT_CHECK) {
381               BuffyCount++;
382               tmp->new = 1;
383             }
384 #ifdef BUFFY_SIZE
385             else
386             {
387               /* some other program has deleted mail from the folder */
388               tmp->size = (long) sb.st_size;
389             }
390 #endif
391           } else if (SidebarWidth > 0 && option (OPTMBOXPANE) && 
392                     (STAT_CHECK || tmp->msgcount == 0)) {
393             /* sidebar visible */
394             BuffyCount++;
395             if ((ctx = mx_open_mailbox (tmp->path, M_READONLY | M_QUIET | M_NOSORT, NULL)) != NULL) {
396               tmp->msgcount = ctx->msgcount;
397               tmp->new = ctx->new;
398               tmp->msg_unread = ctx->new;       /* for sidebar, wtf? */
399               tmp->msg_flagged = ctx->flagged;
400               mx_close_mailbox (ctx, 0);
401             }
402           }
403           if (tmp->newly_created &&
404               (sb.st_ctime != sb.st_mtime || sb.st_ctime != sb.st_atime))
405             tmp->newly_created = 0;
406         } else if (tmp->new > 0)
407           BuffyCount++;
408         break;
409
410       case M_MAILDIR:
411         /* only check on force or $mail_check reached */
412         if (force != 0 || (now - last1 >= BuffyTimeout)) {
413           snprintf (path, sizeof (path), "%s/new", tmp->path);
414           if ((dirp = opendir (path)) == NULL)
415           {
416             tmp->magic = 0;
417             break;
418           }
419           tmp->new = 0;
420           tmp->msg_unread = 0;
421           tmp->msgcount = 0;
422           while ((de = readdir (dirp)) != NULL)
423           {
424             char *p;
425             if (*de->d_name != '.' && 
426                 (!(p = strstr (de->d_name, ":2,")) || !strchr (p + 3, 'T')))
427             {
428               /* one new and undeleted message is enough */
429               if (tmp->new == 0)
430               {
431                 BuffyCount++;
432                 tmp->new = 1;
433                 if (SidebarWidth == 0 || !option (OPTMBOXPANE))
434                   /* if sidebar invisible -> done */
435                   break;
436               }
437               tmp->msgcount++;
438               tmp->msg_unread++;
439               tmp->new++;
440             }
441           }
442           closedir (dirp);
443
444           if (SidebarWidth > 0 && option (OPTMBOXPANE))
445           {
446             /* only count total mail if sidebar visible */
447             snprintf (path, sizeof (path), "%s/cur", tmp->path);
448             if ((dirp = opendir (path)) == NULL)
449             {
450               tmp->magic = 0;
451               break;
452             }
453             tmp->msg_flagged = 0;
454             while ((de = readdir (dirp)) != NULL)
455             {
456               char *p;
457               if (*de->d_name != '.' && (p = strstr (de->d_name, ":2,")) != NULL) {
458                 if (!strchr (p + 3, 'T'))
459                   tmp->msgcount++;
460                 if (strchr (p + 3, 'F'))
461                   tmp->msg_flagged++;
462               }
463             }
464             closedir (dirp);
465           }
466         } else if (tmp->new > 0)
467           /* keep current stats if !force and !$mail_check reached */
468           BuffyCount++;
469         break;
470
471       case M_MH:
472         /* only check on force or $mail_check reached */
473         if (force != 0 || (now - last1 >= BuffyTimeout)) {
474           if ((tmp->new = mh_buffy (tmp->path)) > 0)
475             BuffyCount++;
476           if (SidebarWidth > 0 && option (OPTMBOXPANE))
477           {
478             DIR *dp;
479             struct dirent *de;
480             if ((dp = opendir (path)) == NULL)
481               break;
482             tmp->new = 0;
483             tmp->msgcount = 0;
484             tmp->msg_unread = 0;
485             while ((de = readdir (dp)))
486             {
487               if (mh_valid_message (de->d_name))
488               {
489                 tmp->msgcount++;
490                 tmp->msg_unread++;
491                 tmp->new++;
492               }
493             }
494             closedir (dp);
495           }
496         } else if (tmp->new > 0)
497           /* keep current stats if !force and !$mail_check reached */
498           BuffyCount++;
499         break;
500
501 #ifdef USE_IMAP
502       case M_IMAP:
503         /* only check on force or $imap_mail_check reached */
504         if (force != 0 || (now - last2 >= ImapBuffyTimeout)) {
505           tmp->msgcount = imap_mailbox_check (tmp->path, 0);
506           if ((tmp->new = imap_mailbox_check (tmp->path, 1)) > 0) {
507             BuffyCount++;
508             tmp->msg_unread = tmp->new; /* for sidebar; wtf? */
509           }
510           else {
511             tmp->new = 0;
512             tmp->msg_unread = 0;
513           }
514         } else if (tmp->new > 0)
515           /* keep current stats if !force and !$imap_mail_check reached */
516           BuffyCount++;
517         break;
518 #endif
519
520 #ifdef USE_POP
521       case M_POP:
522         break;
523 #endif
524
525 #ifdef USE_NNTP
526       case M_NNTP:
527         break;
528 #endif
529       }
530     }
531 #ifdef BUFFY_SIZE
532     else if (Context && Context->path)
533       tmp->size = (long) sb.st_size;    /* update the size */
534 #endif
535
536     if (!tmp->new)
537       tmp->notified = 0;
538     else if (!tmp->notified)
539       BuffyNotify++;
540     tmp->has_new = tmp->new > 0;
541   }
542   if (BuffyCount > 0 && force != 2)
543     draw_sidebar (CurrentMenu);
544   return (BuffyCount);
545 }
546
547 int mutt_buffy_list (void)
548 {
549   BUFFY *tmp;
550   char path[_POSIX_PATH_MAX];
551   char buffylist[160];
552   int pos;
553   int first;
554   int have_unnotified = BuffyNotify;
555
556   if (option (OPTFORCEBUFFYCHECK))
557     mutt_buffy_check (1);
558
559   pos = 0;
560   first = 1;
561   buffylist[0] = 0;
562   pos += strlen (strncat (buffylist, _("New mail in "), sizeof (buffylist) - 1 - pos)); /* __STRNCAT_CHECKED__ */
563   for (tmp = Incoming; tmp; tmp = tmp->next)
564   {
565     /* Is there new mail in this mailbox? */
566     if (!tmp->new || (have_unnotified && tmp->notified))
567       continue;
568
569     strfcpy (path, tmp->path, sizeof (path));
570     mutt_pretty_mailbox (path);
571     
572     if (!first && pos + strlen (path) >= COLS - 7)
573       break;
574     
575     if (!first)
576       pos += strlen (strncat(buffylist + pos, ", ", sizeof(buffylist)-1-pos)); /* __STRNCAT_CHECKED__ */
577
578     /* Prepend an asterisk to mailboxes not already notified */
579     if (!tmp->notified)
580     {
581       /* pos += strlen (strncat(buffylist + pos, "*", sizeof(buffylist)-1-pos));  __STRNCAT_CHECKED__ */
582       tmp->notified = 1;
583       BuffyNotify--;
584     }
585     pos += strlen (strncat(buffylist + pos, path, sizeof(buffylist)-1-pos)); /* __STRNCAT_CHECKED__ */
586     first = 0;
587   }
588   if (!first && tmp)
589   {
590     strncat (buffylist + pos, ", ...", sizeof (buffylist) - 1 - pos); /* __STRNCAT_CHECKED__ */
591   }
592   if (!first)
593   {
594     /* on new mail: redraw sidebar */
595     draw_sidebar (CurrentMenu);
596     mutt_message ("%s", buffylist);
597     return (1);
598   }
599   /* there were no mailboxes needing to be notified, so clean up since 
600    * BuffyNotify has somehow gotten out of sync
601    */
602   BuffyNotify = 0;
603   return (0);
604 }
605
606 int mutt_buffy_notify (void)
607 {
608   if (mutt_buffy_check (0) && BuffyNotify)
609   {
610     return (mutt_buffy_list ());
611   }
612   return (0);
613 }
614
615 /* 
616  * mutt_buffy() -- incoming folders completion routine
617  *
618  * given a folder name, this routine gives the next incoming folder with new
619  * new mail.
620  */
621 void mutt_buffy (char *s, size_t slen)
622 {
623   int count;
624   BUFFY *tmp = Incoming;
625
626   mutt_expand_path (s, _POSIX_PATH_MAX);
627   switch (mutt_buffy_check (0))
628   {
629   case 0:
630
631     *s = '\0';
632     break;
633
634   case 1:
635
636     while (tmp && !tmp->new)
637       tmp = tmp->next;
638     if (!tmp)
639     {
640       *s = '\0';
641       mutt_buffy_check (1); /* buffy was wrong - resync things */
642       break;
643     }
644     strfcpy (s, tmp->path, slen);
645     mutt_pretty_mailbox (s);
646     break;
647
648   default:
649     
650     count = 0;
651     while (count < 3)
652     {
653       if (mutt_strcmp (s, tmp->path) == 0)
654         count++;
655       else if (count && tmp->new)
656         break;
657       tmp = tmp->next;
658       if (!tmp)
659       {
660         tmp = Incoming;
661         count++;
662       }
663     }
664     if (count >= 3)
665     {
666       *s = '\0';
667       mutt_buffy_check (1); /* buffy was wrong - resync things */
668       break;
669     }
670     strfcpy (s, tmp->path, slen);
671     mutt_pretty_mailbox (s);
672     break;
673   }
674 }