Rocco Rutte:
[apps/madmutt.git] / buffy.c
1 /*
2  * Copyright notice from original mutt:
3  * Copyright (C) 1996-2000 Michael R. Elkins <me@mutt.org>
4  *
5  * Parts were written/modified by:
6  * Rocco Rutte <pdmef@cs.tu-berlin.de>
7  *
8  * This file is part of mutt-ng, see http://www.muttng.org/.
9  * It's licensed under the GNU General Public License,
10  * please see the file GPL in the top level source directory.
11  */
12
13 #if HAVE_CONFIG_H
14 # include "config.h"
15 #endif
16
17 #include "mutt.h"
18 #include "buffy.h"
19 #include "mailbox.h"
20 #include "mx.h"
21 #include "sidebar.h"
22
23 #include "mutt_curses.h"
24
25 #ifdef USE_IMAP
26 #include "imap.h"
27 #endif
28
29 #include "lib/mem.h"
30 #include "lib/intl.h"
31
32 #include <string.h>
33 #include <sys/stat.h>
34 #include <dirent.h>
35 #include <utime.h>
36 #include <ctype.h>
37 #include <unistd.h>
38
39 #include <stdio.h>
40
41 static time_t BuffyTime = 0;    /* last time we started checking for mail */
42
43 #ifdef USE_IMAP
44 static time_t ImapBuffyTime = 0;        /* last time we started checking for mail */
45 #endif
46 static short BuffyCount = 0;    /* how many boxes with new mail */
47 static short BuffyNotify = 0;   /* # of unnotified new boxes */
48
49 #ifdef BUFFY_SIZE
50
51 /* Find the last message in the file. 
52  * upon success return 0. If no message found - return -1 */
53
54 int fseek_last_message (FILE * f)
55 {
56   long int pos;
57   char buffer[BUFSIZ + 9];      /* 7 for "\n\nFrom " */
58   int bytes_read;
59   int i;                        /* Index into `buffer' for scanning.  */
60
61   memset (buffer, 0, sizeof (buffer));
62   fseek (f, 0, SEEK_END);
63   pos = ftell (f);
64
65   /* Set `bytes_read' to the size of the last, probably partial, buffer; 0 <
66    * `bytes_read' <= `BUFSIZ'.  */
67   bytes_read = pos % BUFSIZ;
68   if (bytes_read == 0)
69     bytes_read = BUFSIZ;
70   /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
71    * reads will be on block boundaries, which might increase efficiency.  */
72   while ((pos -= bytes_read) >= 0) {
73     /* we save in the buffer at the end the first 7 chars from the last read */
74     strncpy (buffer + BUFSIZ, buffer, 5 + 2);   /* 2 == 2 * mutt_strlen(CRLF) */
75     fseek (f, pos, SEEK_SET);
76     bytes_read = fread (buffer, sizeof (char), bytes_read, f);
77     if (bytes_read == -1)
78       return -1;
79     for (i = bytes_read; --i >= 0;)
80       if (!mutt_strncmp (buffer + i, "\n\nFrom ", mutt_strlen ("\n\nFrom "))) { /* found it - go to the beginning of the From */
81         fseek (f, pos + i + 2, SEEK_SET);
82         return 0;
83       }
84     bytes_read = BUFSIZ;
85   }
86
87   /* here we are at the beginning of the file */
88   if (!mutt_strncmp ("From ", buffer, 5)) {
89     fseek (f, 0, 0);
90     return (0);
91   }
92
93   return (-1);
94 }
95
96 /* Return 1 if the last message is new */
97 int test_last_status_new (FILE * f)
98 {
99   HEADER *hdr;
100   ENVELOPE *tmp_envelope;
101   int result = 0;
102
103   if (fseek_last_message (f) == -1)
104     return (0);
105
106   hdr = mutt_new_header ();
107   tmp_envelope = mutt_read_rfc822_header (f, hdr, 0, 0);
108   if (!(hdr->read || hdr->old))
109     result = 1;
110
111   mutt_free_envelope (&tmp_envelope);
112   mutt_free_header (&hdr);
113
114   return result;
115 }
116
117 int test_new_folder (const char *path)
118 {
119   FILE *f;
120   int rc = 0;
121   int typ;
122
123   typ = mx_get_magic (path);
124
125   if (typ != M_MBOX && typ != M_MMDF)
126     return 0;
127
128   if ((f = fopen (path, "rb"))) {
129     rc = test_last_status_new (f);
130     fclose (f);
131   }
132
133   return rc;
134 }
135
136 BUFFY *mutt_find_mailbox (const char *path)
137 {
138   BUFFY *tmp = NULL;
139   struct stat sb;
140   struct stat tmp_sb;
141
142   if (stat (path, &sb) != 0)
143     return NULL;
144
145   for (tmp = Incoming; tmp; tmp = tmp->next) {
146     if (stat (tmp->path, &tmp_sb) == 0 &&
147         sb.st_dev == tmp_sb.st_dev && sb.st_ino == tmp_sb.st_ino)
148       break;
149   }
150   return tmp;
151 }
152
153 void mutt_update_mailbox (BUFFY * b)
154 {
155   struct stat sb;
156
157   if (!b)
158     return;
159
160   if (stat (b->path, &sb) == 0)
161     b->size = (long) sb.st_size;
162   else
163     b->size = 0;
164   return;
165 }
166 #endif
167
168 /* func to free buffy for list_del() */
169 static void buffy_free (void** p) {
170   FREE(&(*((BUFFY**) p))->path);
171   FREE(p);
172 }
173
174 int buffy_lookup (const char* path) {
175   int i = 0;
176   if (list_empty(Incoming) || !path || !*path)
177     return (-1);
178   for (i = 0; i < Incoming->length; i++) {
179     if (mutt_strcmp (((BUFFY*) Incoming->data[i])->path, path) == 0)
180       return (i);
181   }
182   return (-1);
183 }
184
185 int mutt_parse_mailboxes (BUFFER * path, BUFFER * s, unsigned long data,
186                           BUFFER * err)
187 {
188   BUFFY* tmp;
189   char buf[_POSIX_PATH_MAX];
190   int i = 0;
191 #ifdef BUFFY_SIZE
192   struct stat sb;
193 #endif /* BUFFY_SIZE */
194
195   while (MoreArgs (s)) {
196     mutt_extract_token (path, s, 0);
197     strfcpy (buf, path->data, sizeof (buf));
198
199     if (data == M_UNMAILBOXES && mutt_strcmp (buf, "*") == 0) {
200       list_del (&Incoming, buffy_free);
201       return 0;
202     }
203
204     /* Skip empty tokens. */
205     if (!*buf)
206       continue;
207
208     mutt_expand_path (buf, sizeof (buf));
209     i = buffy_lookup (buf);
210
211     if (data == M_UNMAILBOXES) {
212       if (i >= 0) {
213         tmp = (BUFFY*) list_pop_idx (Incoming, i);
214         buffy_free (&tmp);
215       }
216       continue;
217     }
218
219     if (i < 0) {
220       tmp = safe_calloc (1, sizeof (BUFFY));
221       tmp->path = safe_strdup (buf);
222       tmp->magic = 0;
223       list_push_back (&Incoming, tmp);
224       i = Incoming->length-1;
225     } else
226       tmp = (BUFFY*) Incoming->data[i];
227
228     tmp->new = 0;
229     tmp->notified = 1;
230     tmp->newly_created = 0;
231
232 #ifdef BUFFY_SIZE
233     /* for buffy_size, it is important that if the folder is new (tested by
234      * reading it), the size is set to 0 so that later when we check we see
235      * that it increased .  without buffy_size we probably don't care.
236      */
237     if (stat (tmp->path, &sb) == 0 && !test_new_folder (tmp->path)) {
238       /* some systems out there don't have an off_t type */
239       tmp->size = (long) sb.st_size;
240     }
241     else
242       tmp->size = 0;
243 #endif /* BUFFY_SIZE */
244   }
245   return 0;
246 }
247
248 #ifdef BUFFY_SIZE
249 /* people use buffy_size on systems where modified time attributes are BADLY
250  * broken. Ignore them.
251  */
252 #define STAT_CHECK (sb.st_size > tmp->size)
253 #else
254 #define STAT_CHECK (sb.st_mtime > sb.st_atime || (tmp->newly_created && sb.st_ctime == sb.st_mtime && sb.st_ctime == sb.st_atime))
255 #endif /* BUFFY_SIZE */
256
257 /* values for force:
258  * 0    don't force any checks + update sidebar
259  * 1    force all checks + update sidebar
260  * 2    force all checks + _don't_ update sidebar
261  */
262 int mutt_buffy_check (int force)
263 {
264   BUFFY *tmp;
265   struct stat sb;
266   struct dirent *de;
267   DIR *dirp;
268   char path[_POSIX_PATH_MAX];
269   struct stat contex_sb;
270   time_t now, last1;
271   CONTEXT *ctx;
272   int i = 0;
273 #ifdef USE_IMAP
274   time_t last2;
275
276   /* update postponed count as well, on force */
277   if (force != 0)
278     mutt_update_num_postponed ();
279 #endif
280
281   /* fastest return if there are no mailboxes */
282   if (list_empty(Incoming))
283     return 0;
284   now = time (NULL);
285   if (force == 0 && (now - BuffyTime < BuffyTimeout)
286 #ifdef USE_IMAP
287       && (now - ImapBuffyTime < ImapBuffyTimeout))
288 #else
289     )
290 #endif
291     return BuffyCount;
292
293   last1 = BuffyTime;
294   if (force != 0 || now - BuffyTime >= BuffyTimeout)
295     BuffyTime = now;
296 #ifdef USE_IMAP
297   last2 = ImapBuffyTime;
298   if (force != 0 || now - ImapBuffyTime >= ImapBuffyTimeout)
299     ImapBuffyTime = now;
300 #endif
301   BuffyCount = 0;
302   BuffyNotify = 0;
303
304 #ifdef USE_IMAP
305   if (!Context || Context->magic != M_IMAP)
306 #endif
307 #ifdef USE_POP
308     if (!Context || Context->magic != M_POP)
309 #endif
310 #ifdef USE_NNTP
311       if (!Context || Context->magic != M_NNTP)
312 #endif
313         /* check device ID and serial number instead of comparing paths */
314         if (!Context || !Context->path
315             || stat (Context->path, &contex_sb) != 0) {
316           contex_sb.st_dev = 0;
317           contex_sb.st_ino = 0;
318         }
319
320   for (i = 0; i < Incoming->length; i++) {
321     tmp = (BUFFY*) Incoming->data[i];
322 #ifdef USE_IMAP
323     if (mx_is_imap (tmp->path))
324       tmp->magic = M_IMAP;
325     else
326 #endif
327 #ifdef USE_POP
328     if (mx_is_pop (tmp->path))
329       tmp->magic = M_POP;
330     else
331 #endif
332 #ifdef USE_NNTP
333     if ((tmp->magic == M_NNTP) || mx_is_nntp (tmp->path))
334       tmp->magic = M_NNTP;
335     else
336 #endif
337     if (stat (tmp->path, &sb) != 0 || sb.st_size == 0 ||
338           (!tmp->magic && (tmp->magic = mx_get_magic (tmp->path)) <= 0)) {
339       /* if the mailbox still doesn't exist, set the newly created flag to
340        * be ready for when it does. */
341       tmp->newly_created = 1;
342       tmp->magic = 0;
343 #ifdef BUFFY_SIZE
344       tmp->size = 0;
345 #endif
346       continue;
347     }
348
349     /* check to see if the folder is the currently selected folder
350      * before polling */
351     if (!Context || !Context->path || ((0
352 #ifdef USE_IMAP
353                                         || tmp->magic == M_IMAP
354 #endif
355 #ifdef USE_POP
356                                         || tmp->magic == M_POP
357 #endif
358 #ifdef USE_NNTP
359                                         || tmp->magic == M_NNTP
360 #endif
361                                        )? mutt_strcmp (tmp->path,
362                                                        Context->path) : (sb.
363                                                                          st_dev
364                                                                          !=
365                                                                          contex_sb.
366                                                                          st_dev
367                                                                          ||
368                                                                          sb.
369                                                                          st_ino
370                                                                          !=
371                                                                          contex_sb.
372                                                                          st_ino)
373         )
374       ) {
375       switch (tmp->magic) {
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               /* some other program has deleted mail from the folder */
388               tmp->size = (long) sb.st_size;
389             }
390 #endif
391           }
392           else if (SidebarWidth > 0 && option (OPTMBOXPANE) &&
393                    (STAT_CHECK || tmp->msgcount == 0)) {
394             /* sidebar visible */
395             BuffyCount++;
396             if ((ctx =
397                  mx_open_mailbox (tmp->path, M_READONLY | M_QUIET | M_NOSORT,
398                                   NULL)) != NULL) {
399               tmp->msgcount = ctx->msgcount;
400               tmp->new = ctx->new;
401               tmp->msg_unread = ctx->new;       /* for sidebar, wtf? */
402               tmp->msg_flagged = ctx->flagged;
403               mx_close_mailbox (ctx, 0);
404             }
405           }
406           if (tmp->newly_created &&
407               (sb.st_ctime != sb.st_mtime || sb.st_ctime != sb.st_atime))
408             tmp->newly_created = 0;
409         }
410         else if (tmp->new > 0)
411           BuffyCount++;
412         break;
413
414       case M_MAILDIR:
415         /* only check on force or $mail_check reached */
416         if (force != 0 || (now - last1 >= BuffyTimeout)) {
417           snprintf (path, sizeof (path), "%s/new", tmp->path);
418           if ((dirp = opendir (path)) == NULL) {
419             tmp->magic = 0;
420             break;
421           }
422           tmp->new = 0;
423           tmp->msg_unread = 0;
424           tmp->msgcount = 0;
425           while ((de = readdir (dirp)) != NULL) {
426             char *p;
427
428             if (*de->d_name != '.' &&
429                 (!(p = strstr (de->d_name, ":2,")) || !strchr (p + 3, 'T'))) {
430               /* one new and undeleted message is enough */
431               if (tmp->new == 0) {
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             /* only count total mail if sidebar visible */
447             snprintf (path, sizeof (path), "%s/cur", tmp->path);
448             if ((dirp = opendir (path)) == NULL) {
449               tmp->magic = 0;
450               break;
451             }
452             tmp->msg_flagged = 0;
453             while ((de = readdir (dirp)) != NULL) {
454               char *p;
455
456               if (*de->d_name != '.'
457                   && (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         }
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             DIR *dp;
479             struct dirent *de;
480
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               if (mh_valid_message (de->d_name)) {
488                 tmp->msgcount++;
489                 tmp->msg_unread++;
490                 tmp->new++;
491               }
492             }
493             closedir (dp);
494           }
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         }
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     sidebar_draw (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   int i = 0;
557
558   if (option (OPTFORCEBUFFYCHECK))
559     mutt_buffy_check (1);
560
561   pos = 0;
562   first = 1;
563   buffylist[0] = 0;
564   pos += mutt_strlen (strncat (buffylist, _("New mail in "), sizeof (buffylist) - 1 - pos)); /* __STRNCAT_CHECKED__ */
565   if (Incoming) {
566     for (i = 0; i < Incoming->length; i++) {
567       tmp = (BUFFY*) Incoming->data[i];
568       /* Is there new mail in this mailbox? */
569       if (tmp->new <= 0 || (have_unnotified && tmp->notified))
570         continue;
571
572       strfcpy (path, tmp->path, sizeof (path));
573       mutt_pretty_mailbox (path);
574
575       if (!first && pos + mutt_strlen (path) >= COLS - 7)
576         break;
577
578       if (!first)
579         pos += mutt_strlen (strncat (buffylist + pos, ", ", sizeof (buffylist) - 1 - pos));    /* __STRNCAT_CHECKED__ */
580
581       /* Prepend an asterisk to mailboxes not already notified */
582       if (!tmp->notified) {
583         /* pos += mutt_strlen (strncat(buffylist + pos, "*", sizeof(buffylist)-1-pos));  __STRNCAT_CHECKED__ */
584         tmp->notified = 1;
585         BuffyNotify--;
586       }
587       pos += mutt_strlen (strncat (buffylist + pos, path, sizeof (buffylist) - 1 - pos));      /* __STRNCAT_CHECKED__ */
588       first = 0;
589     }
590   }
591   if (!first && i < Incoming->length) {
592     strncat (buffylist + pos, ", ...", sizeof (buffylist) - 1 - pos);   /* __STRNCAT_CHECKED__ */
593   }
594   if (!first) {
595     /* on new mail: redraw sidebar */
596     sidebar_draw (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     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 i = 0, c = 0;
624
625   if (list_empty(Incoming))
626     return;
627
628   mutt_expand_path (s, _POSIX_PATH_MAX);
629   if (mutt_buffy_check (0) == 0) {
630     *s = '\0';
631     return;
632   }
633
634   i = buffy_lookup (s);
635   c = i == Incoming->length-1 ? 0 : i+1;
636   while (((BUFFY*) Incoming->data[c])->new <= 0) {
637     c = (c+1) % Incoming->length;
638     if (c == i)
639       break;    /* tried all once */
640   }
641   if (c == i) {
642     *s = '\0';
643     /* something went wrong since we're here when mutt_buffy_check
644      * reported new mail */
645     mutt_buffy_check (0);
646   } else {
647     strfcpy (s, ((BUFFY*) Incoming->data[c])->path, slen);
648     mutt_pretty_mailbox (s);
649   }
650 }