~ubuntu-branches/debian/squeeze/alpine/squeeze

« back to all changes in this revision

Viewing changes to imap/src/osdep/unix/mh.c

  • Committer: Bazaar Package Importer
  • Author(s): Asheesh Laroia
  • Date: 2007-02-17 13:17:42 UTC
  • Revision ID: james.westby@ubuntu.com-20070217131742-99x5c6cpg1pbkdhw
Tags: upstream-0.82+dfsg
ImportĀ upstreamĀ versionĀ 0.82+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* ========================================================================
 
2
 * Copyright 1988-2006 University of Washington
 
3
 *
 
4
 * Licensed under the Apache License, Version 2.0 (the "License");
 
5
 * you may not use this file except in compliance with the License.
 
6
 * You may obtain a copy of the License at
 
7
 *
 
8
 *     http://www.apache.org/licenses/LICENSE-2.0
 
9
 *
 
10
 * 
 
11
 * ========================================================================
 
12
 */
 
13
 
 
14
/*
 
15
 * Program:     MH mail routines
 
16
 *
 
17
 * Author(s):   Mark Crispin
 
18
 *              Networks and Distributed Computing
 
19
 *              Computing & Communications
 
20
 *              University of Washington
 
21
 *              Administration Building, AG-44
 
22
 *              Seattle, WA  98195
 
23
 *              Internet: MRC@CAC.Washington.EDU
 
24
 *
 
25
 * Date:        23 February 1992
 
26
 * Last Edited: 18 December 2006
 
27
 */
 
28
 
 
29
 
 
30
#include <stdio.h>
 
31
#include <ctype.h>
 
32
#include <errno.h>
 
33
extern int errno;               /* just in case */
 
34
#include "mail.h"
 
35
#include "osdep.h"
 
36
#include <pwd.h>
 
37
#include <sys/stat.h>
 
38
#include <sys/time.h>
 
39
#include "misc.h"
 
40
#include "dummy.h"
 
41
#include "fdstring.h"
 
42
 
 
43
 
 
44
/* Build parameters */
 
45
 
 
46
#define MHINBOX "#mhinbox"      /* corresponds to namespace in env_unix.c */
 
47
#define MHINBOXDIR "inbox"
 
48
#define MHPROFILE ".mh_profile"
 
49
#define MHCOMMA ','
 
50
#define MHSEQUENCE ".mh_sequence"
 
51
#define MHSEQUENCES ".mh_sequences"
 
52
#define MHPATH "Mail"
 
53
 
 
54
 
 
55
/* mh_load_message() flags */
 
56
 
 
57
#define MLM_HEADER 0x1          /* load message text */
 
58
#define MLM_TEXT 0x2            /* load message text */
 
59
 
 
60
/* MH I/O stream local data */
 
61
        
 
62
typedef struct mh_local {
 
63
  char *dir;                    /* spool directory name */
 
64
  unsigned char buf[CHUNKSIZE]; /* temporary buffer */
 
65
  unsigned long cachedtexts;    /* total size of all cached texts */
 
66
  time_t scantime;              /* last time directory scanned */
 
67
} MHLOCAL;
 
68
 
 
69
 
 
70
/* Convenient access to local data */
 
71
 
 
72
#define LOCAL ((MHLOCAL *) stream->local)
 
73
 
 
74
 
 
75
/* Function prototypes */
 
76
 
 
77
DRIVER *mh_valid (char *name);
 
78
int mh_isvalid (char *name,char *tmp,long synonly);
 
79
int mh_namevalid (char *name);
 
80
char *mh_path (char *tmp);
 
81
void *mh_parameters (long function,void *value);
 
82
long mh_dirfmttest (char *name);
 
83
void mh_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents);
 
84
void mh_list (MAILSTREAM *stream,char *ref,char *pat);
 
85
void mh_lsub (MAILSTREAM *stream,char *ref,char *pat);
 
86
void mh_list_work (MAILSTREAM *stream,char *dir,char *pat,long level);
 
87
long mh_subscribe (MAILSTREAM *stream,char *mailbox);
 
88
long mh_unsubscribe (MAILSTREAM *stream,char *mailbox);
 
89
long mh_create (MAILSTREAM *stream,char *mailbox);
 
90
long mh_delete (MAILSTREAM *stream,char *mailbox);
 
91
long mh_rename (MAILSTREAM *stream,char *old,char *newname);
 
92
MAILSTREAM *mh_open (MAILSTREAM *stream);
 
93
void mh_close (MAILSTREAM *stream,long options);
 
94
void mh_fast (MAILSTREAM *stream,char *sequence,long flags);
 
95
void mh_load_message (MAILSTREAM *stream,unsigned long msgno,long flags);
 
96
char *mh_header (MAILSTREAM *stream,unsigned long msgno,unsigned long *length,
 
97
                 long flags);
 
98
long mh_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags);
 
99
long mh_ping (MAILSTREAM *stream);
 
100
void mh_check (MAILSTREAM *stream);
 
101
long mh_expunge (MAILSTREAM *stream,char *sequence,long options);
 
102
long mh_copy (MAILSTREAM *stream,char *sequence,char *mailbox,
 
103
              long options);
 
104
long mh_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data);
 
105
 
 
106
int mh_select (struct direct *name);
 
107
int mh_numsort (const void *d1,const void *d2);
 
108
char *mh_file (char *dst,char *name);
 
109
long mh_canonicalize (char *pattern,char *ref,char *pat);
 
110
void mh_setdate (char *file,MESSAGECACHE *elt);
 
111
 
 
112
/* MH mail routines */
 
113
 
 
114
 
 
115
/* Driver dispatch used by MAIL */
 
116
 
 
117
DRIVER mhdriver = {
 
118
  "mh",                         /* driver name */
 
119
                                /* driver flags */
 
120
  DR_MAIL|DR_LOCAL|DR_NOFAST|DR_NAMESPACE|DR_NOSTICKY|DR_DIRFMT,
 
121
  (DRIVER *) NIL,               /* next driver */
 
122
  mh_valid,                     /* mailbox is valid for us */
 
123
  mh_parameters,                /* manipulate parameters */
 
124
  mh_scan,                      /* scan mailboxes */
 
125
  mh_list,                      /* find mailboxes */
 
126
  mh_lsub,                      /* find subscribed mailboxes */
 
127
  mh_subscribe,                 /* subscribe to mailbox */
 
128
  mh_unsubscribe,               /* unsubscribe from mailbox */
 
129
  mh_create,                    /* create mailbox */
 
130
  mh_delete,                    /* delete mailbox */
 
131
  mh_rename,                    /* rename mailbox */
 
132
  mail_status_default,          /* status of mailbox */
 
133
  mh_open,                      /* open mailbox */
 
134
  mh_close,                     /* close mailbox */
 
135
  mh_fast,                      /* fetch message "fast" attributes */
 
136
  NIL,                          /* fetch message flags */
 
137
  NIL,                          /* fetch overview */
 
138
  NIL,                          /* fetch message envelopes */
 
139
  mh_header,                    /* fetch message header */
 
140
  mh_text,                      /* fetch message body */
 
141
  NIL,                          /* fetch partial message text */
 
142
  NIL,                          /* unique identifier */
 
143
  NIL,                          /* message number */
 
144
  NIL,                          /* modify flags */
 
145
  NIL,                          /* per-message modify flags */
 
146
  NIL,                          /* search for message based on criteria */
 
147
  NIL,                          /* sort messages */
 
148
  NIL,                          /* thread messages */
 
149
  mh_ping,                      /* ping mailbox to see if still alive */
 
150
  mh_check,                     /* check for new messages */
 
151
  mh_expunge,                   /* expunge deleted messages */
 
152
  mh_copy,                      /* copy messages to another mailbox */
 
153
  mh_append,                    /* append string message to mailbox */
 
154
  NIL                           /* garbage collect stream */
 
155
};
 
156
 
 
157
                                /* prototype stream */
 
158
MAILSTREAM mhproto = {&mhdriver};
 
159
 
 
160
 
 
161
static char *mh_profile = NIL;  /* holds MH profile */
 
162
static char *mh_pathname = NIL; /* holds MH path name */
 
163
static long mh_once = 0;        /* already snarled once */
 
164
static long mh_allow_inbox =NIL;/* allow INBOX as well as MHINBOX */
 
165
 
 
166
/* MH mail validate mailbox
 
167
 * Accepts: mailbox name
 
168
 * Returns: our driver if name is valid, NIL otherwise
 
169
 */
 
170
 
 
171
DRIVER *mh_valid (char *name)
 
172
{
 
173
  char tmp[MAILTMPLEN];
 
174
  return mh_isvalid (name,tmp,T) ? &mhdriver : NIL;
 
175
}
 
176
 
 
177
 
 
178
/* MH mail test for valid mailbox
 
179
 * Accepts: mailbox name
 
180
 *          temporary buffer to use
 
181
 *          syntax only test flag
 
182
 * Returns: T if valid, NIL otherwise
 
183
 */
 
184
 
 
185
int mh_isvalid (char *name,char *tmp,long synonly)
 
186
{
 
187
  struct stat sbuf;
 
188
  char *s,*t,altname[MAILTMPLEN];
 
189
  unsigned long i;
 
190
  int ret = NIL;
 
191
  errno = NIL;                  /* zap any error condition */
 
192
                                /* mh name? */
 
193
  if ((mh_allow_inbox && !compare_cstring (name,"INBOX")) ||
 
194
      !compare_cstring (name,MHINBOX) ||
 
195
      ((name[0] == '#') && ((name[1] == 'm') || (name[1] == 'M')) &&
 
196
       ((name[2] == 'h') || (name[2] == 'H')) && (name[3] == '/') && name[4])){
 
197
    if (mh_path (tmp))          /* validate name if INBOX or not synonly */
 
198
      ret = (synonly && compare_cstring (name,"INBOX")) ?
 
199
        T : ((stat (mh_file (tmp,name),&sbuf) == 0) &&
 
200
             (sbuf.st_mode & S_IFMT) == S_IFDIR);
 
201
    else if (!mh_once++) {      /* only report error once */
 
202
      sprintf (tmp,"%.900s not found, mh format names disabled",mh_profile);
 
203
      mm_log (tmp,WARN);
 
204
    }
 
205
  }
 
206
                                /* see if non-NS name within mh hierarchy */
 
207
  else if ((name[0] != '#') && (s = mh_path (tmp)) && (i = strlen (s)) &&
 
208
           (t = mailboxfile (tmp,name)) && !strncmp (t,s,i) &&
 
209
           (tmp[i] == '/') && tmp[i+1]) {
 
210
    sprintf (altname,"#mh%.900s",tmp+i);
 
211
                                /* can't do synonly here! */
 
212
    ret = mh_isvalid (altname,tmp,NIL);
 
213
  }
 
214
  else errno = EINVAL;          /* bogus name */
 
215
  return ret;
 
216
}
 
217
 
 
218
/* MH mail test for valid mailbox
 
219
 * Accepts: mailbox name
 
220
 * Returns: T if valid, NIL otherwise
 
221
 */
 
222
 
 
223
int mh_namevalid (char *name)
 
224
{
 
225
  char *s;
 
226
  if (name[0] == '#' && (name[1] == 'm' || name[1] == 'M') &&
 
227
      (name[2] == 'h' || name[2] == 'H') && name[3] == '/')
 
228
    for (s = name; s && *s;) {  /* make sure no all-digit nodes */
 
229
      if (isdigit (*s)) s++;    /* digit, check this node further... */
 
230
      else if (*s == '/') break;/* all digit node, barf */
 
231
                                /* non-digit, skip to next node or return */
 
232
      else if (!((s = strchr (s+1,'/')) && *++s)) return T;
 
233
    }
 
234
  return NIL;                   /* all numeric or empty node */
 
235
}
 
236
 
 
237
/* Return MH path
 
238
 * Accepts: temporary buffer
 
239
 * Returns: MH path or NIL if MH disabled
 
240
 */
 
241
 
 
242
char *mh_path (char *tmp)
 
243
{
 
244
  char *s,*t,*v;
 
245
  int fd;
 
246
  struct stat sbuf;
 
247
  if (!mh_profile) {            /* build mh_profile and mh_pathname now */
 
248
    sprintf (tmp,"%s/%s",myhomedir (),MHPROFILE);
 
249
    if ((fd = open (mh_profile = cpystr (tmp),O_RDONLY,NIL)) >= 0) {
 
250
      fstat (fd,&sbuf);         /* yes, get size and read file */
 
251
      read (fd,(t = (char *) fs_get (sbuf.st_size + 1)),sbuf.st_size);
 
252
      close (fd);               /* don't need the file any more */
 
253
      t[sbuf.st_size] = '\0';   /* tie it off */
 
254
                                /* parse profile file */
 
255
      for (s = strtok (t,"\r\n"); s && *s; s = strtok (NIL,"\r\n")) {
 
256
                                /* found space in line? */
 
257
        if (v = strpbrk (s," \t")) {
 
258
          *v++ = '\0';          /* tie off, is keyword "Path:"? */
 
259
          if (!compare_cstring (s,"Path:")) {
 
260
                                /* skip whitespace */
 
261
            while ((*v == ' ') || (*v == '\t')) ++v;
 
262
                                /* absolute path? */
 
263
            if (*v == '/') s = v;
 
264
            else sprintf (s = tmp,"%s/%s",myhomedir (),v);
 
265
                                /* copy name */
 
266
            mh_pathname = cpystr (s);
 
267
            break;              /* don't need to look at rest of file */
 
268
          }
 
269
        }
 
270
      }
 
271
      fs_give ((void **) &t);   /* flush profile text */
 
272
      if (!mh_pathname) {       /* default path if not in the profile */
 
273
        sprintf (tmp,"%s/%s",myhomedir (),MHPATH);
 
274
        mh_pathname = cpystr (tmp);
 
275
      }
 
276
    }
 
277
  }
 
278
  return mh_pathname;
 
279
}
 
280
 
 
281
/* MH manipulate driver parameters
 
282
 * Accepts: function code
 
283
 *          function-dependent value
 
284
 * Returns: function-dependent return value
 
285
 */
 
286
 
 
287
void *mh_parameters (long function,void *value)
 
288
{
 
289
  void *ret = NIL;
 
290
  switch ((int) function) {
 
291
  case GET_INBOXPATH:
 
292
    if (value) ret = mh_file ((char *) value,"INBOX");
 
293
    break;
 
294
  case GET_DIRFMTTEST:
 
295
    ret = (void *) mh_dirfmttest;
 
296
    break;
 
297
  case SET_MHPROFILE:
 
298
    if (mh_profile) fs_give ((void **) &mh_profile);
 
299
    mh_profile = cpystr ((char *) value);
 
300
  case GET_MHPROFILE:
 
301
    ret = (void *) mh_profile;
 
302
    break;
 
303
  case SET_MHPATH:
 
304
    if (mh_pathname) fs_give ((void **) &mh_pathname);
 
305
    mh_pathname = cpystr ((char *) value);
 
306
  case GET_MHPATH:
 
307
    ret = (void *) mh_pathname;
 
308
    break;
 
309
  case SET_MHALLOWINBOX:
 
310
    mh_allow_inbox = value ? T : NIL;
 
311
  case GET_MHALLOWINBOX:
 
312
    ret = (void *) (mh_allow_inbox ? VOIDT : NIL);
 
313
  }
 
314
  return ret;
 
315
}
 
316
 
 
317
 
 
318
/* MX test for directory format internal node
 
319
 * Accepts: candidate node name
 
320
 * Returns: T if internal name, NIL otherwise
 
321
 */
 
322
 
 
323
long mh_dirfmttest (char *s)
 
324
{
 
325
  int c;
 
326
                                /* sequence(s) file is an internal name */
 
327
  if (strcmp (s,MHSEQUENCE) && strcmp (s,MHSEQUENCES)) {
 
328
    if (*s == MHCOMMA) ++s;     /* else comma + all numeric name */
 
329
                                /* success if all-numeric */
 
330
    while (c = *s++) if (!isdigit (c)) return NIL;
 
331
  }
 
332
  return LONGT;
 
333
}
 
334
 
 
335
/* MH scan mailboxes
 
336
 * Accepts: mail stream
 
337
 *          reference
 
338
 *          pattern to search
 
339
 *          string to scan
 
340
 */
 
341
 
 
342
void mh_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
 
343
{
 
344
  char *s,test[MAILTMPLEN],file[MAILTMPLEN];
 
345
  long i = 0;
 
346
  if (!pat || !*pat) {          /* empty pattern? */
 
347
    if (mh_canonicalize (test,ref,"*")) {
 
348
                                /* tie off name at root */
 
349
      if (s = strchr (test,'/')) *++s = '\0';
 
350
      else test[0] = '\0';
 
351
      mm_list (stream,'/',test,LATT_NOSELECT);
 
352
    }
 
353
  }
 
354
                                /* get canonical form of name */
 
355
  else if (mh_canonicalize (test,ref,pat)) {
 
356
    if (contents) {             /* maybe I'll implement this someday */
 
357
      mm_log ("Scan not valid for mh mailboxes",ERROR);
 
358
      return;
 
359
    }
 
360
    if (test[3] == '/') {       /* looking down levels? */
 
361
                                /* yes, found any wildcards? */
 
362
      if (s = strpbrk (test,"%*")) {
 
363
                                /* yes, copy name up to that point */
 
364
        strncpy (file,test+4,i = s - (test+4));
 
365
        file[i] = '\0';         /* tie off */
 
366
      }
 
367
      else strcpy (file,test+4);/* use just that name then */
 
368
                                /* find directory name */
 
369
      if (s = strrchr (file,'/')) {
 
370
        *s = '\0';              /* found, tie off at that point */
 
371
        s = file;
 
372
      }
 
373
                                /* do the work */
 
374
      mh_list_work (stream,s,test,0);
 
375
    }
 
376
                                /* always an INBOX */
 
377
    if (!compare_cstring (test,MHINBOX))
 
378
      mm_list (stream,NIL,MHINBOX,LATT_NOINFERIORS);
 
379
  }
 
380
}
 
381
 
 
382
/* MH list mailboxes
 
383
 * Accepts: mail stream
 
384
 *          reference
 
385
 *          pattern to search
 
386
 */
 
387
 
 
388
void mh_list (MAILSTREAM *stream,char *ref,char *pat)
 
389
{
 
390
  mh_scan (stream,ref,pat,NIL);
 
391
}
 
392
 
 
393
 
 
394
/* MH list subscribed mailboxes
 
395
 * Accepts: mail stream
 
396
 *          reference
 
397
 *          pattern to search
 
398
 */
 
399
 
 
400
void mh_lsub (MAILSTREAM *stream,char *ref,char *pat)
 
401
{
 
402
  void *sdb = NIL;
 
403
  char *s,test[MAILTMPLEN];
 
404
                                /* get canonical form of name */
 
405
  if (mh_canonicalize (test,ref,pat) && (s = sm_read (&sdb))) {
 
406
    do if (pmatch_full (s,test,'/')) mm_lsub (stream,'/',s,NIL);
 
407
    while (s = sm_read (&sdb)); /* until no more subscriptions */
 
408
  }
 
409
}
 
410
 
 
411
/* MH list mailboxes worker routine
 
412
 * Accepts: mail stream
 
413
 *          directory name to search
 
414
 *          search pattern
 
415
 *          search level
 
416
 */
 
417
 
 
418
void mh_list_work (MAILSTREAM *stream,char *dir,char *pat,long level)
 
419
{
 
420
  DIR *dp;
 
421
  struct direct *d;
 
422
  struct stat sbuf;
 
423
  char *cp,*np,curdir[MAILTMPLEN],name[MAILTMPLEN];
 
424
                                /* build MH name to search */
 
425
  if (dir) sprintf (name,"#mh/%s/",dir);
 
426
  else strcpy (name,"#mh/");
 
427
                                /* make directory name, punt if bogus */
 
428
  if (!mh_file (curdir,name)) return;
 
429
  cp = curdir + strlen (curdir);/* end of directory name */
 
430
  np = name + strlen (name);    /* end of MH name */
 
431
  if (dp = opendir (curdir)) {  /* open directory */
 
432
    while (d = readdir (dp))    /* scan, ignore . and numeric names */
 
433
      if ((d->d_name[0] != '.') && !mh_select (d)) {
 
434
        strcpy (cp,d->d_name);  /* make directory name */
 
435
        if (!stat (curdir,&sbuf) && ((sbuf.st_mode & S_IFMT) == S_IFDIR)) {
 
436
          strcpy (np,d->d_name);/* make mh name of directory name */
 
437
                                /* yes, an MH name if full match */
 
438
          if (pmatch_full (name,pat,'/')) mm_list (stream,'/',name,NIL);
 
439
                                /* check if should recurse */
 
440
          if (dmatch (name,pat,'/') &&
 
441
              (level < (long) mail_parameters (NIL,GET_LISTMAXLEVEL,NIL)))
 
442
            mh_list_work (stream,name+4,pat,level+1);
 
443
        }
 
444
      }
 
445
    closedir (dp);              /* all done, flush directory */
 
446
  }
 
447
}
 
448
 
 
449
/* MH mail subscribe to mailbox
 
450
 * Accepts: mail stream
 
451
 *          mailbox to add to subscription list
 
452
 * Returns: T on success, NIL on failure
 
453
 */
 
454
 
 
455
long mh_subscribe (MAILSTREAM *stream,char *mailbox)
 
456
{
 
457
  return sm_subscribe (mailbox);
 
458
}
 
459
 
 
460
 
 
461
/* MH mail unsubscribe to mailbox
 
462
 * Accepts: mail stream
 
463
 *          mailbox to delete from subscription list
 
464
 * Returns: T on success, NIL on failure
 
465
 */
 
466
 
 
467
long mh_unsubscribe (MAILSTREAM *stream,char *mailbox)
 
468
{
 
469
  return sm_unsubscribe (mailbox);
 
470
}
 
471
 
 
472
/* MH mail create mailbox
 
473
 * Accepts: mail stream
 
474
 *          mailbox name to create
 
475
 * Returns: T on success, NIL on failure
 
476
 */
 
477
 
 
478
long mh_create (MAILSTREAM *stream,char *mailbox)
 
479
{
 
480
  char tmp[MAILTMPLEN];
 
481
  if (!mh_namevalid (mailbox))  /* validate name */
 
482
    sprintf (tmp,"Can't create mailbox %.80s: invalid MH-format name",mailbox);
 
483
                                /* must not already exist */
 
484
  else if (mh_isvalid (mailbox,tmp,NIL))
 
485
    sprintf (tmp,"Can't create mailbox %.80s: mailbox already exists",mailbox);
 
486
  else if (!mh_path (tmp)) return NIL;
 
487
                                /* try to make it */
 
488
  else if (!(mh_file (tmp,mailbox) &&
 
489
             dummy_create_path (stream,strcat (tmp,"/"),
 
490
                                get_dir_protection (mailbox))))
 
491
    sprintf (tmp,"Can't create mailbox %.80s: %s",mailbox,strerror (errno));
 
492
  else return LONGT;            /* success */
 
493
  mm_log (tmp,ERROR);
 
494
  return NIL;
 
495
}
 
496
 
 
497
/* MH mail delete mailbox
 
498
 *          mailbox name to delete
 
499
 * Returns: T on success, NIL on failure
 
500
 */
 
501
 
 
502
long mh_delete (MAILSTREAM *stream,char *mailbox)
 
503
{
 
504
  DIR *dirp;
 
505
  struct direct *d;
 
506
  int i;
 
507
  char tmp[MAILTMPLEN];
 
508
                                /* is mailbox valid? */
 
509
  if (!mh_isvalid (mailbox,tmp,NIL)) {
 
510
    sprintf (tmp,"Can't delete mailbox %.80s: no such mailbox",mailbox);
 
511
    mm_log (tmp,ERROR);
 
512
    return NIL;
 
513
  }
 
514
                                /* get name of directory */
 
515
  i = strlen (mh_file (tmp,mailbox));
 
516
  if (dirp = opendir (tmp)) {   /* open directory */
 
517
    tmp[i++] = '/';             /* now apply trailing delimiter */
 
518
                                /* massacre all mh owned files */
 
519
    while (d = readdir (dirp)) if (mh_dirfmttest (d->d_name)) {
 
520
      strcpy (tmp + i,d->d_name);
 
521
      unlink (tmp);             /* sayonara */
 
522
    }
 
523
    closedir (dirp);            /* flush directory */
 
524
  }
 
525
                                /* try to remove the directory */
 
526
  if (rmdir (mh_file (tmp,mailbox))) {
 
527
    sprintf (tmp,"Can't delete mailbox %.80s: %s",mailbox,strerror (errno));
 
528
    mm_log (tmp,WARN);
 
529
  }
 
530
  return T;                     /* return success */
 
531
}
 
532
 
 
533
/* MH mail rename mailbox
 
534
 * Accepts: MH mail stream
 
535
 *          old mailbox name
 
536
 *          new mailbox name
 
537
 * Returns: T on success, NIL on failure
 
538
 */
 
539
 
 
540
long mh_rename (MAILSTREAM *stream,char *old,char *newname)
 
541
{
 
542
  char c,*s,tmp[MAILTMPLEN],tmp1[MAILTMPLEN];
 
543
  struct stat sbuf;
 
544
                                /* old mailbox name must be valid */
 
545
  if (!mh_isvalid (old,tmp,NIL))
 
546
    sprintf (tmp,"Can't rename mailbox %.80s: no such mailbox",old);
 
547
  else if (!mh_namevalid (newname))
 
548
    sprintf (tmp,"Can't rename to mailbox %.80s: invalid MH-format name",
 
549
             newname);
 
550
                                /* new mailbox name must not be valid */
 
551
  else if (mh_isvalid (newname,tmp,NIL))
 
552
    sprintf (tmp,"Can't rename to mailbox %.80s: destination already exists",
 
553
             newname);
 
554
                                /* success if can rename the directory */
 
555
  else {                        /* found superior to destination name? */
 
556
    if (s = strrchr (mh_file (tmp1,newname),'/')) {
 
557
      c = *++s;                 /* remember first character of inferior */
 
558
      *s = '\0';                /* tie off to get just superior */
 
559
                                /* name doesn't exist, create it */
 
560
      if ((stat (tmp1,&sbuf) || ((sbuf.st_mode & S_IFMT) != S_IFDIR)) &&
 
561
          !dummy_create_path (stream,tmp1,get_dir_protection (newname)))
 
562
        return NIL;
 
563
      *s = c;                   /* restore full name */
 
564
    }
 
565
    if (!rename (mh_file (tmp,old),tmp1)) return T;
 
566
    sprintf (tmp,"Can't rename mailbox %.80s to %.80s: %s",
 
567
             old,newname,strerror (errno));
 
568
  }
 
569
  mm_log (tmp,ERROR);           /* something failed */
 
570
  return NIL;
 
571
}
 
572
 
 
573
/* MH mail open
 
574
 * Accepts: stream to open
 
575
 * Returns: stream on success, NIL on failure
 
576
 */
 
577
 
 
578
MAILSTREAM *mh_open (MAILSTREAM *stream)
 
579
{
 
580
  char tmp[MAILTMPLEN];
 
581
  if (!stream) return &mhproto; /* return prototype for OP_PROTOTYPE call */
 
582
  if (stream->local) fatal ("mh recycle stream");
 
583
  stream->local = fs_get (sizeof (MHLOCAL));
 
584
  /* INBOXness is one of the following:
 
585
   * #mhinbox (case-independent)
 
586
   * #mh/inbox (mh is case-independent, inbox is case-dependent)
 
587
   * INBOX (case-independent
 
588
   */           
 
589
  stream->inbox =               /* note if an INBOX or not */
 
590
    (!compare_cstring (stream->mailbox,MHINBOX) ||
 
591
     ((stream->mailbox[0] == '#') &&
 
592
      ((stream->mailbox[1] == 'm') || (stream->mailbox[1] == 'M')) &&
 
593
      ((stream->mailbox[2] == 'h') || (stream->mailbox[2] == 'H')) &&
 
594
      (stream->mailbox[3] == '/') && !strcmp (stream->mailbox+4,MHINBOXDIR)) ||
 
595
     !compare_cstring (stream->mailbox,"INBOX")) ? T : NIL;
 
596
  mh_file (tmp,stream->mailbox);/* get directory name */
 
597
  LOCAL->dir = cpystr (tmp);    /* copy directory name for later */
 
598
  LOCAL->scantime = 0;          /* not scanned yet */
 
599
  LOCAL->cachedtexts = 0;       /* no cached texts */
 
600
  stream->sequence++;           /* bump sequence number */
 
601
                                /* parse mailbox */
 
602
  stream->nmsgs = stream->recent = 0;
 
603
  if (!mh_ping (stream)) return NIL;
 
604
  if (!(stream->nmsgs || stream->silent))
 
605
    mm_log ("Mailbox is empty",(long) NIL);
 
606
  return stream;                /* return stream to caller */
 
607
}
 
608
 
 
609
/* MH mail close
 
610
 * Accepts: MAIL stream
 
611
 *          close options
 
612
 */
 
613
 
 
614
void mh_close (MAILSTREAM *stream,long options)
 
615
{
 
616
  if (LOCAL) {                  /* only if a file is open */
 
617
    int silent = stream->silent;
 
618
    stream->silent = T;         /* note this stream is dying */
 
619
    if (options & CL_EXPUNGE) mh_expunge (stream,NIL,NIL);
 
620
    if (LOCAL->dir) fs_give ((void **) &LOCAL->dir);
 
621
                                /* nuke the local data */
 
622
    fs_give ((void **) &stream->local);
 
623
    stream->dtb = NIL;          /* log out the DTB */
 
624
    stream->silent = silent;    /* reset silent state */
 
625
  }
 
626
}
 
627
 
 
628
 
 
629
/* MH mail fetch fast information
 
630
 * Accepts: MAIL stream
 
631
 *          sequence
 
632
 *          option flags
 
633
 */
 
634
 
 
635
void mh_fast (MAILSTREAM *stream,char *sequence,long flags)
 
636
{
 
637
  MESSAGECACHE *elt;
 
638
  unsigned long i;
 
639
                                /* set up metadata for all messages */
 
640
  if (stream && LOCAL && ((flags & FT_UID) ?
 
641
                          mail_uid_sequence (stream,sequence) :
 
642
                          mail_sequence (stream,sequence)))
 
643
    for (i = 1; i <= stream->nmsgs; i++)
 
644
      if ((elt = mail_elt (stream,i))->sequence &&
 
645
          !(elt->day && elt->rfc822_size)) mh_load_message (stream,i,NIL);
 
646
}
 
647
 
 
648
/* MH load message into cache
 
649
 * Accepts: MAIL stream
 
650
 *          message #
 
651
 *          option flags
 
652
 */
 
653
 
 
654
void mh_load_message (MAILSTREAM *stream,unsigned long msgno,long flags)
 
655
{
 
656
  unsigned long i,j,nlseen;
 
657
  int fd;
 
658
  unsigned char c,*t;
 
659
  struct stat sbuf;
 
660
  MESSAGECACHE *elt;
 
661
  FDDATA d;
 
662
  STRING bs;
 
663
  elt = mail_elt (stream,msgno);/* get elt */
 
664
                                /* build message file name */
 
665
  sprintf (LOCAL->buf,"%s/%lu",LOCAL->dir,elt->private.uid);
 
666
                                /* anything we need not currently cached? */
 
667
  if ((!elt->day || !elt->rfc822_size ||
 
668
       ((flags & MLM_HEADER) && !elt->private.msg.header.text.data) ||
 
669
       ((flags & MLM_TEXT) && !elt->private.msg.text.text.data)) &&
 
670
      ((fd = open (LOCAL->buf,O_RDONLY,NIL)) >= 0)) {
 
671
    fstat (fd,&sbuf);           /* get file metadata */
 
672
    d.fd = fd;                  /* set up file descriptor */
 
673
    d.pos = 0;                  /* start of file */
 
674
    d.chunk = LOCAL->buf;
 
675
    d.chunksize = CHUNKSIZE;
 
676
    INIT (&bs,fd_string,&d,sbuf.st_size);
 
677
    if (!elt->day) {            /* set internaldate to file date */
 
678
      struct tm *tm = gmtime (&sbuf.st_mtime);
 
679
      elt->day = tm->tm_mday; elt->month = tm->tm_mon + 1;
 
680
      elt->year = tm->tm_year + 1900 - BASEYEAR;
 
681
      elt->hours = tm->tm_hour; elt->minutes = tm->tm_min;
 
682
      elt->seconds = tm->tm_sec;
 
683
      elt->zhours = 0; elt->zminutes = 0;
 
684
    }
 
685
 
 
686
    if (!elt->rfc822_size) {    /* know message size yet? */
 
687
      for (i = 0, j = SIZE (&bs), nlseen = 0; j--; ) switch (SNX (&bs)) {
 
688
      case '\015':              /* unlikely carriage return */
 
689
        if (!j || (CHR (&bs) != '\012')) {
 
690
          i++;                  /* ugh, raw CR */
 
691
          nlseen = NIL;
 
692
          break;
 
693
        }
 
694
        SNX (&bs);              /* eat the line feed, drop in */
 
695
        --j;
 
696
      case '\012':              /* line feed? */
 
697
        i += 2;                 /* count a CRLF */
 
698
                                /* header size known yet? */
 
699
        if (!elt->private.msg.header.text.size && nlseen) {
 
700
                                /* note position in file */
 
701
          elt->private.special.text.size = GETPOS (&bs);
 
702
                                /* and CRLF-adjusted size */
 
703
          elt->private.msg.header.text.size = i;
 
704
        }
 
705
        nlseen = T;             /* note newline seen */
 
706
        break;
 
707
      default:                  /* ordinary chararacter */
 
708
        i++;
 
709
        nlseen = NIL;
 
710
        break;
 
711
      }
 
712
      SETPOS (&bs,0);           /* restore old position */
 
713
      elt->rfc822_size = i;     /* note that we have size now */
 
714
                                /* header is entire message if no delimiter */
 
715
      if (!elt->private.msg.header.text.size)
 
716
        elt->private.msg.header.text.size = elt->rfc822_size;
 
717
                                /* text is remainder of message */
 
718
      elt->private.msg.text.text.size =
 
719
        elt->rfc822_size - elt->private.msg.header.text.size;
 
720
    }
 
721
                                /* need to load cache with message data? */
 
722
    if (((flags & MLM_HEADER) && !elt->private.msg.header.text.data) ||
 
723
        ((flags & MLM_TEXT) && !elt->private.msg.text.text.data)) {
 
724
                                /* purge cache if too big */
 
725
      if (LOCAL->cachedtexts > max (stream->nmsgs * 4096,2097152)) {
 
726
                                /* just can't keep that much */
 
727
        mail_gc (stream,GC_TEXTS);
 
728
        LOCAL->cachedtexts = 0;
 
729
      }
 
730
 
 
731
      if ((flags & MLM_HEADER) && !elt->private.msg.header.text.data) {
 
732
        t = elt->private.msg.header.text.data =
 
733
          (unsigned char *) fs_get (elt->private.msg.header.text.size + 1);
 
734
        LOCAL->cachedtexts += elt->private.msg.header.text.size;
 
735
                                /* read in message header */
 
736
        for (i = 0; i < elt->private.msg.header.text.size; i++)
 
737
          switch (c = SNX (&bs)) {
 
738
          case '\015':          /* unlikely carriage return */
 
739
            *t++ = c;
 
740
            if ((CHR (&bs) == '\012')) {
 
741
              *t++ = SNX (&bs);
 
742
              i++;
 
743
            }
 
744
            break;
 
745
          case '\012':          /* line feed? */
 
746
            *t++ = '\015';
 
747
            i++;
 
748
          default:
 
749
            *t++ = c;
 
750
            break;
 
751
          }
 
752
        *t = '\0';              /* tie off string */
 
753
        if ((t - elt->private.msg.header.text.data) !=
 
754
            elt->private.msg.header.text.size) fatal ("mh hdr size mismatch");
 
755
      }
 
756
      if ((flags & MLM_TEXT) && !elt->private.msg.text.text.data) {
 
757
        t = elt->private.msg.text.text.data =
 
758
          (unsigned char *) fs_get (elt->private.msg.text.text.size + 1);
 
759
        SETPOS (&bs,elt->private.special.text.size);
 
760
        LOCAL->cachedtexts += elt->private.msg.text.text.size;
 
761
                                /* read in message text */
 
762
        for (i = 0; i < elt->private.msg.text.text.size; i++)
 
763
          switch (c = SNX (&bs)) {
 
764
          case '\015':          /* unlikely carriage return */
 
765
            *t++ = c;
 
766
            if ((CHR (&bs) == '\012')) {
 
767
              *t++ = SNX (&bs);
 
768
              i++;
 
769
            }
 
770
            break;
 
771
          case '\012':          /* line feed? */
 
772
            *t++ = '\015';
 
773
            i++;
 
774
          default:
 
775
            *t++ = c;
 
776
            break;
 
777
          }
 
778
        *t = '\0';              /* tie off string */
 
779
        if ((t - elt->private.msg.text.text.data) !=
 
780
            elt->private.msg.text.text.size) fatal ("mh txt size mismatch");
 
781
      }
 
782
    }
 
783
    close (fd);                 /* flush message file */
 
784
  }
 
785
}
 
786
 
 
787
/* MH mail fetch message header
 
788
 * Accepts: MAIL stream
 
789
 *          message # to fetch
 
790
 *          pointer to returned header text length
 
791
 *          option flags
 
792
 * Returns: message header in RFC822 format
 
793
 */
 
794
 
 
795
char *mh_header (MAILSTREAM *stream,unsigned long msgno,unsigned long *length,
 
796
                 long flags)
 
797
{
 
798
  MESSAGECACHE *elt;
 
799
  *length = 0;                  /* default to empty */
 
800
  if (flags & FT_UID) return "";/* UID call "impossible" */
 
801
  elt = mail_elt (stream,msgno);/* get elt */
 
802
  if (!elt->private.msg.header.text.data)
 
803
    mh_load_message (stream,msgno,MLM_HEADER);
 
804
  *length = elt->private.msg.header.text.size;
 
805
  return (char *) elt->private.msg.header.text.data;
 
806
}
 
807
 
 
808
 
 
809
/* MH mail fetch message text (body only)
 
810
 * Accepts: MAIL stream
 
811
 *          message # to fetch
 
812
 *          pointer to returned stringstruct
 
813
 *          option flags
 
814
 * Returns: T on success, NIL on failure
 
815
 */
 
816
 
 
817
long mh_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags)
 
818
{
 
819
  MESSAGECACHE *elt;
 
820
                                /* UID call "impossible" */
 
821
  if (flags & FT_UID) return NIL;
 
822
  elt = mail_elt (stream,msgno);/* get elt */
 
823
                                /* snarf message if don't have it yet */
 
824
  if (!elt->private.msg.text.text.data) {
 
825
    mh_load_message (stream,msgno,MLM_TEXT);
 
826
    if (!elt->private.msg.text.text.data) return NIL;
 
827
  }
 
828
  if (!(flags & FT_PEEK)) {     /* mark as seen */
 
829
    mail_elt (stream,msgno)->seen = T;
 
830
    mm_flags (stream,msgno);
 
831
  }
 
832
  INIT (bs,mail_string,elt->private.msg.text.text.data,
 
833
        elt->private.msg.text.text.size);
 
834
  return T;
 
835
}
 
836
 
 
837
/* MH mail ping mailbox
 
838
 * Accepts: MAIL stream
 
839
 * Returns: T if stream alive, else NIL
 
840
 */
 
841
 
 
842
long mh_ping (MAILSTREAM *stream)
 
843
{
 
844
  MAILSTREAM *sysibx = NIL;
 
845
  MESSAGECACHE *elt,*selt;
 
846
  struct stat sbuf;
 
847
  char *s,tmp[MAILTMPLEN];
 
848
  int fd;
 
849
  unsigned long i,j,r;
 
850
  unsigned long old = stream->uid_last;
 
851
  long nmsgs = stream->nmsgs;
 
852
  long recent = stream->recent;
 
853
  int silent = stream->silent;
 
854
  if (stat (LOCAL->dir,&sbuf)) {/* directory exists? */
 
855
    if (stream->inbox &&        /* no, create if INBOX */
 
856
        dummy_create_path (stream,strcat (mh_file (tmp,MHINBOX),"/"),
 
857
                           get_dir_protection ("INBOX"))) return T;
 
858
    sprintf (tmp,"Can't open mailbox %.80s: no such mailbox",stream->mailbox);
 
859
    mm_log (tmp,ERROR);
 
860
    return NIL;
 
861
  }
 
862
  stream->silent = T;           /* don't pass up mm_exists() events yet */
 
863
  if (sbuf.st_ctime != LOCAL->scantime) {
 
864
    struct direct **names = NIL;
 
865
    long nfiles = scandir (LOCAL->dir,&names,mh_select,mh_numsort);
 
866
    if (nfiles < 0) nfiles = 0; /* in case error */
 
867
                                /* note scanned now */
 
868
    LOCAL->scantime = sbuf.st_ctime;
 
869
                                /* scan directory */
 
870
    for (i = 0; i < nfiles; ++i) {
 
871
                                /* if newly seen, add to list */
 
872
      if ((j = atoi (names[i]->d_name)) > old) {
 
873
        mail_exists (stream,++nmsgs);
 
874
        stream->uid_last = (elt = mail_elt (stream,nmsgs))->private.uid = j;
 
875
        elt->valid = T;         /* note valid flags */
 
876
        if (old) {              /* other than the first pass? */
 
877
          elt->recent = T;      /* yup, mark as recent */
 
878
          recent++;             /* bump recent count */
 
879
        }
 
880
        else {                  /* see if already read */
 
881
          sprintf (tmp,"%s/%s",LOCAL->dir,names[i]->d_name);
 
882
          if (!stat (tmp,&sbuf) && (sbuf.st_atime > sbuf.st_mtime))
 
883
            elt->seen = T;
 
884
        }
 
885
      }
 
886
      fs_give ((void **) &names[i]);
 
887
    }
 
888
                                /* free directory */
 
889
    if (s = (void *) names) fs_give ((void **) &s);
 
890
  }
 
891
 
 
892
                                /* if INBOX, snarf from system INBOX  */
 
893
  if (stream->inbox && strcmp (sysinbox (),stream->mailbox)) {
 
894
    old = stream->uid_last;
 
895
    mm_critical (stream);       /* go critical */
 
896
                                /* see if anything in system inbox */
 
897
    if (!stat (sysinbox (),&sbuf) && sbuf.st_size &&
 
898
        (sysibx = mail_open (sysibx,sysinbox (),OP_SILENT)) &&
 
899
        !sysibx->rdonly && (r = sysibx->nmsgs)) {
 
900
      for (i = 1; i <= r; ++i) {/* for each message in sysinbox mailbox */
 
901
                                /* build file name we will use */
 
902
        sprintf (LOCAL->buf,"%s/%lu",LOCAL->dir,++old);
 
903
                                /* snarf message from Berkeley mailbox */
 
904
        selt = mail_elt (sysibx,i);
 
905
        if (((fd = open (LOCAL->buf,O_WRONLY|O_CREAT|O_EXCL,
 
906
                         (int) mail_parameters (NIL,GET_MBXPROTECTION,NIL)))
 
907
             >= 0) &&
 
908
            (s = mail_fetchheader_full (sysibx,i,NIL,&j,FT_INTERNAL)) &&
 
909
            (write (fd,s,j) == j) &&
 
910
            (s = mail_fetchtext_full (sysibx,i,&j,FT_INTERNAL|FT_PEEK)) &&
 
911
            (write (fd,s,j) == j) && !fsync (fd) && !close (fd)) {
 
912
                                /* swell the cache */
 
913
          mail_exists (stream,++nmsgs);
 
914
          stream->uid_last =    /* create new elt, note its file number */
 
915
            (elt = mail_elt (stream,nmsgs))->private.uid = old;
 
916
          recent++;             /* bump recent count */
 
917
                                /* set up initial flags and date */
 
918
          elt->valid = elt->recent = T;
 
919
          elt->seen = selt->seen;
 
920
          elt->deleted = selt->deleted;
 
921
          elt->flagged = selt->flagged;
 
922
          elt->answered = selt->answered;
 
923
          elt->draft = selt->draft;
 
924
          elt->day = selt->day;elt->month = selt->month;elt->year = selt->year;
 
925
          elt->hours = selt->hours;elt->minutes = selt->minutes;
 
926
          elt->seconds = selt->seconds;
 
927
          elt->zhours = selt->zhours; elt->zminutes = selt->zminutes;
 
928
          mh_setdate (LOCAL->buf,elt);
 
929
          sprintf (tmp,"%lu",i);/* delete it from the sysinbox */
 
930
          mail_flag (sysibx,tmp,"\\Deleted",ST_SET);
 
931
        }
 
932
 
 
933
        else {                  /* failed to snarf */
 
934
          if (fd) {             /* did it ever get opened? */
 
935
            close (fd);         /* close descriptor */
 
936
            unlink (LOCAL->buf);/* flush this file */
 
937
          }
 
938
          sprintf (tmp,"Message copy to MH mailbox failed: %.80s",
 
939
                   s,strerror (errno));
 
940
          mm_log (tmp,ERROR);
 
941
          r = 0;                /* stop the snarf in its tracks */
 
942
        }
 
943
      }
 
944
                                /* update scan time */
 
945
      if (!stat (LOCAL->dir,&sbuf)) LOCAL->scantime = sbuf.st_ctime;      
 
946
      mail_expunge (sysibx);    /* now expunge all those messages */
 
947
    }
 
948
    if (sysibx) mail_close (sysibx);
 
949
    mm_nocritical (stream);     /* release critical */
 
950
  }
 
951
  stream->silent = silent;      /* can pass up events now */
 
952
  mail_exists (stream,nmsgs);   /* notify upper level of mailbox size */
 
953
  mail_recent (stream,recent);
 
954
  return T;                     /* return that we are alive */
 
955
}
 
956
 
 
957
/* MH mail check mailbox
 
958
 * Accepts: MAIL stream
 
959
 */
 
960
 
 
961
void mh_check (MAILSTREAM *stream)
 
962
{
 
963
  /* Perhaps in the future this will preserve flags */
 
964
  if (mh_ping (stream)) mm_log ("Check completed",(long) NIL);
 
965
}
 
966
 
 
967
 
 
968
/* MH mail expunge mailbox
 
969
 * Accepts: MAIL stream
 
970
 *          sequence to expunge if non-NIL
 
971
 *          expunge options
 
972
 * Returns: T, always
 
973
 */
 
974
 
 
975
long mh_expunge (MAILSTREAM *stream,char *sequence,long options)
 
976
{
 
977
  long ret;
 
978
  MESSAGECACHE *elt;
 
979
  unsigned long i = 1;
 
980
  unsigned long n = 0;
 
981
  unsigned long recent = stream->recent;
 
982
  if (ret = sequence ? ((options & EX_UID) ?
 
983
                        mail_uid_sequence (stream,sequence) :
 
984
                        mail_sequence (stream,sequence)) : LONGT) {
 
985
    mm_critical (stream);       /* go critical */
 
986
    while (i <= stream->nmsgs) {/* for each message */
 
987
      elt = mail_elt (stream,i);/* if deleted, need to trash it */
 
988
      if (elt->deleted && (sequence ? elt->sequence : T)) {
 
989
        sprintf (LOCAL->buf,"%s/%lu",LOCAL->dir,elt->private.uid);
 
990
        if (unlink (LOCAL->buf)) {/* try to delete the message */
 
991
          sprintf (LOCAL->buf,"Expunge of message %lu failed, aborted: %s",i,
 
992
                   strerror (errno));
 
993
          mm_log (LOCAL->buf,(long) NIL);
 
994
          break;
 
995
        }
 
996
                                /* note uncached */
 
997
        LOCAL->cachedtexts -= ((elt->private.msg.header.text.data ?
 
998
                                elt->private.msg.header.text.size : 0) +
 
999
                               (elt->private.msg.text.text.data ?
 
1000
                                elt->private.msg.text.text.size : 0));
 
1001
        mail_gc_msg (&elt->private.msg,GC_ENV | GC_TEXTS);
 
1002
                                /* if recent, note one less recent message */
 
1003
        if (elt->recent) --recent;
 
1004
                                /* notify upper levels */
 
1005
        mail_expunged (stream,i);
 
1006
        n++;                    /* count up one more expunged message */
 
1007
      }
 
1008
      else i++;                 /* otherwise try next message */
 
1009
    }
 
1010
    if (n) {                    /* output the news if any expunged */
 
1011
      sprintf (LOCAL->buf,"Expunged %lu messages",n);
 
1012
      mm_log (LOCAL->buf,(long) NIL);
 
1013
    }
 
1014
    else mm_log ("No messages deleted, so no update needed",(long) NIL);
 
1015
    mm_nocritical (stream);     /* release critical */
 
1016
                                /* notify upper level of new mailbox size */
 
1017
    mail_exists (stream,stream->nmsgs);
 
1018
    mail_recent (stream,recent);
 
1019
  }
 
1020
  return ret;
 
1021
}
 
1022
 
 
1023
/* MH mail copy message(s)
 
1024
 * Accepts: MAIL stream
 
1025
 *          sequence
 
1026
 *          destination mailbox
 
1027
 *          copy options
 
1028
 * Returns: T if copy successful, else NIL
 
1029
 */
 
1030
 
 
1031
long mh_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options)
 
1032
{
 
1033
  FDDATA d;
 
1034
  STRING st;
 
1035
  MESSAGECACHE *elt;
 
1036
  struct stat sbuf;
 
1037
  int fd;
 
1038
  unsigned long i;
 
1039
  char flags[MAILTMPLEN],date[MAILTMPLEN];
 
1040
  appenduid_t au = (appenduid_t) mail_parameters (NIL,GET_APPENDUID,NIL);
 
1041
  long ret = NIL;
 
1042
                                /* copy the messages */
 
1043
  if ((options & CP_UID) ? mail_uid_sequence (stream,sequence) :
 
1044
      mail_sequence (stream,sequence))
 
1045
    for (i = 1; i <= stream->nmsgs; i++) 
 
1046
      if ((elt = mail_elt (stream,i))->sequence) {
 
1047
        sprintf (LOCAL->buf,"%s/%lu",LOCAL->dir,elt->private.uid);
 
1048
        if ((fd = open (LOCAL->buf,O_RDONLY,NIL)) < 0) return NIL;
 
1049
        fstat (fd,&sbuf);       /* get size of message */
 
1050
        if (!elt->day) {        /* set internaldate to file date if needed */
 
1051
          struct tm *tm = gmtime (&sbuf.st_mtime);
 
1052
          elt->day = tm->tm_mday; elt->month = tm->tm_mon + 1;
 
1053
          elt->year = tm->tm_year + 1900 - BASEYEAR;
 
1054
          elt->hours = tm->tm_hour; elt->minutes = tm->tm_min;
 
1055
          elt->seconds = tm->tm_sec;
 
1056
          elt->zhours = 0; elt->zminutes = 0;
 
1057
        }
 
1058
        d.fd = fd;              /* set up file descriptor */
 
1059
        d.pos = 0;              /* start of file */
 
1060
        d.chunk = LOCAL->buf;
 
1061
        d.chunksize = CHUNKSIZE;
 
1062
                                /* kludge; mh_append would just strip CRs */
 
1063
        INIT (&st,fd_string,&d,sbuf.st_size);
 
1064
                                /* init flag string */
 
1065
        flags[0] = flags[1] = '\0';
 
1066
        if (elt->seen) strcat (flags," \\Seen");
 
1067
        if (elt->deleted) strcat (flags," \\Deleted");
 
1068
        if (elt->flagged) strcat (flags," \\Flagged");
 
1069
        if (elt->answered) strcat (flags," \\Answered");
 
1070
        if (elt->draft) strcat (flags," \\Draft");
 
1071
        flags[0] = '(';         /* open list */
 
1072
        strcat (flags,")");     /* close list */
 
1073
        mail_date (date,elt);   /* generate internal date */
 
1074
        if (au) mail_parameters (NIL,SET_APPENDUID,NIL);
 
1075
        if ((ret = mail_append_full (NIL,mailbox,flags,date,&st)) &&
 
1076
            (options & CP_MOVE)) elt->deleted = T;
 
1077
        if (au) mail_parameters (NIL,SET_APPENDUID,(void *) au);
 
1078
        close (fd);
 
1079
      }
 
1080
  if (ret && mail_parameters (NIL,GET_COPYUID,NIL))
 
1081
    mm_log ("Can not return meaningful COPYUID with this mailbox format",WARN);
 
1082
  return ret;                   /* return success */
 
1083
}
 
1084
 
 
1085
/* MH mail append message from stringstruct
 
1086
 * Accepts: MAIL stream
 
1087
 *          destination mailbox
 
1088
 *          append callback
 
1089
 *          data for callback
 
1090
 * Returns: T if append successful, else NIL
 
1091
 */
 
1092
 
 
1093
long mh_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data)
 
1094
{
 
1095
  struct direct **names = NIL;
 
1096
  int fd;
 
1097
  char c,*flags,*date,*s,tmp[MAILTMPLEN];
 
1098
  STRING *message;
 
1099
  MESSAGECACHE elt;
 
1100
  FILE *df;
 
1101
  long i,size,last,nfiles;
 
1102
  long ret = LONGT;
 
1103
                                /* default stream to prototype */
 
1104
  if (!stream) stream = &mhproto;
 
1105
                                /* make sure valid mailbox */
 
1106
  if (!mh_isvalid (mailbox,tmp,NIL)) switch (errno) {
 
1107
  case ENOENT:                  /* no such file? */
 
1108
    if (!((!compare_cstring (mailbox,MHINBOX) ||
 
1109
           !compare_cstring (mailbox,"INBOX")) &&
 
1110
          (mh_file (tmp,MHINBOX) &&
 
1111
           dummy_create_path (stream,strcat (tmp,"/"),
 
1112
                              get_dir_protection (mailbox))))) {
 
1113
      mm_notify (stream,"[TRYCREATE] Must create mailbox before append",NIL);
 
1114
      return NIL;
 
1115
    }
 
1116
                                /* falls through */
 
1117
  case 0:                       /* merely empty file? */
 
1118
    break;
 
1119
  case EINVAL:
 
1120
    sprintf (tmp,"Invalid MH-format mailbox name: %.80s",mailbox);
 
1121
    mm_log (tmp,ERROR);
 
1122
    return NIL;
 
1123
  default:
 
1124
    sprintf (tmp,"Not a MH-format mailbox: %.80s",mailbox);
 
1125
    mm_log (tmp,ERROR);
 
1126
    return NIL;
 
1127
  }
 
1128
                                /* get first message */
 
1129
  if (!(*af) (stream,data,&flags,&date,&message)) return NIL;
 
1130
  if ((nfiles = scandir (tmp,&names,mh_select,mh_numsort)) > 0) {
 
1131
                                /* largest number */
 
1132
    last = atoi (names[nfiles-1]->d_name);    
 
1133
    for (i = 0; i < nfiles; ++i) /* free directory */
 
1134
      fs_give ((void **) &names[i]);
 
1135
  }
 
1136
  else last = 0;                /* no messages here yet */
 
1137
  if (s = (void *) names) fs_give ((void **) &s);
 
1138
 
 
1139
  mm_critical (stream);         /* go critical */
 
1140
  do {
 
1141
    if (!SIZE (message)) {      /* guard against zero-length */
 
1142
      mm_log ("Append of zero-length message",ERROR);
 
1143
      ret = NIL;
 
1144
      break;
 
1145
    }
 
1146
    if (date) {                 /* want to preserve date? */
 
1147
                                /* yes, parse date into an elt */
 
1148
      if (!mail_parse_date (&elt,date)) {
 
1149
        sprintf (tmp,"Bad date in append: %.80s",date);
 
1150
        mm_log (tmp,ERROR);
 
1151
        ret = NIL;
 
1152
        break;
 
1153
      }
 
1154
    }
 
1155
    mh_file (tmp,mailbox);      /* build file name we will use */
 
1156
    sprintf (tmp + strlen (tmp),"/%ld",++last);
 
1157
    if (((fd = open (tmp,O_WRONLY|O_CREAT|O_EXCL,
 
1158
                     (int) mail_parameters (NIL,GET_MBXPROTECTION,NIL))) < 0)||
 
1159
        !(df = fdopen (fd,"ab"))) {
 
1160
      sprintf (tmp,"Can't open append message: %s",strerror (errno));
 
1161
      mm_log (tmp,ERROR);
 
1162
      ret = NIL;
 
1163
      break;
 
1164
    }
 
1165
                                /* copy the data w/o CR's */
 
1166
    for (size = 0,i = SIZE (message); i && ret; --i)
 
1167
      if (((c = SNX (message)) != '\015') && (putc (c,df) == EOF)) ret = NIL;
 
1168
                                /* close the file */
 
1169
    if (!ret || fclose (df)) {
 
1170
      unlink (tmp);             /* delete message */
 
1171
      sprintf (tmp,"Message append failed: %s",strerror (errno));
 
1172
      mm_log (tmp,ERROR);
 
1173
      ret = NIL;
 
1174
    }
 
1175
    if (ret) {                  /* set the date for this message */
 
1176
      if (date) mh_setdate (tmp,&elt);
 
1177
                                /* get next message */
 
1178
      if (!(*af) (stream,data,&flags,&date,&message)) ret = NIL;
 
1179
    }
 
1180
  } while (ret && message);
 
1181
  mm_nocritical (stream);       /* release critical */
 
1182
  if (ret && mail_parameters (NIL,GET_APPENDUID,NIL))
 
1183
    mm_log ("Can not return meaningful APPENDUID with this mailbox format",
 
1184
            WARN);
 
1185
  return ret;
 
1186
}
 
1187
 
 
1188
/* Internal routines */
 
1189
 
 
1190
 
 
1191
/* MH file name selection test
 
1192
 * Accepts: candidate directory entry
 
1193
 * Returns: T to use file name, NIL to skip it
 
1194
 */
 
1195
 
 
1196
int mh_select (struct direct *name)
 
1197
{
 
1198
  char c;
 
1199
  char *s = name->d_name;
 
1200
  while (c = *s++) if (!isdigit (c)) return NIL;
 
1201
  return T;
 
1202
}
 
1203
 
 
1204
 
 
1205
/* MH file name comparision
 
1206
 * Accepts: first candidate directory entry
 
1207
 *          second candidate directory entry
 
1208
 * Returns: negative if d1 < d2, 0 if d1 == d2, postive if d1 > d2
 
1209
 */
 
1210
 
 
1211
int mh_numsort (const void *d1,const void *d2)
 
1212
{
 
1213
  return atoi ((*(struct direct **) d1)->d_name) -
 
1214
    atoi ((*(struct direct **) d2)->d_name);
 
1215
}
 
1216
 
 
1217
 
 
1218
/* MH mail build file name
 
1219
 * Accepts: destination string
 
1220
 *          source
 
1221
 * Returns: destination
 
1222
 */
 
1223
 
 
1224
char *mh_file (char *dst,char *name)
 
1225
{
 
1226
  char *s;
 
1227
  char *path = mh_path (dst);
 
1228
  if (!path) fatal ("No mh path in mh_file()!");
 
1229
                                /* INBOX becomes "inbox" in the MH path */
 
1230
  if (!compare_cstring (name,MHINBOX) || !compare_cstring (name,"INBOX"))
 
1231
    sprintf (dst,"%.900s/%.80s",path,MHINBOXDIR);
 
1232
                                /* #mh names skip past prefix */
 
1233
  else if (*name == '#') sprintf (dst,"%.100s/%.900s",path,name + 4);
 
1234
  else mailboxfile (dst,name);  /* all other names */
 
1235
                                /* tie off unnecessary trailing / */
 
1236
  if ((s = strrchr (dst,'/')) && !s[1] && (s[-1] == '/')) *s = '\0';
 
1237
  return dst;
 
1238
}
 
1239
 
 
1240
/* MH canonicalize name
 
1241
 * Accepts: buffer to write name
 
1242
 *          reference
 
1243
 *          pattern
 
1244
 * Returns: T if success, NIL if failure
 
1245
 */
 
1246
 
 
1247
long mh_canonicalize (char *pattern,char *ref,char *pat)
 
1248
{
 
1249
  unsigned long i;
 
1250
  char *s,tmp[MAILTMPLEN];
 
1251
  if (ref && *ref) {            /* have a reference */
 
1252
    strcpy (pattern,ref);       /* copy reference to pattern */
 
1253
                                /* # overrides mailbox field in reference */
 
1254
    if (*pat == '#') strcpy (pattern,pat);
 
1255
                                /* pattern starts, reference ends, with / */
 
1256
    else if ((*pat == '/') && (pattern[strlen (pattern) - 1] == '/'))
 
1257
      strcat (pattern,pat + 1); /* append, omitting one of the period */
 
1258
    else strcat (pattern,pat);  /* anything else is just appended */
 
1259
  }
 
1260
  else strcpy (pattern,pat);    /* just have basic name */
 
1261
  if (mh_isvalid (pattern,tmp,T)) {
 
1262
                                /* count wildcards */
 
1263
    for (i = 0, s = pattern; *s; *s++) if ((*s == '*') || (*s == '%')) ++i;
 
1264
                                /* success if not too many */
 
1265
    if (i <= MAXWILDCARDS) return LONGT;
 
1266
    MM_LOG ("Excessive wildcards in LIST/LSUB",ERROR);
 
1267
  }
 
1268
  return NIL;
 
1269
}
 
1270
 
 
1271
/* Set date for message
 
1272
 * Accepts: file name
 
1273
 *          elt containing date
 
1274
 */
 
1275
 
 
1276
void mh_setdate (char *file,MESSAGECACHE *elt)
 
1277
{
 
1278
  time_t tp[2];
 
1279
  tp[0] = time (0);             /* atime is now */
 
1280
  tp[1] = mail_longdate (elt);  /* modification time */
 
1281
  utime (file,tp);              /* set the times */
 
1282
}