Nico Golde:
[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;
278   CONTEXT *ctx;
279 #ifdef USE_IMAP
280   time_t last2;
281   /* update postponed count as well, on force */
282   if (force != 0)
283     mutt_update_num_postponed ();
284 #endif
285
286   /* fastest return if there are no mailboxes */
287   if (!Incoming)
288     return 0;
289   now = time (NULL);
290   if (force == 0 && (now - BuffyTime < BuffyTimeout)
291 #ifdef USE_IMAP
292       && (now - ImapBuffyTime < ImapBuffyTimeout))
293 #else
294       )
295 #endif
296     return BuffyCount;
297
298   last1 = BuffyTime;
299   if (force != 0 || now - BuffyTime >= BuffyTimeout)
300     BuffyTime = now;
301 #ifdef USE_IMAP
302   last2 = ImapBuffyTime;
303   if (force != 0 || now - ImapBuffyTime >= ImapBuffyTimeout)
304     ImapBuffyTime = now;
305 #endif
306   BuffyCount = 0;
307   BuffyNotify = 0;
308
309 #ifdef USE_IMAP
310   if (!Context || Context->magic != M_IMAP)
311 #endif
312 #ifdef USE_POP
313   if (!Context || Context->magic != M_POP)
314 #endif
315 #ifdef USE_NNTP
316   if (!Context || Context->magic != M_NNTP)
317 #endif
318   /* check device ID and serial number instead of comparing paths */
319   if (!Context || !Context->path || stat (Context->path, &contex_sb) != 0)
320   {
321     contex_sb.st_dev=0;
322     contex_sb.st_ino=0;
323   }
324   
325   for (tmp = Incoming; tmp; tmp = tmp->next)
326   {
327 #ifdef USE_IMAP
328     if (mx_is_imap (tmp->path))
329       tmp->magic = M_IMAP;
330     else
331 #endif
332 #ifdef USE_POP
333     if (mx_is_pop (tmp->path))
334       tmp->magic = M_POP;
335     else
336 #endif
337 #ifdef USE_NNTP
338     if ((tmp->magic == M_NNTP) || mx_is_nntp (tmp->path))
339       tmp->magic = M_NNTP;
340     else
341 #endif
342     if (stat (tmp->path, &sb) != 0 || sb.st_size == 0 ||
343        (!tmp->magic && (tmp->magic = mx_get_magic (tmp->path)) <= 0))
344     {
345       /* if the mailbox still doesn't exist, set the newly created flag to
346        * be ready for when it does. */
347       tmp->newly_created = 1;
348       tmp->magic = 0;
349 #ifdef BUFFY_SIZE
350       tmp->size = 0;
351 #endif
352       continue;
353     }
354
355     /* check to see if the folder is the currently selected folder
356      * before polling */
357     if (!Context || !Context->path ||
358          (
359            (0
360 #ifdef USE_IMAP
361             || tmp->magic == M_IMAP
362 #endif
363 #ifdef USE_POP
364             || tmp->magic == M_POP
365 #endif
366 #ifdef USE_NNTP
367             || tmp->magic == M_NNTP
368 #endif
369            ) ? mutt_strcmp (tmp->path, Context->path) :
370                (sb.st_dev != contex_sb.st_dev || sb.st_ino != contex_sb.st_ino)
371          )
372        )
373     {
374       switch (tmp->magic)
375       {
376       case M_MBOX:
377       case M_MMDF:
378         /* only check on force or $mail_check reached */
379         if (force != 0 || (now - last1 >= BuffyTimeout)) {
380           if (SidebarWidth == 0 || !option (OPTMBOXPANE)) {
381             if (STAT_CHECK) {
382               BuffyCount++;
383               tmp->new = 1;
384             }
385 #ifdef BUFFY_SIZE
386             else
387             {
388               /* some other program has deleted mail from the folder */
389               tmp->size = (long) sb.st_size;
390             }
391 #endif
392           } else if (SidebarWidth > 0 && option (OPTMBOXPANE) && 
393                     (STAT_CHECK || tmp->msgcount == 0)) {
394             /* sidebar visible */
395             BuffyCount++;
396             if ((ctx = mx_open_mailbox (tmp->path, M_READONLY | M_QUIET | M_NOSORT, NULL)) != NULL) {
397               tmp->msgcount = ctx->msgcount;
398               tmp->new = ctx->new;
399               tmp->msg_unread = ctx->new;       /* for sidebar, wtf? */
400               tmp->msg_flagged = ctx->flagged;
401               mx_close_mailbox (ctx, 0);
402             }
403           }
404           if (tmp->newly_created &&
405               (sb.st_ctime != sb.st_mtime || sb.st_ctime != sb.st_atime))
406             tmp->newly_created = 0;
407         } else if (tmp->new > 0)
408           BuffyCount++;
409         break;
410
411       case M_MAILDIR:
412         /* only check on force or $mail_check reached */
413         if (force != 0 || (now - last1 >= BuffyTimeout)) {
414           snprintf (path, sizeof (path), "%s/new", tmp->path);
415           if ((dirp = opendir (path)) == NULL)
416           {
417             tmp->magic = 0;
418             break;
419           }
420           tmp->new = 0;
421           tmp->msg_unread = 0;
422           tmp->msgcount = 0;
423           while ((de = readdir (dirp)) != NULL)
424           {
425             char *p;
426             if (*de->d_name != '.' && 
427                 (!(p = strstr (de->d_name, ":2,")) || !strchr (p + 3, 'T')))
428             {
429               /* one new and undeleted message is enough */
430               if (tmp->new == 0)
431               {
432                 BuffyCount++;
433                 tmp->new = 1;
434                 if (SidebarWidth == 0 || !option (OPTMBOXPANE))
435                   /* if sidebar invisible -> done */
436                   break;
437               }
438               tmp->msgcount++;
439               tmp->msg_unread++;
440               tmp->new++;
441             }
442           }
443           closedir (dirp);
444
445           if (SidebarWidth > 0 && option (OPTMBOXPANE))
446           {
447             /* only count total mail if sidebar visible */
448             snprintf (path, sizeof (path), "%s/cur", tmp->path);
449             if ((dirp = opendir (path)) == NULL)
450             {
451               tmp->magic = 0;
452               break;
453             }
454             tmp->msg_flagged = 0;
455             while ((de = readdir (dirp)) != NULL)
456             {
457               char *p;
458               if (*de->d_name != '.' && (p = strstr (de->d_name, ":2,")) != NULL) {
459                 if (!strchr (p + 3, 'T'))
460                   tmp->msgcount++;
461                 if (strchr (p + 3, 'F'))
462                   tmp->msg_flagged++;
463               }
464             }
465             closedir (dirp);
466           }
467         } else if (tmp->new > 0)
468           /* keep current stats if !force and !$mail_check reached */
469           BuffyCount++;
470         break;
471
472       case M_MH:
473         /* only check on force or $mail_check reached */
474         if (force != 0 || (now - last1 >= BuffyTimeout)) {
475           if ((tmp->new = mh_buffy (tmp->path)) > 0)
476             BuffyCount++;
477           if (SidebarWidth > 0 && option (OPTMBOXPANE))
478           {
479             DIR *dp;
480             struct dirent *de;
481             if ((dp = opendir (path)) == NULL)
482               break;
483             tmp->new = 0;
484             tmp->msgcount = 0;
485             tmp->msg_unread = 0;
486             while ((de = readdir (dp)))
487             {
488               if (mh_valid_message (de->d_name))
489               {
490                 tmp->msgcount++;
491                 tmp->msg_unread++;
492                 tmp->new++;
493               }
494             }
495             closedir (dp);
496           }
497         } else if (tmp->new > 0)
498           /* keep current stats if !force and !$mail_check reached */
499           BuffyCount++;
500         break;
501
502 #ifdef USE_IMAP
503       case M_IMAP:
504         /* only check on force or $imap_mail_check reached */
505         if (force != 0 || (now - last2 >= ImapBuffyTimeout)) {
506           tmp->msgcount = imap_mailbox_check (tmp->path, 0);
507           if ((tmp->new = imap_mailbox_check (tmp->path, 1)) > 0) {
508             BuffyCount++;
509             tmp->msg_unread = tmp->new; /* for sidebar; wtf? */
510           }
511           else {
512             tmp->new = 0;
513             tmp->msg_unread = 0;
514           }
515         } else if (tmp->new > 0)
516           /* keep current stats if !force and !$imap_mail_check reached */
517           BuffyCount++;
518         break;
519 #endif
520
521 #ifdef USE_POP
522       case M_POP:
523         break;
524 #endif
525
526 #ifdef USE_NNTP
527       case M_NNTP:
528         break;
529 #endif
530       }
531     }
532 #ifdef BUFFY_SIZE
533     else if (Context && Context->path)
534       tmp->size = (long) sb.st_size;    /* update the size */
535 #endif
536
537     if (tmp->new <= 0)
538       tmp->notified = 0;
539     else if (!tmp->notified)
540       BuffyNotify++;
541     tmp->has_new = tmp->new > 0;
542   }
543   if (BuffyCount > 0 && force != 2)
544     draw_sidebar (CurrentMenu);
545   return (BuffyCount);
546 }
547
548 int mutt_buffy_list (void)
549 {
550   BUFFY *tmp;
551   char path[_POSIX_PATH_MAX];
552   char buffylist[160];
553   int pos;
554   int first;
555   int have_unnotified = BuffyNotify;
556
557   if (option (OPTFORCEBUFFYCHECK))
558     mutt_buffy_check (1);
559
560   pos = 0;
561   first = 1;
562   buffylist[0] = 0;
563   pos += strlen (strncat (buffylist, _("New mail in "), sizeof (buffylist) - 1 - pos)); /* __STRNCAT_CHECKED__ */
564   for (tmp = Incoming; tmp; tmp = tmp->next)
565   {
566     /* Is there new mail in this mailbox? */
567     if (tmp->new <= 0 || (have_unnotified && tmp->notified))
568       continue;
569
570     strfcpy (path, tmp->path, sizeof (path));
571     mutt_pretty_mailbox (path);
572     
573     if (!first && pos + strlen (path) >= COLS - 7)
574       break;
575     
576     if (!first)
577       pos += strlen (strncat(buffylist + pos, ", ", sizeof(buffylist)-1-pos)); /* __STRNCAT_CHECKED__ */
578
579     /* Prepend an asterisk to mailboxes not already notified */
580     if (!tmp->notified)
581     {
582       /* pos += strlen (strncat(buffylist + pos, "*", sizeof(buffylist)-1-pos));  __STRNCAT_CHECKED__ */
583       tmp->notified = 1;
584       BuffyNotify--;
585     }
586     pos += strlen (strncat(buffylist + pos, path, sizeof(buffylist)-1-pos)); /* __STRNCAT_CHECKED__ */
587     first = 0;
588   }
589   if (!first && tmp)
590   {
591     strncat (buffylist + pos, ", ...", sizeof (buffylist) - 1 - pos); /* __STRNCAT_CHECKED__ */
592   }
593   if (!first)
594   {
595     /* on new mail: redraw sidebar */
596     draw_sidebar (CurrentMenu);
597     mutt_message ("%s", buffylist);
598     return (1);
599   }
600   /* there were no mailboxes needing to be notified, so clean up since 
601    * BuffyNotify has somehow gotten out of sync
602    */
603   BuffyNotify = 0;
604   return (0);
605 }
606
607 int mutt_buffy_notify (void)
608 {
609   if (mutt_buffy_check (0) && BuffyNotify)
610   {
611     return (mutt_buffy_list ());
612   }
613   return (0);
614 }
615
616 /* 
617  * mutt_buffy() -- incoming folders completion routine
618  *
619  * given a folder name, this routine gives the next incoming folder with new
620  * new mail.
621  */
622 void mutt_buffy (char *s, size_t slen)
623 {
624   int count;
625   BUFFY *tmp = Incoming;
626
627   mutt_expand_path (s, _POSIX_PATH_MAX);
628   switch (mutt_buffy_check (0))
629   {
630   case 0:
631
632     *s = '\0';
633     break;
634
635   case 1:
636
637     while (tmp && tmp->new <= 0)
638       tmp = tmp->next;
639     if (!tmp)
640     {
641       *s = '\0';
642       mutt_buffy_check (1); /* buffy was wrong - resync things */
643       break;
644     }
645     strfcpy (s, tmp->path, slen);
646     mutt_pretty_mailbox (s);
647     break;
648
649   default:
650     
651     count = 0;
652     while (count < 3)
653     {
654       if (mutt_strcmp (s, tmp->path) == 0)
655         count++;
656       else if (count && tmp->new > 0)
657         break;
658       tmp = tmp->next;
659       if (!tmp)
660       {
661         tmp = Incoming;
662         count++;
663       }
664     }
665     if (count >= 3)
666     {
667       *s = '\0';
668       mutt_buffy_check (1); /* buffy was wrong - resync things */
669       break;
670     }
671     strfcpy (s, tmp->path, slen);
672     mutt_pretty_mailbox (s);
673     break;
674   }
675 }