push more things in the str lib.
[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 <lib-lib/mem.h>
18 #include <lib-lib/buffer.h>
19 #include <lib-lib/macros.h>
20
21 #include "mutt.h"
22 #include "buffy.h"
23 #include "mx.h"
24 #include "mh.h"
25 #include "sidebar.h"
26
27 #include "mutt_curses.h"
28
29 #ifdef USE_IMAP
30 #include "imap.h"
31 #endif
32
33
34 #include <string.h>
35 #include <sys/stat.h>
36 #include <dirent.h>
37 #include <utime.h>
38 #include <ctype.h>
39 #include <unistd.h>
40
41 #include <stdio.h>
42
43 static time_t BuffyTime = 0;    /* last time we started checking for mail */
44
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 static int fseeko_last_message (FILE * f)
57 {
58   LOFF_T pos;
59   char buffer[BUFSIZ + 9];      /* 7 for "\n\nFrom " */
60   int bytes_read;
61   int i;                        /* Index into `buffer' for scanning.  */
62
63   p_clear(buffer, 1);
64   fseeko (f, 0, SEEK_END);
65   pos = ftello (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     /* we save in the buffer at the end the first 7 chars from the last read */
76     strncpy (buffer + BUFSIZ, buffer, 5 + 2);   /* 2 == 2 * m_strlen(CRLF) */
77     fseeko (f, pos, SEEK_SET);
78     bytes_read = fread (buffer, sizeof (char), bytes_read, f);
79     if (bytes_read == -1)
80       return -1;
81     for (i = bytes_read; --i >= 0;)
82       if (!m_strncmp(buffer + i, "\n\nFrom ", m_strlen("\n\nFrom "))) { /* found it - go to the beginning of the From */
83         fseeko (f, pos + i + 2, SEEK_SET);
84         return 0;
85       }
86     bytes_read = BUFSIZ;
87   }
88
89   /* here we are at the beginning of the file */
90   if (!m_strncmp("From ", buffer, 5)) {
91     fseeko (f, 0, 0);
92     return (0);
93   }
94
95   return (-1);
96 }
97
98 /* Return 1 if the last message is new */
99 static int test_last_status_new (FILE * f)
100 {
101   HEADER *hdr;
102   ENVELOPE *tmp_envelope;
103   int result = 0;
104
105   if (fseeko_last_message (f) == -1)
106     return (0);
107
108   hdr = mutt_new_header ();
109   tmp_envelope = mutt_read_rfc822_header (f, hdr, 0, 0);
110   if (!(hdr->read || hdr->old))
111     result = 1;
112
113   mutt_free_envelope (&tmp_envelope);
114   mutt_free_header (&hdr);
115
116   return result;
117 }
118
119 static int test_new_folder (const char *path)
120 {
121   FILE *f;
122   int rc = 0;
123   int typ;
124
125   typ = mx_get_magic (path);
126
127   if (typ != M_MBOX && typ != M_MMDF)
128     return 0;
129
130   if ((f = fopen (path, "rb"))) {
131     rc = test_last_status_new (f);
132     fclose (f);
133   }
134
135   return rc;
136 }
137
138 BUFFY *buffy_find_mailbox (const char *path)
139 {
140   struct stat sb;
141   struct stat tmp_sb;
142   int i = 0;
143
144   if (stat (path, &sb) != 0)
145     return NULL;
146
147   if (!list_empty(Incoming)) {
148     for (i = 0; i < Incoming->length; i++) {
149       if (stat (Incoming->data[i], &tmp_sb) == 0 &&
150           sb.st_dev == tmp_sb.st_dev && sb.st_ino == tmp_sb.st_ino)
151         return ((BUFFY*) Incoming->data[i]);
152     }
153   }
154   return (NULL);
155 }
156
157 void buffy_update_mailbox (BUFFY * b)
158 {
159   struct stat sb;
160
161   if (!b)
162     return;
163
164   if (stat (b->path, &sb) == 0)
165     b->size = (long) sb.st_size;
166   else
167     b->size = 0;
168   return;
169 }
170 #endif
171
172 /* func to free buffy for list_del() */
173 static void buffy_free (BUFFY** p) {
174   p_delete(&(*p)->path);
175   p_delete(p);
176 }
177
178 int buffy_lookup (const char* path) {
179   int i = 0;
180   if (list_empty(Incoming) || !path || !*path)
181     return (-1);
182   for (i = 0; i < Incoming->length; i++) {
183     if (str_eq (((BUFFY*) Incoming->data[i])->path, path) )
184       return (i);
185   }
186   return (-1);
187 }
188
189 int buffy_parse_mailboxes (BUFFER * path, BUFFER * s, unsigned long data,
190                           BUFFER * err)
191 {
192   BUFFY* tmp;
193   char buf[_POSIX_PATH_MAX];
194   int i = 0;
195 #ifdef BUFFY_SIZE
196   struct stat sb;
197 #endif /* BUFFY_SIZE */
198
199   while (MoreArgs (s)) {
200     mutt_extract_token (path, s, 0);
201     m_strcpy(buf, sizeof(buf), path->data);
202
203     if (data == M_UNMAILBOXES && str_eq (buf, "*")) {
204       list_del (&Incoming, (list_del_t*) buffy_free);
205       return 0;
206     }
207
208     /* Skip empty tokens. */
209     if (!*buf)
210       continue;
211
212     mutt_expand_path (buf, sizeof (buf));
213     i = buffy_lookup (buf);
214
215     if (data == M_UNMAILBOXES) {
216       if (i >= 0) {
217         tmp = (BUFFY*) list_pop_idx (Incoming, i);
218         buffy_free (&tmp);
219       }
220       continue;
221     }
222
223     if (i < 0) {
224       tmp = p_new(BUFFY, 1);
225       tmp->path = m_strdup(buf);
226       tmp->magic = 0;
227       list_push_back (&Incoming, tmp);
228       i = Incoming->length-1;
229     } else
230       tmp = (BUFFY*) Incoming->data[i];
231
232     tmp->new = 0;
233     tmp->notified = 1;
234     tmp->newly_created = 0;
235
236 #ifdef BUFFY_SIZE
237     /* for buffy_size, it is important that if the folder is new (tested by
238      * reading it), the size is set to 0 so that later when we check we see
239      * that it increased .  without buffy_size we probably don't care.
240      */
241     if (stat (tmp->path, &sb) == 0 && !test_new_folder (tmp->path)) {
242       /* some systems out there don't have an off_t type */
243       tmp->size = (long) sb.st_size;
244     }
245     else
246       tmp->size = 0;
247 #endif /* BUFFY_SIZE */
248   }
249   return 0;
250 }
251
252 #ifdef BUFFY_SIZE
253 /* people use buffy_size on systems where modified time attributes are BADLY
254  * broken. Ignore them.
255  */
256 #define STAT_CHECK (sb.st_size > tmp->size)
257 #else
258 #define STAT_CHECK (sb.st_mtime > sb.st_atime || (tmp->newly_created && sb.st_ctime == sb.st_mtime && sb.st_ctime == sb.st_atime))
259 #endif /* BUFFY_SIZE */
260
261 /* values for force:
262  * 0    don't force any checks + update sidebar
263  * 1    force all checks + update sidebar
264  * 2    don't force any checks + _don't_ update sidebar
265  */
266 int buffy_check (int force)
267 {
268   BUFFY *tmp;
269   struct stat sb;
270   struct dirent *de;
271   DIR *dirp;
272   char path[_POSIX_PATH_MAX];
273   struct stat contex_sb;
274   time_t now, last1;
275   CONTEXT *ctx;
276   int i = 0, local = 0, count = 0;
277 #ifdef USE_IMAP
278   time_t last2;
279
280   /* update postponed count as well, on force */
281   if (force == 1)
282     mutt_update_num_postponed ();
283 #endif
284
285   /* fastest return if there are no mailboxes */
286   if (list_empty(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 == 1 || now - BuffyTime >= BuffyTimeout)
299     BuffyTime = now;
300 #ifdef USE_IMAP
301   last2 = ImapBuffyTime;
302   if (force == 1 || now - ImapBuffyTime >= ImapBuffyTimeout)
303     ImapBuffyTime = now;
304 #endif
305   BuffyCount = 0;
306   BuffyNotify = 0;
307
308   count = sidebar_need_count ();
309
310   if (!Context || !Context->path || 
311       (mx_is_local (Context->magic-1) && stat (Context->path, &contex_sb) != 0)) {
312     /* check device ID and serial number instead of comparing paths */
313     contex_sb.st_dev = 0;
314     contex_sb.st_ino = 0;
315   }
316
317   for (i = 0; i < Incoming->length; i++) {
318     tmp = (BUFFY*) Incoming->data[i];
319     tmp->magic = mx_get_magic (tmp->path);
320     local = mx_is_local (tmp->magic-1);
321     if ((tmp->magic <= 0 || local) && (stat (tmp->path, &sb) != 0 || sb.st_size == 0)) {
322       /* if the mailbox still doesn't exist, set the newly created flag to
323        * be ready for when it does. */
324       tmp->newly_created = 1;
325       tmp->magic = -1;
326 #ifdef BUFFY_SIZE
327       tmp->size = 0;
328 #endif
329       continue;
330     }
331
332     /* check to see if the folder is the currently selected folder
333      * before polling */
334     if (!Context || !Context->path || (local ? (sb.st_dev != contex_sb.st_dev ||
335                                                 sb.st_ino != contex_sb.st_ino) : 
336                                        !str_eq (tmp->path, Context->path))) {
337       switch (tmp->magic) {
338       case M_MBOX:
339       case M_MMDF:
340         /* only check on force or $mail_check reached */
341         if (force == 1 || (now - last1 >= BuffyTimeout)) {
342           if (!count) {
343             if (STAT_CHECK) {
344               BuffyCount++;
345               tmp->new = 1;
346             }
347 #ifdef BUFFY_SIZE
348             else {
349               /* some other program has deleted mail from the folder */
350               tmp->size = (long) sb.st_size;
351             }
352 #endif
353           }
354           else if (STAT_CHECK || tmp->msgcount == 0) {
355             /* sidebar visible */
356             BuffyCount++;
357             if ((ctx =
358                  mx_open_mailbox (tmp->path, M_READONLY | M_QUIET | M_NOSORT | M_COUNT,
359                                   NULL)) != NULL) {
360               tmp->msgcount = ctx->msgcount;
361               tmp->new = ctx->new;
362               tmp->msg_unread = ctx->new;       /* for sidebar, wtf? */
363               tmp->msg_flagged = ctx->flagged;
364               mx_close_mailbox (ctx, 0);
365             }
366           }
367           if (tmp->newly_created &&
368               (sb.st_ctime != sb.st_mtime || sb.st_ctime != sb.st_atime))
369             tmp->newly_created = 0;
370         }
371         else if (tmp->new > 0)
372           BuffyCount++;
373         break;
374
375       case M_MAILDIR:
376         /* only check on force or $mail_check reached */
377         if (force == 1 || (now - last1 >= BuffyTimeout)) {
378           snprintf (path, sizeof (path), "%s/new", tmp->path);
379           if ((dirp = opendir (path)) == NULL) {
380             tmp->magic = 0;
381             break;
382           }
383           tmp->new = 0;
384           tmp->msg_unread = 0;
385           tmp->msgcount = 0;
386           while ((de = readdir (dirp)) != NULL) {
387             char *p;
388
389             if (*de->d_name != '.' &&
390                 (!(p = strstr (de->d_name, ":2,")) || !strchr (p + 3, 'T'))) {
391               /* one new and undeleted message is enough */
392               if (tmp->new == 0) {
393                 BuffyCount++;
394                 if (!count) {
395                   /* if sidebar invisible -> done */
396                   tmp->new = 1;
397                   break;
398                 }
399               }
400               tmp->msgcount++;
401               tmp->msg_unread++;
402               tmp->new++;
403             }
404           }
405           closedir (dirp);
406
407           if (count) {
408             /* only count total mail if sidebar visible */
409             snprintf (path, sizeof (path), "%s/cur", tmp->path);
410             if ((dirp = opendir (path)) == NULL) {
411               tmp->magic = 0;
412               break;
413             }
414             tmp->msg_flagged = 0;
415             while ((de = readdir (dirp)) != NULL) {
416               char *p;
417
418               if (*de->d_name != '.'
419                   && (p = strstr (de->d_name, ":2,")) != NULL) {
420                 if (!strchr (p + 3, 'T'))
421                   tmp->msgcount++;
422                 if (strchr (p + 3, 'F'))
423                   tmp->msg_flagged++;
424               }
425             }
426             closedir (dirp);
427           }
428         }
429         else if (tmp->new > 0)
430           /* keep current stats if !force and !$mail_check reached */
431           BuffyCount++;
432         break;
433
434       case M_MH:
435         /* only check on force or $mail_check reached */
436         if (force == 1 || (now - last1 >= BuffyTimeout)) {
437           if ((tmp->new = mh_buffy (tmp->path)) > 0)
438             BuffyCount++;
439           if (count) {
440             DIR *dp;
441             struct dirent *de;
442
443             if ((dp = opendir (path)) == NULL)
444               break;
445             tmp->new = 0;
446             tmp->msgcount = 0;
447             tmp->msg_unread = 0;
448             while ((de = readdir (dp))) {
449               if (mh_valid_message (de->d_name)) {
450                 tmp->msgcount++;
451                 tmp->msg_unread++;
452                 tmp->new++;
453               }
454             }
455             closedir (dp);
456           }
457         }
458         else if (tmp->new > 0)
459           /* keep current stats if !force and !$mail_check reached */
460           BuffyCount++;
461         break;
462
463 #ifdef USE_IMAP
464       case M_IMAP:
465         /* only check on force or $imap_mail_check reached */
466         if (force == 1 || (now - last2 >= ImapBuffyTimeout)) {
467           tmp->msgcount = imap_mailbox_check (tmp->path, 0);
468           tmp->new = imap_mailbox_check (tmp->path, 1);
469           tmp->msg_unread = imap_mailbox_check (tmp->path, 2);
470           if (tmp->new > 0)
471             BuffyCount++;
472           else
473             tmp->new = 0;
474           if (tmp->msg_unread < 0)
475             tmp->msg_unread = 0;
476         }
477         else if (tmp->new > 0)
478           /* keep current stats if !force and !$imap_mail_check reached */
479           BuffyCount++;
480         break;
481 #endif
482
483       }
484     }
485 #ifdef BUFFY_SIZE
486     else if (Context && Context->path)
487       tmp->size = (long) sb.st_size;    /* update the size */
488 #endif
489
490     if (tmp->new <= 0)
491       tmp->notified = 0;
492     else if (!tmp->notified)
493       BuffyNotify++;
494     tmp->has_new = tmp->new > 0;
495   }
496   if (BuffyCount > 0 && force != 2)
497     sidebar_draw (CurrentMenu);
498   return (BuffyCount);
499 }
500
501 int buffy_list (void)
502 {
503   BUFFY *tmp;
504   char path[_POSIX_PATH_MAX];
505   char buffylist[160];
506   int pos;
507   int first;
508   int have_unnotified = BuffyNotify;
509   int i = 0;
510
511   pos = 0;
512   first = 1;
513   buffylist[0] = 0;
514   pos += m_strlen(strncat (buffylist, _("New mail in "), sizeof (buffylist) - 1 - pos)); /* __STRNCAT_CHECKED__ */
515   if (Incoming) {
516     for (i = 0; i < Incoming->length; i++) {
517       tmp = (BUFFY*) Incoming->data[i];
518       /* Is there new mail in this mailbox? */
519       if (tmp->new <= 0 || (have_unnotified && tmp->notified))
520         continue;
521
522       m_strcpy(path, sizeof(path), tmp->path);
523       mutt_pretty_mailbox (path);
524
525       if (!first && pos + m_strlen(path) >= COLS - 7)
526         break;
527
528       if (!first)
529         pos += m_strlen(strncat (buffylist + pos, ", ", sizeof (buffylist) - 1 - pos));    /* __STRNCAT_CHECKED__ */
530
531       /* Prepend an asterisk to mailboxes not already notified */
532       if (!tmp->notified) {
533         /* pos += m_strlen(strncat(buffylist + pos, "*", sizeof(buffylist)-1-pos));  __STRNCAT_CHECKED__ */
534         tmp->notified = 1;
535         BuffyNotify--;
536       }
537       pos += m_strlen(strncat (buffylist + pos, path, sizeof (buffylist) - 1 - pos));      /* __STRNCAT_CHECKED__ */
538       first = 0;
539     }
540   }
541   if (!first && i < Incoming->length) {
542     strncat (buffylist + pos, ", ...", sizeof (buffylist) - 1 - pos);   /* __STRNCAT_CHECKED__ */
543   }
544   if (!first) {
545     /* on new mail: redraw sidebar */
546     sidebar_draw (CurrentMenu);
547     mutt_message ("%s", buffylist);
548     return (1);
549   }
550   /* there were no mailboxes needing to be notified, so clean up since 
551    * BuffyNotify has somehow gotten out of sync
552    */
553   BuffyNotify = 0;
554   return (0);
555 }
556
557 int buffy_notify (void)
558 {
559   if (buffy_check (0) && BuffyNotify) {
560     return (buffy_list ());
561   }
562   return (0);
563 }
564
565 /* 
566  * mutt_buffy() -- incoming folders completion routine
567  *
568  * given a folder name, this routine gives the next incoming folder with new
569  * new mail.
570  */
571 void buffy_next (char *s, size_t slen)
572 {
573   int i = 0, c = 0, l = 0;
574
575   if (list_empty(Incoming))
576     return;
577
578   mutt_expand_path (s, _POSIX_PATH_MAX);
579   if (buffy_check (0) == 0) {
580     *s = '\0';
581     return;
582   }
583
584   /*
585    * If buffy_lookup returns the index,
586    * or -1 if not found (-1..Incoming->length-1);
587    * plus one --> (0..Incoming->length).
588    * Modulo mapps it into the correct range.
589    */
590   i = 1 + buffy_lookup (s);
591   for (l=0; l < Incoming->length; l++) {
592     c = (l+i) % Incoming->length;
593     if ((!Context || !Context->path || !str_eq (((BUFFY*) Incoming->data[c])->path, Context->path)) &&
594         ((BUFFY*) Incoming->data[c])->new > 0)
595       break;
596   }
597   if (l >= Incoming->length) {
598     *s = '\0';
599     /* something went wrong since we're here when buffy_check
600      * reported new mail */
601     buffy_check (0);
602   } else {
603     m_strcpy(s, slen, ((BUFFY*)Incoming->data[c])->path);
604     mutt_pretty_mailbox (s);
605   }
606 }