imapext-2007

diff src/osdep/os2/mbxnt.c @ 0:ada5e610ab86

imap-2007e
author yuuji@gentei.org
date Mon, 14 Sep 2009 15:17:45 +0900
parents
children
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/osdep/os2/mbxnt.c	Mon Sep 14 15:17:45 2009 +0900
     1.3 @@ -0,0 +1,1694 @@
     1.4 +/* ========================================================================
     1.5 + * Copyright 1988-2007 University of Washington
     1.6 + *
     1.7 + * Licensed under the Apache License, Version 2.0 (the "License");
     1.8 + * you may not use this file except in compliance with the License.
     1.9 + * You may obtain a copy of the License at
    1.10 + *
    1.11 + *     http://www.apache.org/licenses/LICENSE-2.0
    1.12 + *
    1.13 + * 
    1.14 + * ========================================================================
    1.15 + */
    1.16 +
    1.17 +/*
    1.18 + * Program:	MBX mail routines
    1.19 + *
    1.20 + * Author:	Mark Crispin
    1.21 + *		Networks and Distributed Computing
    1.22 + *		Computing & Communications
    1.23 + *		University of Washington
    1.24 + *		Administration Building, AG-44
    1.25 + *		Seattle, WA  98195
    1.26 + *		Internet: MRC@CAC.Washington.EDU
    1.27 + *
    1.28 + * Date:	3 October 1995
    1.29 + * Last Edited:	28 September 2007
    1.30 + */
    1.31 +
    1.32 +
    1.33 +/*				FILE TIME SEMANTICS
    1.34 + *
    1.35 + * The atime is the last read time of the file.
    1.36 + * The mtime is the last flags update time of the file.
    1.37 + * The ctime is the last write time of the file.
    1.38 + */
    1.39 +
    1.40 +#include <stdio.h>
    1.41 +#include <ctype.h>
    1.42 +#include <errno.h>
    1.43 +extern int errno;		/* just in case */
    1.44 +#include "mail.h"
    1.45 +#include "osdep.h"
    1.46 +#include <fcntl.h>
    1.47 +#include <time.h>
    1.48 +#include <sys/stat.h>
    1.49 +#include <sys/utime.h>
    1.50 +#include "misc.h"
    1.51 +#include "dummy.h"
    1.52 +#include "fdstring.h"
    1.53 +
    1.54 +
    1.55 +/* Build parameters */
    1.56 +
    1.57 +#define HDRSIZE 2048
    1.58 +
    1.59 +/* MBX I/O stream local data */
    1.60 +	
    1.61 +typedef struct mbx_local {
    1.62 +  unsigned int flagcheck: 1;	/* if ping should sweep for flags */
    1.63 +  unsigned int expok: 1;	/* if expunging OK in ping */
    1.64 +  unsigned int expunged : 1;	/* if one or more expunged messages */
    1.65 +  int fd;			/* file descriptor for I/O */
    1.66 +  int ld;			/* lock file descriptor */
    1.67 +  int ffuserflag;		/* first free user flag */
    1.68 +  off_t filesize;		/* file size parsed */
    1.69 +  time_t filetime;		/* last file time */
    1.70 +  time_t lastsnarf;		/* last snarf time */
    1.71 +  unsigned char *buf;		/* temporary buffer */
    1.72 +  unsigned long buflen;		/* current size of temporary buffer */
    1.73 +  char lock[MAILTMPLEN];	/* buffer to write lock name */
    1.74 +} MBXLOCAL;
    1.75 +
    1.76 +
    1.77 +/* Convenient access to local data */
    1.78 +
    1.79 +#define LOCAL ((MBXLOCAL *) stream->local)
    1.80 +
    1.81 +/* Function prototypes */
    1.82 +
    1.83 +DRIVER *mbx_valid (char *name);
    1.84 +int mbx_isvalid (MAILSTREAM **stream,char *name,char *file,int *ld,char *lock,
    1.85 +		 long flags);
    1.86 +void *mbx_parameters (long function,void *value);
    1.87 +void mbx_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents);
    1.88 +void mbx_list (MAILSTREAM *stream,char *ref,char *pat);
    1.89 +void mbx_lsub (MAILSTREAM *stream,char *ref,char *pat);
    1.90 +long mbx_create (MAILSTREAM *stream,char *mailbox);
    1.91 +long mbx_delete (MAILSTREAM *stream,char *mailbox);
    1.92 +long mbx_rename (MAILSTREAM *stream,char *old,char *newname);
    1.93 +long mbx_status (MAILSTREAM *stream,char *mbx,long flags);
    1.94 +MAILSTREAM *mbx_open (MAILSTREAM *stream);
    1.95 +void mbx_close (MAILSTREAM *stream,long options);
    1.96 +void mbx_abort (MAILSTREAM *stream);
    1.97 +void mbx_flags (MAILSTREAM *stream,char *sequence,long flags);
    1.98 +char *mbx_header (MAILSTREAM *stream,unsigned long msgno,unsigned long *length,
    1.99 +		  long flags);
   1.100 +long mbx_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags);
   1.101 +void mbx_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags);
   1.102 +void mbx_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt);
   1.103 +long mbx_ping (MAILSTREAM *stream);
   1.104 +void mbx_check (MAILSTREAM *stream);
   1.105 +long mbx_expunge (MAILSTREAM *stream,char *sequence,long options);
   1.106 +void mbx_snarf (MAILSTREAM *stream);
   1.107 +long mbx_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options);
   1.108 +long mbx_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data);
   1.109 +
   1.110 +long mbx_parse (MAILSTREAM *stream);
   1.111 +MESSAGECACHE *mbx_elt (MAILSTREAM *stream,unsigned long msgno,long expok);
   1.112 +unsigned long mbx_read_flags (MAILSTREAM *stream,MESSAGECACHE *elt);
   1.113 +void mbx_update_header (MAILSTREAM *stream);
   1.114 +void mbx_update_status (MAILSTREAM *stream,unsigned long msgno,long flags);
   1.115 +unsigned long mbx_hdrpos (MAILSTREAM *stream,unsigned long msgno,
   1.116 +			  unsigned long *size,char **hdr);
   1.117 +unsigned long mbx_rewrite (MAILSTREAM *stream,unsigned long *reclaimed,
   1.118 +			   long flags);
   1.119 +long mbx_flaglock (MAILSTREAM *stream);
   1.120 +
   1.121 +/* MBX mail routines */
   1.122 +
   1.123 +
   1.124 +/* Driver dispatch used by MAIL */
   1.125 +
   1.126 +DRIVER mbxdriver = {
   1.127 +  "mbx",			/* driver name */
   1.128 +  DR_LOCAL|DR_MAIL|DR_CRLF|DR_LOCKING,
   1.129 +				/* driver flags */
   1.130 +  (DRIVER *) NIL,		/* next driver */
   1.131 +  mbx_valid,			/* mailbox is valid for us */
   1.132 +  mbx_parameters,		/* manipulate parameters */
   1.133 +  mbx_scan,			/* scan mailboxes */
   1.134 +  mbx_list,			/* list mailboxes */
   1.135 +  mbx_lsub,			/* list subscribed mailboxes */
   1.136 +  NIL,				/* subscribe to mailbox */
   1.137 +  NIL,				/* unsubscribe from mailbox */
   1.138 +  mbx_create,			/* create mailbox */
   1.139 +  mbx_delete,			/* delete mailbox */
   1.140 +  mbx_rename,			/* rename mailbox */
   1.141 +  mail_status_default,		/* status of mailbox */
   1.142 +  mbx_open,			/* open mailbox */
   1.143 +  mbx_close,			/* close mailbox */
   1.144 +  mbx_flags,			/* fetch message "fast" attributes */
   1.145 +  mbx_flags,			/* fetch message flags */
   1.146 +  NIL,				/* fetch overview */
   1.147 +  NIL,				/* fetch message envelopes */
   1.148 +  mbx_header,			/* fetch message header */
   1.149 +  mbx_text,			/* fetch message body */
   1.150 +  NIL,				/* fetch partial message text */
   1.151 +  NIL,				/* unique identifier */
   1.152 +  NIL,				/* message number */
   1.153 +  mbx_flag,			/* modify flags */
   1.154 +  mbx_flagmsg,			/* per-message modify flags */
   1.155 +  NIL,				/* search for message based on criteria */
   1.156 +  NIL,				/* sort messages */
   1.157 +  NIL,				/* thread messages */
   1.158 +  mbx_ping,			/* ping mailbox to see if still alive */
   1.159 +  mbx_check,			/* check for new messages */
   1.160 +  mbx_expunge,			/* expunge deleted messages */
   1.161 +  mbx_copy,			/* copy messages to another mailbox */
   1.162 +  mbx_append,			/* append string message to mailbox */
   1.163 +  NIL				/* garbage collect stream */
   1.164 +};
   1.165 +
   1.166 +				/* prototype stream */
   1.167 +MAILSTREAM mbxproto = {&mbxdriver};
   1.168 +
   1.169 +/* MBX mail validate mailbox
   1.170 + * Accepts: mailbox name
   1.171 + * Returns: our driver if name is valid, NIL otherwise
   1.172 + */
   1.173 +
   1.174 +DRIVER *mbx_valid (char *name)
   1.175 +{
   1.176 +  char tmp[MAILTMPLEN];
   1.177 +  int fd = mbx_isvalid (NIL,name,tmp,NIL,NIL,NIL);
   1.178 +  if (fd < 0) return NIL;
   1.179 +  close (fd);			/* don't need the fd now */
   1.180 +  return &mbxdriver;
   1.181 +}
   1.182 +
   1.183 +
   1.184 +/* MBX mail test for valid mailbox
   1.185 + * Accepts: returned stream with valid mailbox keywords
   1.186 + *	    mailbox name
   1.187 + *	    buffer to write file name
   1.188 + *	    returned lock fd
   1.189 + *	    returned lock name
   1.190 + *	    RW flags or NIL for readonly
   1.191 + * Returns: file descriptor if valid, NIL otherwise
   1.192 + */
   1.193 +
   1.194 +#define MBXISVALIDNOUID 0x1	/* RW, don't do UID action */
   1.195 +#define MBXISVALIDUID 0x2	/* RW, do UID action */
   1.196 +
   1.197 +int mbx_isvalid (MAILSTREAM **stream,char *name,char *file,int *ld,char *lock,
   1.198 +		 long flags)
   1.199 +{
   1.200 +  int fd,upd;
   1.201 +  int ret = -1;
   1.202 +  unsigned long i;
   1.203 +  long j,k;
   1.204 +  off_t pos;
   1.205 +  char c,*s,*t,hdr[HDRSIZE];
   1.206 +  struct stat sbuf;
   1.207 +  struct utimbuf times;
   1.208 +  int error = EINVAL;		/* assume invalid argument */
   1.209 +  if (ld) *ld = -1;		/* initially no lock */
   1.210 +				/* if file, get its status */
   1.211 +  if ((s = dummy_file (file,name)) && !stat (s,&sbuf) &&
   1.212 +      ((sbuf.st_mode & S_IFMT) == S_IFREG) &&
   1.213 +      ((fd = open (file,(flags ? O_RDWR : O_RDONLY)|O_BINARY,NIL)) >= 0)) {
   1.214 +    error = -1;			/* assume bogus format */
   1.215 +    if (((((j = read (fd,hdr,HDRSIZE)) == HDRSIZE) && (hdr[0] == '*')) ||
   1.216 +				/* locked, set byte 0 to "*", read rest */
   1.217 +	 ((j < 0) && (lseek (fd,1,L_SET) == 1) &&
   1.218 +	  (read (fd,hdr+1,HDRSIZE-1) == (HDRSIZE-1)) && (hdr[0] = '*'))) &&
   1.219 +	(hdr[1] == 'm') && (hdr[2] == 'b') && (hdr[3] == 'x') &&
   1.220 +	(hdr[4] == '*') && (hdr[5] == '\015') && (hdr[6] == '\012') &&
   1.221 +	isxdigit (hdr[7]) && isxdigit (hdr[8]) && isxdigit (hdr[9]) &&
   1.222 +	isxdigit (hdr[10]) && isxdigit (hdr[11]) && isxdigit (hdr[12]) &&
   1.223 +	isxdigit (hdr[13]) && isxdigit (hdr[14]) && isxdigit (c = hdr[15]) &&
   1.224 +	isxdigit (hdr[16]) && isxdigit (hdr[17]) && isxdigit (hdr[18]) &&
   1.225 +	isxdigit (hdr[19]) && isxdigit (hdr[20]) && isxdigit (hdr[21]) &&
   1.226 +	isxdigit (hdr[22]) && (hdr[23] == '\015') && (hdr[24] == '\012')) {
   1.227 +      ret = fd;			/* mbx format */
   1.228 +
   1.229 +      if (stream) {		/* lock if making a mini-stream */
   1.230 +	if (flock (fd,LOCK_SH) ||
   1.231 +	    (flags && ((*ld = lockname (lock,file,LOCK_EX)) < 0))) ret = -1;
   1.232 +				/* reread data now that locked */
   1.233 +	else if (lseek (fd,0,L_SET) ||
   1.234 +		 (read (fd,hdr+1,HDRSIZE-1) != (HDRSIZE-1))) ret = -1;
   1.235 +	else {
   1.236 +	  *stream = (MAILSTREAM *) memset (fs_get (sizeof (MAILSTREAM)),0,
   1.237 +					   sizeof (MAILSTREAM));
   1.238 +	  hdr[15] = '\0';	/* tie off UIDVALIDITY */
   1.239 +	  (*stream)->uid_validity = strtoul (hdr+7,NIL,16);
   1.240 +	  hdr[15] = c;		/* now get UIDLAST */
   1.241 +	  (*stream)->uid_last = strtoul (hdr+15,NIL,16);
   1.242 +				/* parse user flags */
   1.243 +	  for (i = 0, s = hdr + 25;
   1.244 +	       (i < NUSERFLAGS) && (t = strchr (s,'\015')) && (t - s);
   1.245 +	       i++, s = t + 2) {
   1.246 +	    *t = '\0';		/* tie off flag */
   1.247 +	    if (strlen (s) <= MAXUSERFLAG)
   1.248 +	      (*stream)->user_flags[i] = cpystr (s);
   1.249 +	  }
   1.250 +				/* make sure have true UIDLAST */
   1.251 +	  if (flags & MBXISVALIDUID) {
   1.252 +	    for (upd = NIL,pos = 2048, k = 0; pos < sbuf.st_size;
   1.253 +		 pos += (j + k)) {
   1.254 +				/* read header for this message */
   1.255 +	      lseek (fd,pos,L_SET);
   1.256 +	      if ((j = read (fd,hdr,64)) >= 0) {
   1.257 +		hdr[j] = '\0';
   1.258 +		if ((s = strchr (hdr,'\015')) && (s[1] == '\012')) {
   1.259 +		  *s = '\0';
   1.260 +		  k = s + 2 - hdr;
   1.261 +		  if ((s = strchr (hdr,',')) && (j = strtol (s+1,&s,10)) &&
   1.262 +		      (*s == ';') && (s = strchr (s+1,'-'))) {
   1.263 +				/* get UID if there is any */
   1.264 +		    i = strtoul (++s,&t,16);
   1.265 +		    if (!*t && (t == (s + 8)) && (i <= (*stream)->uid_last)) {
   1.266 +		      if (!i) {
   1.267 +			lseek (fd,pos + s - hdr,L_SET);
   1.268 +			sprintf (hdr,"%08lx",++(*stream)->uid_last);
   1.269 +			write (fd,hdr,8);
   1.270 +			upd = T;
   1.271 +		      }
   1.272 +		      continue;
   1.273 +		    }
   1.274 +		  }
   1.275 +		}
   1.276 +		ret = -1;	/* error, give up */
   1.277 +		*stream = mail_close (*stream);
   1.278 +		pos = sbuf.st_size + 1;
   1.279 +		j = k = 0;
   1.280 +	      }
   1.281 +	    }
   1.282 +
   1.283 +	    if (upd) {	    /* need to update hdr with new UIDLAST? */
   1.284 +	      lseek (fd,15,L_SET);
   1.285 +	      sprintf (hdr,"%08lx",(*stream)->uid_last);
   1.286 +	      write (fd,hdr,8);
   1.287 +	    }
   1.288 +	  }
   1.289 +	}
   1.290 +      }
   1.291 +    }
   1.292 +    if (ret != fd) close (fd);	/* close the file */
   1.293 +    else lseek (fd,0,L_SET);	/* else rewind to start */
   1.294 +				/* \Marked status? */
   1.295 +    if (sbuf.st_ctime > sbuf.st_atime) {
   1.296 +				/* preserve atime and mtime */
   1.297 +      times.actime = sbuf.st_atime;
   1.298 +      times.modtime = sbuf.st_mtime;
   1.299 +      utime (file,&times);	/* set the times */
   1.300 +    }
   1.301 +  }
   1.302 +				/* in case INBOX but not mbx format */
   1.303 +  else if (((error = errno) == ENOENT) && !compare_cstring (name,"INBOX"))
   1.304 +    error = -1;
   1.305 +  if ((ret < 0) && ld && (*ld >= 0)) {
   1.306 +    unlockfd (*ld,lock);
   1.307 +    *ld = -1;
   1.308 +  }
   1.309 +  errno = error;		/* return as last error */
   1.310 +  return ret;			/* return what we should */
   1.311 +}
   1.312 +
   1.313 +/* MBX manipulate driver parameters
   1.314 + * Accepts: function code
   1.315 + *	    function-dependent value
   1.316 + * Returns: function-dependent return value
   1.317 + */
   1.318 +
   1.319 +void *mbx_parameters (long function,void *value)
   1.320 +{
   1.321 +  void *ret = NIL;
   1.322 +  switch ((int) function) {
   1.323 +  case SET_ONETIMEEXPUNGEATPING:
   1.324 +    if (value) ((MBXLOCAL *) ((MAILSTREAM *) value)->local)->expok = T;
   1.325 +  case GET_ONETIMEEXPUNGEATPING:
   1.326 +    if (value) ret = (void *)
   1.327 +      (((MBXLOCAL *) ((MAILSTREAM *) value)->local)->expok ? VOIDT : NIL);
   1.328 +    break;
   1.329 +  }
   1.330 +  return ret;
   1.331 +}
   1.332 +
   1.333 +
   1.334 +/* MBX mail scan mailboxes
   1.335 + * Accepts: mail stream
   1.336 + *	    reference
   1.337 + *	    pattern to search
   1.338 + *	    string to scan
   1.339 + */
   1.340 +
   1.341 +void mbx_scan (MAILSTREAM *stream,char *ref,char *pat,char *contents)
   1.342 +{
   1.343 +  if (stream) dummy_scan (NIL,ref,pat,contents);
   1.344 +}
   1.345 +
   1.346 +
   1.347 +/* MBX mail list mailboxes
   1.348 + * Accepts: mail stream
   1.349 + *	    reference
   1.350 + *	    pattern to search
   1.351 + */
   1.352 +
   1.353 +void mbx_list (MAILSTREAM *stream,char *ref,char *pat)
   1.354 +{
   1.355 +  if (stream) dummy_list (NIL,ref,pat);
   1.356 +}
   1.357 +
   1.358 +
   1.359 +/* MBX mail list subscribed mailboxes
   1.360 + * Accepts: mail stream
   1.361 + *	    reference
   1.362 + *	    pattern to search
   1.363 + */
   1.364 +
   1.365 +void mbx_lsub (MAILSTREAM *stream,char *ref,char *pat)
   1.366 +{
   1.367 +  if (stream) dummy_lsub (NIL,ref,pat);
   1.368 +}
   1.369 +
   1.370 +/* MBX mail create mailbox
   1.371 + * Accepts: MAIL stream
   1.372 + *	    mailbox name to create
   1.373 + * Returns: T on success, NIL on failure
   1.374 + */
   1.375 +
   1.376 +long mbx_create (MAILSTREAM *stream,char *mailbox)
   1.377 +{
   1.378 +  char *s,mbx[MAILTMPLEN],tmp[HDRSIZE];
   1.379 +  long ret = NIL;
   1.380 +  int i,fd;
   1.381 +  if (!(s = dummy_file (mbx,mailbox))) {
   1.382 +    sprintf (mbx,"Can't create %.80s: invalid name",mailbox);
   1.383 +    mm_log (mbx,ERROR);
   1.384 +  }
   1.385 +				/* create underlying file */
   1.386 +  else if (dummy_create (stream,s)) {
   1.387 +				/* done if made directory */
   1.388 +    if ((s = strrchr (s,'\\')) && !s[1]) return T;
   1.389 +    if ((fd = open (mbx,O_WRONLY|O_BINARY,NIL)) < 0) {
   1.390 +      sprintf (tmp,"Can't reopen mailbox node %.80s: %s",mbx,strerror (errno));
   1.391 +      mm_log (tmp,ERROR);
   1.392 +      unlink (mbx);		/* delete the file */
   1.393 +    }
   1.394 +    else {
   1.395 +      memset (tmp,'\0',HDRSIZE);/* initialize header */
   1.396 +      sprintf (s = tmp,"*mbx*\015\012%08lx00000000\015\012",
   1.397 +	       (unsigned long) time (0));
   1.398 +      for (i = 0; i < NUSERFLAGS; ++i)
   1.399 +	sprintf (s += strlen (s),"%s\015\012",
   1.400 +		 (stream && stream->user_flags[i]) ? stream->user_flags[i] :
   1.401 +		 "");
   1.402 +      if (write (fd,tmp,HDRSIZE) != HDRSIZE) {
   1.403 +	sprintf (tmp,"Can't initialize mailbox node %.80s: %s",
   1.404 +		 mbx,strerror (errno));
   1.405 +	mm_log (tmp,ERROR);
   1.406 +	unlink (mbx);		/* delete the file */
   1.407 +      }
   1.408 +      else ret = T;		/* success */
   1.409 +      close (fd);		/* close file */
   1.410 +    }
   1.411 +  }
   1.412 +  return ret;
   1.413 +}
   1.414 +
   1.415 +
   1.416 +/* MBX mail delete mailbox
   1.417 + * Accepts: MAIL stream
   1.418 + *	    mailbox name to delete
   1.419 + * Returns: T on success, NIL on failure
   1.420 + */
   1.421 +
   1.422 +long mbx_delete (MAILSTREAM *stream,char *mailbox)
   1.423 +{
   1.424 +  return mbx_rename (stream,mailbox,NIL);
   1.425 +}
   1.426 +
   1.427 +/* MBX mail rename mailbox
   1.428 + * Accepts: MAIL stream
   1.429 + *	    old mailbox name
   1.430 + *	    new mailbox name (or NIL for delete)
   1.431 + * Returns: T on success, NIL on failure
   1.432 + */
   1.433 +
   1.434 +long mbx_rename (MAILSTREAM *stream,char *old,char *newname)
   1.435 +{
   1.436 +  long ret = LONGT;
   1.437 +  char c,*s,tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN];
   1.438 +  int fd,ld;
   1.439 +  struct stat sbuf;
   1.440 +  if (!dummy_file (file,old) ||
   1.441 +      (newname && (!((s = mailboxfile (tmp,newname)) && *s) ||
   1.442 +		   ((s = strrchr (tmp,'\\')) && !s[1])))) {
   1.443 +    sprintf (tmp,newname ?
   1.444 +	     "Can't rename mailbox %.80s to %.80s: invalid name" :
   1.445 +	     "Can't delete mailbox %.80s: invalid name",
   1.446 +	     old,newname);
   1.447 +    mm_log (tmp,ERROR);
   1.448 +    return NIL;
   1.449 +  }
   1.450 +  else if ((fd = open (file,O_RDWR|O_BINARY,NIL)) < 0) {
   1.451 +    sprintf (tmp,"Can't open mailbox %.80s: %s",old,strerror (errno));
   1.452 +    mm_log (tmp,ERROR);
   1.453 +    return NIL;
   1.454 +  }
   1.455 +				/* get parse/append permission */
   1.456 +  if ((ld = lockname (lock,file,LOCK_EX)) < 0) {
   1.457 +    mm_log ("Unable to lock rename mailbox",ERROR);
   1.458 +    return NIL;
   1.459 +  }
   1.460 +				/* lock out other users */
   1.461 +  if (flock (fd,LOCK_EX|LOCK_NB)) {
   1.462 +    close (fd);			/* couldn't lock, give up on it then */
   1.463 +    sprintf (tmp,"Mailbox %.80s is in use by another process",old);
   1.464 +    mm_log (tmp,ERROR);
   1.465 +    unlockfd (ld,lock);		/* release exclusive parse/append permission */
   1.466 +    return NIL;
   1.467 +  }
   1.468 +
   1.469 +  if (newname) {		/* want rename? */
   1.470 +				/* found superior to destination name? */
   1.471 +    if ((s = strrchr (tmp,'\\')) && (s != tmp) &&
   1.472 +	((tmp[1] != ':') || (s != tmp + 2))) {
   1.473 +      c = s[1];			/* remember character after delimiter */
   1.474 +      *s = s[1] = '\0';		/* tie off name at delimiter */
   1.475 +				/* name doesn't exist, create it */
   1.476 +      if (stat (tmp,&sbuf) || ((sbuf.st_mode & S_IFMT) != S_IFDIR)) {
   1.477 +	*s = '\\';		/* restore delimiter */
   1.478 +	if (!dummy_create (stream,tmp)) ret = NIL;
   1.479 +      }
   1.480 +      else *s = '\\';		/* restore delimiter */
   1.481 +      s[1] = c;			/* restore character after delimiter */
   1.482 +    }
   1.483 +    flock (fd,LOCK_UN);		/* release lock on the file */
   1.484 +    close (fd);			/* pacify NTFS */
   1.485 +				/* rename the file */
   1.486 +    if (ret && rename (file,tmp)) {
   1.487 +      sprintf (tmp,"Can't rename mailbox %.80s to %.80s: %s",old,newname,
   1.488 +	       strerror (errno));
   1.489 +      mm_log (tmp,ERROR);
   1.490 +      ret = NIL;		/* set failure */
   1.491 +    }
   1.492 +  }
   1.493 +  else {
   1.494 +    flock (fd,LOCK_UN);		/* release lock on the file */
   1.495 +    close (fd);			/* pacify NTFS */
   1.496 +    if (unlink (file)) {
   1.497 +      sprintf (tmp,"Can't delete mailbox %.80s: %s",old,strerror (errno));
   1.498 +      mm_log (tmp,ERROR);
   1.499 +      ret = NIL;		/* set failure */
   1.500 +    }
   1.501 +  }
   1.502 +  unlockfd (ld,lock);		/* release exclusive parse/append permission */
   1.503 +				/* recreate file if renamed INBOX */
   1.504 +  if (ret && !compare_cstring (old,"INBOX")) mbx_create (NIL,"INBOX");
   1.505 +  return ret;			/* return success */
   1.506 +}
   1.507 +
   1.508 +/* MBX mail open
   1.509 + * Accepts: stream to open
   1.510 + * Returns: stream on success, NIL on failure
   1.511 + */
   1.512 +
   1.513 +MAILSTREAM *mbx_open (MAILSTREAM *stream)
   1.514 +{
   1.515 +  int fd,ld;
   1.516 +  short silent;
   1.517 +  char tmp[MAILTMPLEN];
   1.518 +  if (!stream) return &mbxproto;/* return prototype for OP_PROTOTYPE call */
   1.519 +  if (stream->local) fatal ("mbx recycle stream");
   1.520 +				/* canonicalize the mailbox name */
   1.521 +  if (!dummy_file (tmp,stream->mailbox)) {
   1.522 +    sprintf (tmp,"Can't open - invalid name: %.80s",stream->mailbox);
   1.523 +    mm_log (tmp,ERROR);
   1.524 +  }
   1.525 +  if (stream->rdonly ||
   1.526 +      (fd = open (tmp,O_RDWR|O_BINARY,NIL)) < 0) {
   1.527 +    if ((fd = open (tmp,O_RDONLY|O_BINARY,NIL)) < 0) {
   1.528 +      sprintf (tmp,"Can't open mailbox: %s",strerror (errno));
   1.529 +      mm_log (tmp,ERROR);
   1.530 +      return NIL;
   1.531 +    }
   1.532 +    else if (!stream->rdonly) {	/* got it, but readonly */
   1.533 +      mm_log ("Can't get write access to mailbox, access is readonly",WARN);
   1.534 +      stream->rdonly = T;
   1.535 +    }
   1.536 +  }
   1.537 +
   1.538 +  stream->local = memset (fs_get (sizeof (MBXLOCAL)),NIL,sizeof (MBXLOCAL));
   1.539 +  LOCAL->fd = fd;		/* bind the file */
   1.540 +  LOCAL->ld = -1;		/* no flaglock */
   1.541 +  LOCAL->buf = (char *) fs_get (CHUNKSIZE);
   1.542 +  LOCAL->buflen = CHUNKSIZE - 1;
   1.543 +				/* note if an INBOX or not */
   1.544 +  stream->inbox = !compare_cstring (stream->mailbox,"INBOX");
   1.545 +  fs_give ((void **) &stream->mailbox);
   1.546 +  stream->mailbox = cpystr (tmp);
   1.547 +				/* get parse/append permission */
   1.548 +  if ((ld = lockname (tmp,stream->mailbox,LOCK_EX)) < 0) {
   1.549 +    mm_log ("Unable to lock open mailbox",ERROR);
   1.550 +    return NIL;
   1.551 +  }
   1.552 +  flock (LOCAL->fd,LOCK_SH);	/* lock the file */
   1.553 +  unlockfd (ld,tmp);		/* release shared parse permission */
   1.554 +  LOCAL->filesize = HDRSIZE;	/* initialize parsed file size */
   1.555 +  LOCAL->filetime = 0;		/* time not set up yet */
   1.556 +  LOCAL->expok = LOCAL->flagcheck = NIL;
   1.557 +  stream->sequence++;		/* bump sequence number */
   1.558 +				/* parse mailbox */
   1.559 +  stream->nmsgs = stream->recent = 0;
   1.560 +  silent = stream->silent;	/* defer events */
   1.561 +  stream->silent = T;
   1.562 +  if (mbx_ping (stream) && !stream->nmsgs)
   1.563 +    mm_log ("Mailbox is empty",(long) NIL);
   1.564 +  stream->silent = silent;	/* now notify upper level */
   1.565 +  mail_exists (stream,stream->nmsgs);
   1.566 +  mail_recent (stream,stream->recent);
   1.567 +  if (!LOCAL) return NIL;	/* failure if stream died */
   1.568 +  stream->perm_seen = stream->perm_deleted = stream->perm_flagged =
   1.569 +    stream->perm_answered = stream->perm_draft = stream->rdonly ? NIL : T;
   1.570 +  stream->perm_user_flags = stream->rdonly ? NIL : 0xffffffff;
   1.571 +  stream->kwd_create = (stream->user_flags[NUSERFLAGS-1] || stream->rdonly) ?
   1.572 +    NIL : T;			/* can we create new user flags? */
   1.573 +  return stream;		/* return stream to caller */
   1.574 +}
   1.575 +
   1.576 +/* MBX mail close
   1.577 + * Accepts: MAIL stream
   1.578 + *	    close options
   1.579 + */
   1.580 +
   1.581 +void mbx_close (MAILSTREAM *stream,long options)
   1.582 +{
   1.583 +  if (stream && LOCAL) {	/* only if a file is open */
   1.584 +    int silent = stream->silent;
   1.585 +    stream->silent = T;		/* note this stream is dying */
   1.586 +				/* do an expunge if requested */
   1.587 +    if (options & CL_EXPUNGE) mbx_expunge (stream,NIL,NIL);
   1.588 +    else {			/* otherwise do a checkpoint to purge */
   1.589 +      LOCAL->expok = T;		/*  possible expunged messages */
   1.590 +      mbx_ping (stream);
   1.591 +    }
   1.592 +    stream->silent = silent;	/* restore previous status */
   1.593 +    mbx_abort (stream);
   1.594 +  }
   1.595 +}
   1.596 +
   1.597 +
   1.598 +/* MBX mail abort stream
   1.599 + * Accepts: MAIL stream
   1.600 + */
   1.601 +
   1.602 +void mbx_abort (MAILSTREAM *stream)
   1.603 +{
   1.604 +  if (stream && LOCAL) {	/* only if a file is open */
   1.605 +    flock (LOCAL->fd,LOCK_UN);	/* unlock local file */
   1.606 +    close (LOCAL->fd);		/* close the local file */
   1.607 +				/* free local text buffer */
   1.608 +    if (LOCAL->buf) fs_give ((void **) &LOCAL->buf);
   1.609 +				/* nuke the local data */
   1.610 +    fs_give ((void **) &stream->local);
   1.611 +    stream->dtb = NIL;		/* log out the DTB */
   1.612 +  }
   1.613 +}
   1.614 +
   1.615 +
   1.616 +/* MBX mail fetch flags
   1.617 + * Accepts: MAIL stream
   1.618 + *	    sequence
   1.619 + *	    option flags
   1.620 + * Sniffs at file to see if some other process changed the flags
   1.621 + */
   1.622 +
   1.623 +void mbx_flags (MAILSTREAM *stream,char *sequence,long flags)
   1.624 +{
   1.625 +  MESSAGECACHE *elt;
   1.626 +  unsigned long i;
   1.627 +  if (mbx_ping (stream) &&	/* ping mailbox, get new status for messages */
   1.628 +      ((flags & FT_UID) ? mail_uid_sequence (stream,sequence) :
   1.629 +       mail_sequence (stream,sequence)))
   1.630 +    for (i = 1; i <= stream->nmsgs; i++) 
   1.631 +      if ((elt = mail_elt (stream,i))->sequence && !elt->valid)
   1.632 +	mbx_elt (stream,i,NIL);
   1.633 +}
   1.634 +
   1.635 +/* MBX mail fetch message header
   1.636 + * Accepts: MAIL stream
   1.637 + *	    message # to fetch
   1.638 + *	    pointer to returned header text length
   1.639 + *	    option flags
   1.640 + * Returns: message header in RFC822 format
   1.641 + */
   1.642 +
   1.643 +char *mbx_header (MAILSTREAM *stream,unsigned long msgno,unsigned long *length,
   1.644 +		  long flags)
   1.645 +{
   1.646 +  unsigned long i;
   1.647 +  char *s;
   1.648 +  *length = 0;			/* default to empty */
   1.649 +  if (flags & FT_UID) return "";/* UID call "impossible" */
   1.650 +				/* get header position, possibly header */
   1.651 +  i = mbx_hdrpos (stream,msgno,length,&s);
   1.652 +  if (!s) {			/* mbx_hdrpos() returned header? */
   1.653 +    lseek (LOCAL->fd,i,L_SET);	/* no, get to header position */
   1.654 +				/* is buffer big enough? */
   1.655 +    if (*length > LOCAL->buflen) {
   1.656 +      fs_give ((void **) &LOCAL->buf);
   1.657 +      LOCAL->buf = (char *) fs_get ((LOCAL->buflen = *length) + 1);
   1.658 +    }
   1.659 +				/* slurp the data */
   1.660 +    read (LOCAL->fd,s = LOCAL->buf,*length);
   1.661 +  }
   1.662 +  s[*length] = '\0';		/* tie off string */
   1.663 +  return s;
   1.664 +}
   1.665 +
   1.666 +/* MBX mail fetch message text (body only)
   1.667 + * Accepts: MAIL stream
   1.668 + *	    message # to fetch
   1.669 + *	    pointer to returned header text length
   1.670 + *	    option flags
   1.671 + * Returns: T on success, NIL on failure
   1.672 + */
   1.673 +
   1.674 +long mbx_text (MAILSTREAM *stream,unsigned long msgno,STRING *bs,long flags)
   1.675 +{
   1.676 +  FDDATA d;
   1.677 +  unsigned long i,j;
   1.678 +  MESSAGECACHE *elt;
   1.679 +				/* UID call "impossible" */
   1.680 +  if (flags & FT_UID) return NIL;
   1.681 +				/* get message status */
   1.682 +  elt = mbx_elt (stream,msgno,NIL);
   1.683 +				/* if message not seen */
   1.684 +  if (!(flags & FT_PEEK) && !elt->seen && mbx_flaglock (stream)) {
   1.685 +    elt->seen = T;		/* mark message as seen */
   1.686 +				/* recalculate status */
   1.687 +    mbx_update_status (stream,msgno,NIL);
   1.688 +    mm_flags (stream,msgno);
   1.689 +				/* update flags */
   1.690 +    mbx_flag (stream,NIL,NIL,NIL);
   1.691 +  }
   1.692 +  if (!LOCAL) return NIL;	/* mbx_flaglock() could have aborted */
   1.693 +				/* find header position */
   1.694 +  i = mbx_hdrpos (stream,msgno,&j,NIL);
   1.695 +  d.fd = LOCAL->fd;		/* set up file descriptor */
   1.696 +  d.pos = i + j;
   1.697 +  d.chunk = LOCAL->buf;	/* initial buffer chunk */
   1.698 +  d.chunksize = CHUNKSIZE;
   1.699 +  INIT (bs,fd_string,&d,elt->rfc822_size - j);
   1.700 +  return LONGT;			/* success */
   1.701 +}
   1.702 +
   1.703 +/* MBX mail modify flags
   1.704 + * Accepts: MAIL stream
   1.705 + *	    sequence
   1.706 + *	    flag(s)
   1.707 + *	    option flags
   1.708 + * Unlocks flag lock
   1.709 + */
   1.710 +
   1.711 +void mbx_flag (MAILSTREAM *stream,char *sequence,char *flag,long flags)
   1.712 +{
   1.713 +  struct utimbuf times;
   1.714 +  struct stat sbuf;
   1.715 +				/* make sure the update takes */
   1.716 +  if (!stream->rdonly && LOCAL && (LOCAL->fd >= 0) && (LOCAL->ld >= 0)) {
   1.717 +    fsync (LOCAL->fd);
   1.718 +    fstat (LOCAL->fd,&sbuf);	/* get current write time */
   1.719 +    times.modtime = LOCAL->filetime = sbuf.st_mtime;
   1.720 +				/* update header */
   1.721 +    if ((LOCAL->ffuserflag < NUSERFLAGS) &&
   1.722 +	stream->user_flags[LOCAL->ffuserflag]) mbx_update_header (stream);
   1.723 +    times.actime = time (0);	/* make sure read comes after all that */
   1.724 +    utime (stream->mailbox,&times);
   1.725 +  }
   1.726 +  if (LOCAL->ld >= 0) {		/* unlock now */
   1.727 +    unlockfd (LOCAL->ld,LOCAL->lock);
   1.728 +    LOCAL->ld = -1;
   1.729 +  }
   1.730 +}
   1.731 +
   1.732 +
   1.733 +/* MBX mail per-message modify flags
   1.734 + * Accepts: MAIL stream
   1.735 + *	    message cache element
   1.736 + */
   1.737 +
   1.738 +void mbx_flagmsg (MAILSTREAM *stream,MESSAGECACHE *elt)
   1.739 +{
   1.740 +  if (mbx_flaglock (stream)) mbx_update_status (stream,elt->msgno,NIL);
   1.741 +}
   1.742 +
   1.743 +/* MBX mail ping mailbox
   1.744 + * Accepts: MAIL stream
   1.745 + * Returns: T if stream still alive, NIL if not
   1.746 + */
   1.747 +
   1.748 +long mbx_ping (MAILSTREAM *stream)
   1.749 +{
   1.750 +  unsigned long i,pos;
   1.751 +  long ret = NIL;
   1.752 +  int ld;
   1.753 +  char lock[MAILTMPLEN];
   1.754 +  MESSAGECACHE *elt;
   1.755 +  struct stat sbuf;
   1.756 +  if (stream && LOCAL) {	/* only if stream already open */
   1.757 +    ret = LONGT;		/* assume OK */
   1.758 +    fstat (LOCAL->fd,&sbuf);	/* get current file poop */
   1.759 +				/* allow expunge if permitted at ping */
   1.760 +    if (mail_parameters (NIL,GET_EXPUNGEATPING,NIL)) LOCAL->expok = T;
   1.761 +				/* if external modification */
   1.762 +    if (LOCAL->filetime && (LOCAL->filetime < sbuf.st_mtime))
   1.763 +      LOCAL->flagcheck = T;	/* upgrade to flag checking */
   1.764 +				/* new mail or flagcheck handling needed? */
   1.765 +    if (((sbuf.st_size - LOCAL->filesize) || LOCAL->flagcheck ||
   1.766 +	 !stream->nmsgs) &&
   1.767 +	((ld = lockname (lock,stream->mailbox,LOCK_EX)) >= 0)) {
   1.768 +      if (!LOCAL->flagcheck) ret = mbx_parse (stream);
   1.769 +				/* sweep mailbox for changed message status */
   1.770 +      else if (ret = mbx_parse (stream)) {
   1.771 +	unsigned long recent = 0;
   1.772 +	LOCAL->filetime = sbuf.st_mtime;
   1.773 +	for (i = 1; i <= stream->nmsgs; )
   1.774 +	  if (elt = mbx_elt (stream,i,LOCAL->expok)) {
   1.775 +	    if (elt->recent) ++recent;
   1.776 +	    ++i;
   1.777 +	  }
   1.778 +	mail_recent (stream,recent);
   1.779 +	LOCAL->flagcheck = NIL;	/* got all the updates */
   1.780 +      }
   1.781 +      unlockfd (ld,lock);	/* release shared parse/append permission */
   1.782 +    }
   1.783 +    if (ret) {			/* must still be alive */
   1.784 +      if (!LOCAL->expunged)	/* look for holes if none known yet */
   1.785 +	for (i = 1, pos = HDRSIZE;
   1.786 +	     !LOCAL->expunged && (i <= stream->nmsgs);
   1.787 +	     i++, pos += elt->private.special.text.size + elt->rfc822_size)
   1.788 +	  if ((elt = mail_elt (stream,i))->private.special.offset != pos)
   1.789 +	    LOCAL->expunged = T;/* found a hole */
   1.790 +				/* burp any holes */
   1.791 +      if (LOCAL->expunged && !stream->rdonly) {
   1.792 +	if (mbx_rewrite (stream,&i,NIL)) fatal ("expunge on check");
   1.793 +	if (i) {		/* any space reclaimed? */
   1.794 +	  LOCAL->expunged = NIL;/* no more pending expunge */
   1.795 +	  sprintf (LOCAL->buf,"Reclaimed %lu bytes of expunged space",i);
   1.796 +	  mm_log (LOCAL->buf,(long) NIL);
   1.797 +	}
   1.798 +      }
   1.799 +      LOCAL->expok = NIL;	/* no more expok */
   1.800 +    }
   1.801 +  }
   1.802 +  return ret;			/* return result of the parse */
   1.803 +}
   1.804 +
   1.805 +/* MBX mail check mailbox (reparses status too)
   1.806 + * Accepts: MAIL stream
   1.807 + */
   1.808 +
   1.809 +void mbx_check (MAILSTREAM *stream)
   1.810 +{
   1.811 +  if (LOCAL) LOCAL->expok = T;	/* mark that a check is desired */
   1.812 +  if (mbx_ping (stream)) mm_log ("Check completed",(long) NIL);
   1.813 +}
   1.814 +
   1.815 +
   1.816 +/* MBX mail expunge mailbox
   1.817 + * Accepts: MAIL stream
   1.818 + *	    sequence to expunge if non-NIL
   1.819 + *	    expunge options
   1.820 + * Returns: T if success, NIL if failure
   1.821 + */
   1.822 +
   1.823 +long mbx_expunge (MAILSTREAM *stream,char *sequence,long options)
   1.824 +{
   1.825 +  long ret;
   1.826 +  unsigned long nexp,reclaimed;
   1.827 +  if (ret = sequence ? ((options & EX_UID) ?
   1.828 +			mail_uid_sequence (stream,sequence) :
   1.829 +			mail_sequence (stream,sequence)) : LONGT) {
   1.830 +    if (!mbx_ping (stream));	/* do nothing if stream dead */
   1.831 +    else if (stream->rdonly)	/* won't do on readonly files! */
   1.832 +      mm_log ("Expunge ignored on readonly mailbox",WARN);
   1.833 +				/* if expunged any messages */
   1.834 +    else if (nexp = mbx_rewrite (stream,&reclaimed,sequence ? -1 : 1)) {
   1.835 +      sprintf (LOCAL->buf,"Expunged %lu messages",nexp);
   1.836 +      mm_log (LOCAL->buf,(long) NIL);
   1.837 +    }
   1.838 +    else if (reclaimed) {	 /* or if any prior expunged space reclaimed */
   1.839 +      sprintf (LOCAL->buf,"Reclaimed %lu bytes of expunged space",reclaimed);
   1.840 +      mm_log (LOCAL->buf,(long) NIL);
   1.841 +    }
   1.842 +    else mm_log ("No messages deleted, so no update needed",(long) NIL);
   1.843 +  }
   1.844 +  return ret;
   1.845 +}
   1.846 +
   1.847 +/* MBX mail copy message(s)
   1.848 + * Accepts: MAIL stream
   1.849 + *	    sequence
   1.850 + *	    destination mailbox
   1.851 + *	    copy options
   1.852 + * Returns: T if success, NIL if failed
   1.853 + */
   1.854 +
   1.855 +long mbx_copy (MAILSTREAM *stream,char *sequence,char *mailbox,long options)
   1.856 +{
   1.857 +  struct stat sbuf;
   1.858 +  struct utimbuf times;
   1.859 +  MESSAGECACHE *elt;
   1.860 +  unsigned long i,j,k,m;
   1.861 +  long ret = LONGT;
   1.862 +  int fd,ld;
   1.863 +  char *s,*t,file[MAILTMPLEN],lock[MAILTMPLEN];
   1.864 +  mailproxycopy_t pc =
   1.865 +    (mailproxycopy_t) mail_parameters (stream,GET_MAILPROXYCOPY,NIL);
   1.866 +  copyuid_t cu = (copyuid_t) mail_parameters (NIL,GET_COPYUID,NIL);
   1.867 +  SEARCHSET *source = cu ? mail_newsearchset () : NIL;
   1.868 +  SEARCHSET *dest = cu ? mail_newsearchset () : NIL;
   1.869 +  MAILSTREAM *dstream = NIL;
   1.870 +  if (!((options & CP_UID) ? mail_uid_sequence (stream,sequence) :
   1.871 +	mail_sequence (stream,sequence))) return NIL;
   1.872 +				/* make sure valid mailbox */
   1.873 +  if ((fd = mbx_isvalid (&dstream,mailbox,file,&ld,lock,
   1.874 +			 cu ? MBXISVALIDUID : MBXISVALIDNOUID)) < 0)
   1.875 +    switch (errno) {
   1.876 +    case ENOENT:		/* no such file? */
   1.877 +      mm_notify (stream,"[TRYCREATE] Must create mailbox before copy",NIL);
   1.878 +      return NIL;
   1.879 +    case EACCES:		/* file protected */
   1.880 +      sprintf (LOCAL->buf,"Can't access destination: %.80s",mailbox);
   1.881 +      MM_LOG (LOCAL->buf,ERROR);
   1.882 +      return NIL;
   1.883 +    case EINVAL:
   1.884 +      if (pc) return (*pc) (stream,sequence,mailbox,options);
   1.885 +      sprintf (LOCAL->buf,"Invalid MBX-format mailbox name: %.80s",mailbox);
   1.886 +      mm_log (LOCAL->buf,ERROR);
   1.887 +      return NIL;
   1.888 +    default:
   1.889 +      if (pc) return (*pc) (stream,sequence,mailbox,options);
   1.890 +      sprintf (LOCAL->buf,"Not a MBX-format mailbox: %.80s",mailbox);
   1.891 +      mm_log (LOCAL->buf,ERROR);
   1.892 +      return NIL;
   1.893 +    }
   1.894 +				/* got file? */  
   1.895 +  if ((fd = open (dummy_file (file,mailbox),O_RDWR|O_CREAT|O_BINARY,
   1.896 +		  S_IREAD|S_IWRITE)) < 0) {
   1.897 +    sprintf (LOCAL->buf,"Unable to open copy mailbox: %s",strerror (errno));
   1.898 +    mm_log (LOCAL->buf,ERROR);
   1.899 +    return NIL;
   1.900 +  }
   1.901 +  mm_critical (stream);		/* go critical */
   1.902 +  fstat (fd,&sbuf);		/* get current file size */
   1.903 +  lseek (fd,sbuf.st_size,L_SET);/* move to end of file */
   1.904 +
   1.905 +				/* for each requested message */
   1.906 +  for (i = 1; ret && (i <= stream->nmsgs); i++) 
   1.907 +    if ((elt = mail_elt (stream,i))->sequence) {
   1.908 +      lseek (LOCAL->fd,elt->private.special.offset +
   1.909 +	     elt->private.special.text.size,L_SET);
   1.910 +      mail_date(LOCAL->buf,elt);/* build target header */
   1.911 +				/* get target keyword mask */
   1.912 +      for (j = elt->user_flags, k = 0; j; )
   1.913 +	if (s = stream->user_flags[find_rightmost_bit (&j)])
   1.914 +	  for (m = 0; (m < NUSERFLAGS) && (t = dstream->user_flags[m]); m++)
   1.915 +	    if (!compare_cstring (s,t) && (k |= 1 << m)) break;
   1.916 +      sprintf (LOCAL->buf+strlen(LOCAL->buf),",%lu;%08lx%04x-%08lx\015\012",
   1.917 +	       elt->rfc822_size,k,(unsigned)
   1.918 +	       ((fSEEN * elt->seen) + (fDELETED * elt->deleted) +
   1.919 +		(fFLAGGED * elt->flagged) + (fANSWERED * elt->answered) +
   1.920 +		(fDRAFT * elt->draft)),cu ? ++dstream->uid_last : 0);
   1.921 +				/* write target header */
   1.922 +      if (ret = (write (fd,LOCAL->buf,strlen (LOCAL->buf)) > 0)) {
   1.923 +	for (k = elt->rfc822_size; ret && (j = min (k,LOCAL->buflen)); k -= j){
   1.924 +	  read (LOCAL->fd,LOCAL->buf,j);
   1.925 +	  ret = write (fd,LOCAL->buf,j) >= 0;
   1.926 +	}
   1.927 +	if (cu) {		/* need to pass back new UID? */
   1.928 +	  mail_append_set (source,mail_uid (stream,i));
   1.929 +	  mail_append_set (dest,dstream->uid_last);
   1.930 +	}
   1.931 +      }
   1.932 +    }
   1.933 +
   1.934 +				/* make sure all the updates take */
   1.935 +  if (!(ret && (ret = !fsync (fd)))) {
   1.936 +    sprintf (LOCAL->buf,"Unable to write message: %s",strerror (errno));
   1.937 +    mm_log (LOCAL->buf,ERROR);
   1.938 +    ftruncate (fd,sbuf.st_size);
   1.939 +  }
   1.940 +  if (cu && ret) {		/* return sets if doing COPYUID */
   1.941 +    (*cu) (stream,mailbox,dstream->uid_validity,source,dest);
   1.942 +    lseek (fd,15,L_SET);	/* update UIDLAST */
   1.943 +    sprintf (LOCAL->buf,"%08lx",dstream->uid_last);
   1.944 +    write (fd,LOCAL->buf,8);
   1.945 +  }
   1.946 +  else {			/* flush any sets we may have built */
   1.947 +    mail_free_searchset (&source);
   1.948 +    mail_free_searchset (&dest);
   1.949 +  }
   1.950 +				/* set atime to now-1 if successful copy */
   1.951 +  if (ret) times.actime = time (0) - 1;
   1.952 +				/* else preserved \Marked status */
   1.953 +  else times.actime = (sbuf.st_ctime > sbuf.st_atime) ?
   1.954 +	 sbuf.st_atime : time (0);
   1.955 +  times.modtime = sbuf.st_mtime;/* preserve mtime */
   1.956 +  utime (file,&times);		/* set the times */
   1.957 +  close (fd);			/* close the file */
   1.958 +  mm_nocritical (stream);	/* release critical */
   1.959 +  unlockfd (ld,lock);		/* release exclusive parse/append permission */
   1.960 +				/* delete all requested messages */
   1.961 +  if (ret && (options & CP_MOVE) && mbx_flaglock (stream)) {
   1.962 +    for (i = 1; i <= stream->nmsgs; i++) if (mail_elt (stream,i)->sequence) {
   1.963 +				/* mark message deleted */
   1.964 +      mbx_elt (stream,i,NIL)->deleted = T;
   1.965 +				/* recalculate status */
   1.966 +      mbx_update_status (stream,i,NIL);
   1.967 +    }
   1.968 +				/* update flags */
   1.969 +    mbx_flag (stream,NIL,NIL,NIL);
   1.970 +  }
   1.971 +  if (dstream != stream) mail_close (dstream);
   1.972 +  return ret;
   1.973 +}
   1.974 +
   1.975 +/* MBX mail append message from stringstruct
   1.976 + * Accepts: MAIL stream
   1.977 + *	    destination mailbox
   1.978 + *	    append callback
   1.979 + *	    data for callback
   1.980 + * Returns: T if append successful, else NIL
   1.981 + */
   1.982 +
   1.983 +long mbx_append (MAILSTREAM *stream,char *mailbox,append_t af,void *data)
   1.984 +{
   1.985 +  struct stat sbuf;
   1.986 +  int fd,ld;
   1.987 +  char *flags,*date,tmp[MAILTMPLEN],file[MAILTMPLEN],lock[MAILTMPLEN];
   1.988 +  struct utimbuf times;
   1.989 +  FILE *df;
   1.990 +  MESSAGECACHE elt;
   1.991 +  long f;
   1.992 +  unsigned long i,uf;
   1.993 +  STRING *message;
   1.994 +  long ret = NIL;
   1.995 +  MAILSTREAM *dstream = NIL;
   1.996 +  appenduid_t au = (appenduid_t) mail_parameters (NIL,GET_APPENDUID,NIL);
   1.997 +  SEARCHSET *dst = au ? mail_newsearchset () : NIL;
   1.998 +				/* make sure valid mailbox */
   1.999 +				/* make sure valid mailbox */
  1.1000 +  if ((fd = mbx_isvalid (&dstream,mailbox,file,&ld,lock,
  1.1001 +			 au ? MBXISVALIDUID : MBXISVALIDNOUID)) < 0)
  1.1002 +    switch (errno) {
  1.1003 +    case ENOENT:		/* no such file? */
  1.1004 +      if (compare_cstring (mailbox,"INBOX")) {
  1.1005 +	mm_notify (stream,"[TRYCREATE] Must create mailbox before append",NIL);
  1.1006 +	return NIL;
  1.1007 +      }
  1.1008 +				/* can create INBOX here */
  1.1009 +      mbx_create (dstream = stream ? stream : &mbxproto,"INBOX");
  1.1010 +      if ((fd = mbx_isvalid (&dstream,mailbox,file,&ld,lock,
  1.1011 +			     au ? MBXISVALIDUID : MBXISVALIDNOUID)) < 0)
  1.1012 +	break;
  1.1013 +    case EACCES:		/* file protected */
  1.1014 +      sprintf (tmp,"Can't access destination: %.80s",mailbox);
  1.1015 +      MM_LOG (tmp,ERROR);
  1.1016 +      return NIL;
  1.1017 +    case EINVAL:
  1.1018 +      sprintf (tmp,"Invalid MBX-format mailbox name: %.80s",mailbox);
  1.1019 +      mm_log (tmp,ERROR);
  1.1020 +      return NIL;
  1.1021 +    default:
  1.1022 +      sprintf (tmp,"Not a MBX-format mailbox: %.80s",mailbox);
  1.1023 +      mm_log (tmp,ERROR);
  1.1024 +      return NIL;
  1.1025 +    }
  1.1026 +
  1.1027 +				/* get first message */
  1.1028 +  if (!(*af) (dstream,data,&flags,&date,&message)) close (fd);
  1.1029 +  else if (!(df = fdopen (fd,"r+b"))) {
  1.1030 +    MM_LOG ("Unable to reopen append mailbox",ERROR);
  1.1031 +    close (fd);
  1.1032 +  }
  1.1033 +  else {
  1.1034 +    mm_critical (dstream);	/* go critical */
  1.1035 +    fstat (fd,&sbuf);		/* get current file size */
  1.1036 +    fseek (df,sbuf.st_size,SEEK_SET);
  1.1037 +    errno = 0;
  1.1038 +    for (ret = LONGT; ret && message; ) {
  1.1039 +      if (!SIZE (message)) {	/* guard against zero-length */
  1.1040 +	mm_log ("Append of zero-length message",ERROR);
  1.1041 +	ret = NIL;
  1.1042 +	break;
  1.1043 +      }
  1.1044 +      f = mail_parse_flags (dstream,flags,&uf);
  1.1045 +      if (date) {		/* parse date if given */
  1.1046 +	if (!mail_parse_date (&elt,date)) {
  1.1047 +	  sprintf (tmp,"Bad date in append: %.80s",date);
  1.1048 +	  mm_log (tmp,ERROR);
  1.1049 +	  ret = NIL;		/* mark failure */
  1.1050 +	  break;
  1.1051 +	}
  1.1052 +	mail_date (tmp,&elt);	/* write preseved date */
  1.1053 +      }
  1.1054 +      else internal_date (tmp);	/* get current date in IMAP format */
  1.1055 +				/* write header */
  1.1056 +      if (fprintf (df,"%s,%lu;%08lx%04lx-%08lx\015\012",tmp,i = SIZE (message),
  1.1057 +		   uf,(unsigned long) f,au ? ++dstream->uid_last : 0) < 0)
  1.1058 +	ret = NIL;
  1.1059 +      else {			/* write message */
  1.1060 +	size_t j;
  1.1061 +	if (!message->cursize) SETPOS (message,GETPOS (message));
  1.1062 +	while (i && (j = fwrite (message->curpos,1,message->cursize,df))) {
  1.1063 +	  i -= j;
  1.1064 +	  SETPOS (message,GETPOS (message) + j);
  1.1065 +	}
  1.1066 +				/* get next message */
  1.1067 +	if (i || !(*af) (dstream,data,&flags,&date,&message)) ret = NIL;
  1.1068 +	else if (au) mail_append_set (dst,dstream->uid_last);
  1.1069 +      }
  1.1070 +    }
  1.1071 +
  1.1072 +				/* if error... */
  1.1073 +    if (!ret || (fflush (df) == EOF)) {
  1.1074 +				/* revert file */
  1.1075 +      ftruncate (fd,sbuf.st_size);
  1.1076 +      close (fd);		/* make sure fclose() doesn't corrupt us */
  1.1077 +      if (errno) {
  1.1078 +	sprintf (tmp,"Message append failed: %s",strerror (errno));
  1.1079 +	mm_log (tmp,ERROR);
  1.1080 +      }
  1.1081 +      ret = NIL;
  1.1082 +    }
  1.1083 +    if (au && ret) {		/* return sets if doing APPENDUID */
  1.1084 +      (*au) (mailbox,dstream->uid_validity,dst);
  1.1085 +      fseek (df,15,SEEK_SET);	/* update UIDLAST */
  1.1086 +      fprintf (df,"%08lx",dstream->uid_last);
  1.1087 +    }
  1.1088 +    else mail_free_searchset (&dst);
  1.1089 +    if (ret) times.actime = time (0) - 1;
  1.1090 +				/* else preserve \Marked status */
  1.1091 +    else times.actime = (sbuf.st_ctime > sbuf.st_atime) ?
  1.1092 +	   sbuf.st_atime : time (0);
  1.1093 +				/* preserve mtime */
  1.1094 +    times.modtime = sbuf.st_mtime;
  1.1095 +    utime (file,&times);	/* set the times */
  1.1096 +    fclose (df);		/* close the file */
  1.1097 +    mm_nocritical (dstream);	/* release critical */
  1.1098 +  }
  1.1099 +  unlockfd (ld,lock);		/* release exclusive parse/append permission */
  1.1100 +  if (dstream != stream) mail_close (dstream);
  1.1101 +  return ret;
  1.1102 +}
  1.1103 +
  1.1104 +/* Internal routines */
  1.1105 +
  1.1106 +
  1.1107 +/* MBX mail parse mailbox
  1.1108 + * Accepts: MAIL stream
  1.1109 + * Returns: T if parse OK
  1.1110 + *	    NIL if failure, stream aborted
  1.1111 + */
  1.1112 +
  1.1113 +long mbx_parse (MAILSTREAM *stream)
  1.1114 +{
  1.1115 +  struct stat sbuf;
  1.1116 +  MESSAGECACHE *elt = NIL;
  1.1117 +  unsigned char c,*s,*t,*x;
  1.1118 +  char tmp[MAILTMPLEN];
  1.1119 +  unsigned long i,j,k,m;
  1.1120 +  off_t curpos = LOCAL->filesize;
  1.1121 +  unsigned long nmsgs = stream->nmsgs;
  1.1122 +  unsigned long recent = stream->recent;
  1.1123 +  unsigned long lastuid = 0;
  1.1124 +  short dirty = NIL;
  1.1125 +  short added = NIL;
  1.1126 +  short silent = stream->silent;
  1.1127 +  short uidwarn = T;
  1.1128 +  fstat (LOCAL->fd,&sbuf);	/* get status */
  1.1129 +  if (sbuf.st_size < curpos) {	/* sanity check */
  1.1130 +    sprintf (tmp,"Mailbox shrank from %lu to %lu!",
  1.1131 +	     (unsigned long) curpos,(unsigned long) sbuf.st_size);
  1.1132 +    mm_log (tmp,ERROR);
  1.1133 +    mbx_abort (stream);
  1.1134 +    return NIL;
  1.1135 +  }
  1.1136 +  lseek (LOCAL->fd,0,L_SET);	/* rewind file */
  1.1137 +				/* read internal header */
  1.1138 +  read (LOCAL->fd,LOCAL->buf,HDRSIZE);
  1.1139 +  LOCAL->buf[HDRSIZE] = '\0';	/* tie off header */
  1.1140 +  c = LOCAL->buf[15];		/* save first character of last UID */
  1.1141 +  LOCAL->buf[15] = '\0';
  1.1142 +				/* parse UID validity */
  1.1143 +  stream->uid_validity = strtoul (LOCAL->buf + 7,NIL,16);
  1.1144 +  LOCAL->buf[15] = c;		/* restore first character of last UID */
  1.1145 +				/* parse last UID */
  1.1146 +  i = strtoul (LOCAL->buf + 15,NIL,16);
  1.1147 +  stream->uid_last = stream->rdonly ? max (i,stream->uid_last) : i;
  1.1148 +				/* parse user flags */
  1.1149 +  for (i = 0, s = LOCAL->buf + 25;
  1.1150 +       (i < NUSERFLAGS) && (t = strchr (s,'\015')) && (t - s);
  1.1151 +       i++, s = t + 2) {
  1.1152 +    *t = '\0';			/* tie off flag */
  1.1153 +    if (!stream->user_flags[i] && (strlen (s) <= MAXUSERFLAG))
  1.1154 +      stream->user_flags[i] = cpystr (s);
  1.1155 +  }
  1.1156 +  LOCAL->ffuserflag = (int) i;	/* first free user flag */
  1.1157 +
  1.1158 +  stream->silent = T;		/* don't pass up mm_exists() events yet */
  1.1159 +  while (sbuf.st_size - curpos){/* while there is stuff to parse */
  1.1160 +				/* get to that position in the file */
  1.1161 +    lseek (LOCAL->fd,curpos,L_SET);
  1.1162 +    if ((i = read (LOCAL->fd,LOCAL->buf,64)) <= 0) {
  1.1163 +      sprintf (tmp,"Unable to read internal header at %lu, size = %lu: %s",
  1.1164 +	       (unsigned long) curpos,(unsigned long) sbuf.st_size,
  1.1165 +	       i ? strerror (errno) : "no data read");
  1.1166 +      mm_log (tmp,ERROR);
  1.1167 +      mbx_abort (stream);
  1.1168 +      return NIL;
  1.1169 +    }
  1.1170 +    LOCAL->buf[i] = '\0';	/* tie off buffer just in case */
  1.1171 +    if (!((s = strchr (LOCAL->buf,'\015')) && (s[1] == '\012'))) {
  1.1172 +      sprintf (tmp,"Unable to find CRLF at %lu in %lu bytes, text: %.80s",
  1.1173 +	       (unsigned long) curpos,i,(char *) LOCAL->buf);
  1.1174 +      mm_log (tmp,ERROR);
  1.1175 +      mbx_abort (stream);
  1.1176 +      return NIL;
  1.1177 +    }
  1.1178 +    *s = '\0';			/* tie off header line */
  1.1179 +    i = (s + 2) - LOCAL->buf;	/* note start of text offset */
  1.1180 +    if (!((s = strchr (LOCAL->buf,',')) && (t = strchr (s+1,';')))) {
  1.1181 +      sprintf (tmp,"Unable to parse internal header at %lu: %.80s",
  1.1182 +	       (unsigned long) curpos,(char *) LOCAL->buf);
  1.1183 +      mm_log (tmp,ERROR);
  1.1184 +      mbx_abort (stream);
  1.1185 +      return NIL;
  1.1186 +    }
  1.1187 +    if (!(isxdigit (t[1]) && isxdigit (t[2]) && isxdigit (t[3]) &&
  1.1188 +	  isxdigit (t[4]) && isxdigit (t[5]) && isxdigit (t[6]) &&
  1.1189 +	  isxdigit (t[7]) && isxdigit (t[8]) && isxdigit (t[9]) &&
  1.1190 +	  isxdigit (t[10]) && isxdigit (t[11]) && isxdigit (t[12]))) {
  1.1191 +      sprintf (tmp,"Unable to parse message flags at %lu: %.80s",
  1.1192 +	       (unsigned long) curpos,(char *) LOCAL->buf);
  1.1193 +      mm_log (tmp,ERROR);
  1.1194 +      mbx_abort (stream);
  1.1195 +      return NIL;
  1.1196 +    }
  1.1197 +    if ((t[13] != '-') || t[22] ||
  1.1198 +	!(isxdigit (t[14]) && isxdigit (t[15]) && isxdigit (t[16]) &&
  1.1199 +	  isxdigit (t[17]) && isxdigit (t[18]) && isxdigit (t[19]) &&
  1.1200 +	  isxdigit (t[20]) && isxdigit (t[21]))) {
  1.1201 +      sprintf (tmp,"Unable to parse message UID at %lu: %.80s",
  1.1202 +	       (unsigned long) curpos,(char *) LOCAL->buf);
  1.1203 +      mm_log (tmp,ERROR);
  1.1204 +      mbx_abort (stream);
  1.1205 +      return NIL;
  1.1206 +    }
  1.1207 +
  1.1208 +    *s++ = '\0'; *t++ = '\0';	/* break up fields */
  1.1209 +				/* get message size */
  1.1210 +    if (!(j = strtoul (s,(char **) &x,10)) && (!(x && *x))) {
  1.1211 +      sprintf (tmp,"Unable to parse message size at %lu: %.80s,%.80s;%.80s",
  1.1212 +	       (unsigned long) curpos,(char *) LOCAL->buf,(char *) s,
  1.1213 +	       (char *) t);
  1.1214 +      mm_log (tmp,ERROR);
  1.1215 +      mbx_abort (stream);
  1.1216 +      return NIL;
  1.1217 +    }
  1.1218 +				/* make sure didn't run off end of file */
  1.1219 +    if (((off_t) (curpos + i + j)) > sbuf.st_size) {
  1.1220 +      sprintf (tmp,"Last message (at %lu) runs past end of file (%lu > %lu)",
  1.1221 +	       (unsigned long) curpos,(unsigned long) (curpos + i + j),
  1.1222 +	       (unsigned long) sbuf.st_size);
  1.1223 +      mm_log (tmp,ERROR);
  1.1224 +      mbx_abort (stream);
  1.1225 +      return NIL;
  1.1226 +    }
  1.1227 +				/* parse UID */
  1.1228 +    if ((m = strtoul (t+13,NIL,16)) &&
  1.1229 +	((m <= lastuid) || (m > stream->uid_last))) {
  1.1230 +      if (uidwarn) {
  1.1231 +	sprintf (tmp,"Invalid UID %08lx in message %lu, rebuilding UIDs",
  1.1232 +		 m,nmsgs+1);
  1.1233 +	mm_log (tmp,WARN);
  1.1234 +	uidwarn = NIL;
  1.1235 +				/* restart UID validity */
  1.1236 +	stream->uid_validity = (unsigned long) time (0);
  1.1237 +      }
  1.1238 +      m = 0;			/* lose this UID */
  1.1239 +      dirty = T;		/* mark dirty, set new lastuid */
  1.1240 +      stream->uid_last = lastuid;
  1.1241 +    }
  1.1242 +
  1.1243 +    t[12] = '\0';		/* parse system flags */
  1.1244 +    if ((k = strtoul (t+8,NIL,16)) & fEXPUNGED) {
  1.1245 +      if (m) lastuid = m;	/* expunge message, update last UID seen */
  1.1246 +      else {			/* no UID assigned? */
  1.1247 +	lastuid = ++stream->uid_last;
  1.1248 +	dirty = T;
  1.1249 +      }
  1.1250 +    }
  1.1251 +    else {			/* not expunged, swell the cache */
  1.1252 +      added = T;		/* note that a new message was added */
  1.1253 +      mail_exists (stream,++nmsgs);
  1.1254 +				/* instantiate an elt for this message */
  1.1255 +      (elt = mail_elt (stream,nmsgs))->valid = T;
  1.1256 +				/* parse the date */
  1.1257 +      if (!mail_parse_date (elt,LOCAL->buf)) {
  1.1258 +	sprintf (tmp,"Unable to parse message date at %lu: %.80s",
  1.1259 +		 (unsigned long) curpos,(char *) LOCAL->buf);
  1.1260 +	mm_log (tmp,ERROR);
  1.1261 +	mbx_abort (stream);
  1.1262 +	return NIL;
  1.1263 +      }
  1.1264 +				/* note file offset of header */
  1.1265 +      elt->private.special.offset = curpos;
  1.1266 +				/* and internal header size */
  1.1267 +      elt->private.special.text.size = i;
  1.1268 +				/* header size not known yet */
  1.1269 +      elt->private.msg.header.text.size = 0;
  1.1270 +      elt->rfc822_size = j;	/* note message size */
  1.1271 +				/* calculate system flags */
  1.1272 +      if (k & fSEEN) elt->seen = T;
  1.1273 +      if (k & fDELETED) elt->deleted = T;
  1.1274 +      if (k & fFLAGGED) elt->flagged = T;
  1.1275 +      if (k & fANSWERED) elt->answered = T;
  1.1276 +      if (k & fDRAFT) elt->draft = T;
  1.1277 +      t[8] = '\0';		/* get user flags value */
  1.1278 +      elt->user_flags = strtoul (t,NIL,16);
  1.1279 +				/* UID already assigned? */
  1.1280 +      if (!(elt->private.uid = m) || !(k & fOLD)) {
  1.1281 +	elt->recent = T;	/* no, mark as recent */
  1.1282 +	++recent;		/* count up a new recent message */
  1.1283 +	dirty = T;		/* and must rewrite header */
  1.1284 +				/* assign new UID */
  1.1285 +	if (!elt->private.uid) elt->private.uid = ++stream->uid_last;
  1.1286 +	mbx_update_status (stream,elt->msgno,NIL);
  1.1287 +      }
  1.1288 +				/* update last parsed UID */
  1.1289 +      lastuid = elt->private.uid;
  1.1290 +    }
  1.1291 +    curpos += i + j;		/* update position */
  1.1292 +  }
  1.1293 +
  1.1294 +  if (dirty && !stream->rdonly){/* update header */
  1.1295 +    mbx_update_header (stream);
  1.1296 +    fsync (LOCAL->fd);		/* make sure all the UID updates take */
  1.1297 +  }
  1.1298 +				/* update parsed file size and time */
  1.1299 +  LOCAL->filesize = sbuf.st_size;
  1.1300 +  fstat (LOCAL->fd,&sbuf);	/* get status again to ensure time is right */
  1.1301 +  LOCAL->filetime = sbuf.st_mtime;
  1.1302 +  if (added && !stream->rdonly){/* make sure atime updated */
  1.1303 +    struct utimbuf times;
  1.1304 +    times.actime = time (0);
  1.1305 +    times.modtime = LOCAL->filetime;
  1.1306 +    utime (stream->mailbox,&times);
  1.1307 +  }
  1.1308 +  stream->silent = silent;	/* can pass up events now */
  1.1309 +  mail_exists (stream,nmsgs);	/* notify upper level of new mailbox size */
  1.1310 +  mail_recent (stream,recent);	/* and of change in recent messages */
  1.1311 +  return LONGT;			/* return the winnage */
  1.1312 +}
  1.1313 +
  1.1314 +/* MBX get cache element with status updating from file
  1.1315 + * Accepts: MAIL stream
  1.1316 + *	    message number
  1.1317 + *	    expunge OK flag
  1.1318 + * Returns: cache element
  1.1319 + */
  1.1320 +
  1.1321 +MESSAGECACHE *mbx_elt (MAILSTREAM *stream,unsigned long msgno,long expok)
  1.1322 +{
  1.1323 +  MESSAGECACHE *elt = mail_elt (stream,msgno);
  1.1324 +  struct {			/* old flags */
  1.1325 +    unsigned int seen : 1;
  1.1326 +    unsigned int deleted : 1;
  1.1327 +    unsigned int flagged : 1;
  1.1328 +    unsigned int answered : 1;
  1.1329 +    unsigned int draft : 1;
  1.1330 +    unsigned long user_flags;
  1.1331 +  } old;
  1.1332 +  old.seen = elt->seen; old.deleted = elt->deleted; old.flagged = elt->flagged;
  1.1333 +  old.answered = elt->answered; old.draft = elt->draft;
  1.1334 +  old.user_flags = elt->user_flags;
  1.1335 +				/* get new flags */
  1.1336 +  if (mbx_read_flags (stream,elt) && expok) {
  1.1337 +    mail_expunged (stream,elt->msgno);
  1.1338 +    return NIL;			/* return this message was expunged */
  1.1339 +  }
  1.1340 +  if ((old.seen != elt->seen) || (old.deleted != elt->deleted) ||
  1.1341 +      (old.flagged != elt->flagged) || (old.answered != elt->answered) ||
  1.1342 +      (old.draft != elt->draft) || (old.user_flags != elt->user_flags))
  1.1343 +    mm_flags (stream,msgno);	/* let top level know */
  1.1344 +  return elt;
  1.1345 +}
  1.1346 +
  1.1347 +/* MBX read flags from file
  1.1348 + * Accepts: MAIL stream
  1.1349 + *	    cache element
  1.1350 + * Returns: non-NIL if message expunged
  1.1351 + */
  1.1352 +
  1.1353 +unsigned long mbx_read_flags (MAILSTREAM *stream,MESSAGECACHE *elt)
  1.1354 +{
  1.1355 +  unsigned long i;
  1.1356 +  struct stat sbuf;
  1.1357 +  fstat (LOCAL->fd,&sbuf);	/* get status */
  1.1358 +				/* make sure file size is good */
  1.1359 +  if (sbuf.st_size < LOCAL->filesize) {
  1.1360 +    sprintf (LOCAL->buf,"Mailbox shrank from %lu to %lu in flag read!",
  1.1361 +	     (unsigned long) LOCAL->filesize,(unsigned long) sbuf.st_size);
  1.1362 +    fatal (LOCAL->buf);
  1.1363 +  }
  1.1364 +				/* set the seek pointer */
  1.1365 +  lseek (LOCAL->fd,(off_t) elt->private.special.offset +
  1.1366 +	 elt->private.special.text.size - 24,L_SET);
  1.1367 +				/* read the new flags */
  1.1368 +  if (read (LOCAL->fd,LOCAL->buf,14) < 0) {
  1.1369 +    sprintf (LOCAL->buf,"Unable to read new status: %s",strerror (errno));
  1.1370 +    fatal (LOCAL->buf);
  1.1371 +  }
  1.1372 +  if ((LOCAL->buf[0] != ';') || (LOCAL->buf[13] != '-')) {
  1.1373 +    LOCAL->buf[14] = '\0';	/* tie off buffer for error message */
  1.1374 +    sprintf (LOCAL->buf+50,"Invalid flags for message %lu (%lu %lu): %s",
  1.1375 +	     elt->msgno,elt->private.special.offset,
  1.1376 +	     elt->private.special.text.size,(char *) LOCAL->buf);
  1.1377 +    fatal (LOCAL->buf+50);
  1.1378 +  }
  1.1379 +  LOCAL->buf[13] = '\0';	/* tie off buffer */
  1.1380 +				/* calculate system flags */
  1.1381 +  i = strtoul (LOCAL->buf+9,NIL,16);
  1.1382 +  elt->seen = i & fSEEN ? T : NIL;
  1.1383 +  elt->deleted = i & fDELETED ? T : NIL;
  1.1384 +  elt->flagged = i & fFLAGGED ? T : NIL;
  1.1385 +  elt->answered = i & fANSWERED ? T : NIL;
  1.1386 +  elt->draft = i & fDRAFT ? T : NIL;
  1.1387 +  LOCAL->expunged |= i & fEXPUNGED ? T : NIL;
  1.1388 +  LOCAL->buf[9] = '\0';		/* tie off flags */
  1.1389 +				/* get user flags value */
  1.1390 +  elt->user_flags = strtoul (LOCAL->buf+1,NIL,16);
  1.1391 +  elt->valid = T;		/* have valid flags now */
  1.1392 +  return i & fEXPUNGED;
  1.1393 +}
  1.1394 +
  1.1395 +/* MBX update header
  1.1396 + * Accepts: MAIL stream
  1.1397 + */
  1.1398 +
  1.1399 +#define NTKLUDGEOFFSET 7
  1.1400 +
  1.1401 +void mbx_update_header (MAILSTREAM *stream)
  1.1402 +{
  1.1403 +  int i;
  1.1404 +  char *s = LOCAL->buf;
  1.1405 +  memset (s,'\0',HDRSIZE);	/* initialize header */
  1.1406 +  sprintf (s,"*mbx*\015\012%08lx%08lx\015\012",
  1.1407 +	   stream->uid_validity,stream->uid_last);
  1.1408 +  for (i = 0; (i < NUSERFLAGS) && stream->user_flags[i]; ++i)
  1.1409 +    sprintf (s += strlen (s),"%s\015\012",stream->user_flags[i]);
  1.1410 +  LOCAL->ffuserflag = i;	/* first free user flag */
  1.1411 +				/* can we create more user flags? */
  1.1412 +  stream->kwd_create = (i < NUSERFLAGS) ? T : NIL;
  1.1413 +				/* write reserved lines */
  1.1414 +  while (i++ < NUSERFLAGS) strcat (s,"\015\012");
  1.1415 +  while (T) {			/* rewind file */
  1.1416 +    lseek (LOCAL->fd,NTKLUDGEOFFSET,L_SET);
  1.1417 +				/* write new header */
  1.1418 +    if (write (LOCAL->fd,LOCAL->buf + NTKLUDGEOFFSET,
  1.1419 +	       HDRSIZE - NTKLUDGEOFFSET) > 0) break;
  1.1420 +    mm_notify (stream,strerror (errno),WARN);
  1.1421 +    mm_diskerror (stream,errno,T);
  1.1422 +  }
  1.1423 +}
  1.1424 +
  1.1425 +/* MBX update status string
  1.1426 + * Accepts: MAIL stream
  1.1427 + *	    message number
  1.1428 + *	    flags
  1.1429 + */
  1.1430 +
  1.1431 +void mbx_update_status (MAILSTREAM *stream,unsigned long msgno,long flags)
  1.1432 +{
  1.1433 +  struct stat sbuf;
  1.1434 +  MESSAGECACHE *elt = mail_elt (stream,msgno);
  1.1435 +				/* readonly */
  1.1436 +  if (stream->rdonly || !elt->valid) mbx_read_flags (stream,elt);
  1.1437 +  else {			/* readwrite */
  1.1438 +    fstat (LOCAL->fd,&sbuf);	/* get status */
  1.1439 +				/* make sure file size is good */
  1.1440 +    if (sbuf.st_size < LOCAL->filesize) {
  1.1441 +      sprintf (LOCAL->buf,"Mailbox shrank from %lu to %lu in flag update!",
  1.1442 +	       (unsigned long) LOCAL->filesize,(unsigned long) sbuf.st_size);
  1.1443 +      fatal (LOCAL->buf);
  1.1444 +    }
  1.1445 +				/* set the seek pointer */
  1.1446 +    lseek (LOCAL->fd,(off_t) elt->private.special.offset +
  1.1447 +	   elt->private.special.text.size - 24,L_SET);
  1.1448 +				/* read the new flags */
  1.1449 +    if (read (LOCAL->fd,LOCAL->buf,14) < 0) {
  1.1450 +      sprintf (LOCAL->buf,"Unable to read old status: %s",strerror (errno));
  1.1451 +      fatal (LOCAL->buf);
  1.1452 +    }
  1.1453 +    if ((LOCAL->buf[0] != ';') || (LOCAL->buf[13] != '-')) {
  1.1454 +      LOCAL->buf[14] = '\0';	/* tie off buffer for error message */
  1.1455 +      sprintf (LOCAL->buf+50,"Invalid flags for message %lu (%lu %lu): %s",
  1.1456 +	       elt->msgno,elt->private.special.offset,
  1.1457 +	       elt->private.special.text.size,(char *) LOCAL->buf);
  1.1458 +      fatal (LOCAL->buf+50);
  1.1459 +    }
  1.1460 +				/* print new flag string */
  1.1461 +    sprintf (LOCAL->buf,"%08lx%04x-%08lx",elt->user_flags,(unsigned)
  1.1462 +	     (((elt->deleted && flags) ?
  1.1463 +	       fEXPUNGED : (strtoul (LOCAL->buf+9,NIL,16)) & fEXPUNGED) +
  1.1464 +	      (fSEEN * elt->seen) + (fDELETED * elt->deleted) +
  1.1465 +	      (fFLAGGED * elt->flagged) + (fANSWERED * elt->answered) +
  1.1466 +	      (fDRAFT * elt->draft) + fOLD),elt->private.uid);
  1.1467 +    while (T) {			/* get to that place in the file */
  1.1468 +      lseek (LOCAL->fd,(off_t) elt->private.special.offset +
  1.1469 +	     elt->private.special.text.size - 23,L_SET);
  1.1470 +				/* write new flags and UID */
  1.1471 +      if (write (LOCAL->fd,LOCAL->buf,21) > 0) break;
  1.1472 +      mm_notify (stream,strerror (errno),WARN);
  1.1473 +      mm_diskerror (stream,errno,T);
  1.1474 +    }
  1.1475 +  }
  1.1476 +}
  1.1477 +
  1.1478 +/* MBX locate header for a message
  1.1479 + * Accepts: MAIL stream
  1.1480 + *	    message number
  1.1481 + *	    pointer to returned header size
  1.1482 + *	    pointer to possible returned header
  1.1483 + * Returns: position of header in file
  1.1484 + */
  1.1485 +
  1.1486 +#define HDRBUFLEN 16384		/* good enough for most headers */
  1.1487 +#define SLOP 4			/* CR LF CR LF */
  1.1488 +
  1.1489 +unsigned long mbx_hdrpos (MAILSTREAM *stream,unsigned long msgno,
  1.1490 +			  unsigned long *size,char **hdr)
  1.1491 +{
  1.1492 +  unsigned long siz,done;
  1.1493 +  long i;
  1.1494 +  unsigned char *s,*t,*te;
  1.1495 +  MESSAGECACHE *elt = mail_elt (stream,msgno);
  1.1496 +  unsigned long ret = elt->private.special.offset +
  1.1497 +    elt->private.special.text.size;
  1.1498 +  if (hdr) *hdr = NIL;		/* assume no header returned */
  1.1499 +				/* is header size known? */ 
  1.1500 +  if (*size = elt->private.msg.header.text.size) return ret;
  1.1501 +				/* paranoia check */
  1.1502 +  if (LOCAL->buflen < (HDRBUFLEN + SLOP))
  1.1503 +    fatal ("LOCAL->buf smaller than HDRBUFLEN");
  1.1504 +  lseek (LOCAL->fd,ret,L_SET);	/* get to header position */
  1.1505 +				/* read HDRBUFLEN chunks with 4 byte slop */
  1.1506 +  for (done = siz = 0, s = LOCAL->buf;
  1.1507 +       (i = min ((long) (elt->rfc822_size - done),(long) HDRBUFLEN)) &&
  1.1508 +       (read (LOCAL->fd,s,i) == i);
  1.1509 +       done += i, siz += (t - LOCAL->buf) - SLOP, s = LOCAL->buf + SLOP) {
  1.1510 +    te = (t = s + i) - 12;	/* calculate end of fast scan */
  1.1511 +				/* fast scan for CR */
  1.1512 +    for (s = LOCAL->buf; s < te;)
  1.1513 +      if (((*s++ == '\015') || (*s++ == '\015') || (*s++ == '\015') ||
  1.1514 +	   (*s++ == '\015') || (*s++ == '\015') || (*s++ == '\015') ||
  1.1515 +	   (*s++ == '\015') || (*s++ == '\015') || (*s++ == '\015') ||
  1.1516 +	   (*s++ == '\015') || (*s++ == '\015') || (*s++ == '\015')) &&
  1.1517 +	  (*s == '\012') && (*++s == '\015') && (*++s == '\012')) {
  1.1518 +	*size = elt->private.msg.header.text.size = siz + (++s - LOCAL->buf);
  1.1519 +	if (hdr) *hdr = LOCAL->buf;
  1.1520 +	return ret;
  1.1521 +      }
  1.1522 +    for (te = t - 3; (s < te);)	/* final character-at-a-time scan */
  1.1523 +      if ((*s++ == '\015') && (*s == '\012') && (*++s == '\015') &&
  1.1524 +	  (*++s == '\012')) {
  1.1525 +	*size = elt->private.msg.header.text.size = siz + (++s - LOCAL->buf);
  1.1526 +	if (hdr) *hdr = LOCAL->buf;
  1.1527 +	return ret;
  1.1528 +      }
  1.1529 +    if (i <= SLOP) break;	/* end of data */
  1.1530 +				/* slide over last 4 bytes */
  1.1531 +    memmove (LOCAL->buf,t - SLOP,SLOP);
  1.1532 +    hdr = NIL;			/* can't return header this way */
  1.1533 +  }
  1.1534 +				/* not found: header consumes entire message */
  1.1535 +  elt->private.msg.header.text.size = *size = elt->rfc822_size;
  1.1536 +  if (hdr) *hdr = LOCAL->buf;	/* possibly return header too */
  1.1537 +  return ret;
  1.1538 +}
  1.1539 +
  1.1540 +/* MBX mail rewrite mailbox
  1.1541 + * Accepts: MAIL stream
  1.1542 + *	    pointer to return reclaimed size
  1.1543 + *	    flags (0 = no expunge, 1 = expunge deleted, -1 = expunge sequence)
  1.1544 + * Returns: number of expunged messages
  1.1545 + */
  1.1546 +
  1.1547 +unsigned long mbx_rewrite (MAILSTREAM *stream,unsigned long *reclaimed,
  1.1548 +			   long flags)
  1.1549 +{
  1.1550 +  struct utimbuf times;
  1.1551 +  struct stat sbuf;
  1.1552 +  off_t pos,ppos;
  1.1553 +  int ld;
  1.1554 +  unsigned long i,j,k,m,delta;
  1.1555 +  unsigned long n = *reclaimed = 0;
  1.1556 +  unsigned long recent = 0;
  1.1557 +  char lock[MAILTMPLEN];
  1.1558 +  MESSAGECACHE *elt;
  1.1559 +				/* get parse/append permission */
  1.1560 +  if ((ld = lockname (lock,stream->mailbox,LOCK_EX)) < 0) {
  1.1561 +    mm_log ("Unable to lock expunge mailbox",ERROR);
  1.1562 +    return 0;
  1.1563 +  }
  1.1564 +  fstat (LOCAL->fd,&sbuf);	/* get current write time */
  1.1565 +  if (LOCAL->filetime && !LOCAL->flagcheck &&
  1.1566 +      (LOCAL->filetime < sbuf.st_mtime)) LOCAL->flagcheck = T;
  1.1567 +  if (!mbx_parse (stream)) {	/* make sure see any newly-arrived messages */
  1.1568 +    unlockfd (ld,lock);		/* failed?? */
  1.1569 +    return 0;
  1.1570 +  }
  1.1571 +  if (LOCAL->flagcheck) {	/* sweep flags if need flagcheck */
  1.1572 +    LOCAL->filetime = sbuf.st_mtime;
  1.1573 +    for (i = 1; i <= stream->nmsgs; ++i) mbx_elt (stream,i,NIL);
  1.1574 +    LOCAL->flagcheck = NIL;
  1.1575 +  }
  1.1576 +
  1.1577 +				/* get exclusive access */
  1.1578 +  if (!flock (LOCAL->fd,LOCK_EX|LOCK_NB)) {
  1.1579 +    mm_critical (stream);	/* go critical */
  1.1580 +    for (i = 1,delta = 0,pos = ppos = HDRSIZE; i <= stream->nmsgs; ) {
  1.1581 +				/* note if message not at predicted location */
  1.1582 +      if (m = (elt = mbx_elt (stream,i,NIL))->private.special.offset - ppos) {
  1.1583 +	ppos = elt->private.special.offset;
  1.1584 +	*reclaimed += m;	/* note reclaimed message space */
  1.1585 +	delta += m;		/* and as expunge delta  */
  1.1586 +      }
  1.1587 +				/* number of bytes to smash or preserve */
  1.1588 +      ppos += (k = elt->private.special.text.size + elt->rfc822_size);
  1.1589 +				/* if need to expunge this message*/
  1.1590 +      if (flags && elt->deleted && ((flags > 0) || elt->sequence)) {
  1.1591 +	delta += k;		/* number of bytes to delete */
  1.1592 +	mail_expunged(stream,i);/* notify upper levels */
  1.1593 +	n++;			/* count up one more expunged message */
  1.1594 +      }
  1.1595 +      else {			/* preserved message */
  1.1596 +	i++;			/* count this message */
  1.1597 +	if (elt->recent) ++recent;
  1.1598 +	if (delta) {		/* moved, note first byte to preserve */
  1.1599 +	  j = elt->private.special.offset;
  1.1600 +	  do {			/* read from source position */
  1.1601 +	    m = min (k,LOCAL->buflen);
  1.1602 +	    lseek (LOCAL->fd,j,L_SET);
  1.1603 +	    read (LOCAL->fd,LOCAL->buf,m);
  1.1604 +	    pos = j - delta;	/* write to destination position */
  1.1605 +	    while (T) {
  1.1606 +	      lseek (LOCAL->fd,pos,L_SET);
  1.1607 +	      if (write (LOCAL->fd,LOCAL->buf,m) > 0) break;
  1.1608 +	      mm_notify (stream,strerror (errno),WARN);
  1.1609 +	      mm_diskerror (stream,errno,T);
  1.1610 +	    }
  1.1611 +	    pos += m;		/* new position */
  1.1612 +	    j += m;		/* next chunk, perhaps */
  1.1613 +	  } while (k -= m);	/* until done */
  1.1614 +				/* note the new address of this text */
  1.1615 +	  elt->private.special.offset -= delta;
  1.1616 +	}
  1.1617 +				/* preserved but no deleted messages yet */
  1.1618 +	else pos = elt->private.special.offset + k;
  1.1619 +      }
  1.1620 +    }
  1.1621 +				/* deltaed file size match position? */
  1.1622 +    if (m = (LOCAL->filesize -= delta) - pos) {
  1.1623 +      *reclaimed += m;		/* probably an fEXPUNGED msg */
  1.1624 +      LOCAL->filesize = pos;	/* set correct size */
  1.1625 +    }
  1.1626 +				/* truncate file after last message */
  1.1627 +    ftruncate (LOCAL->fd,LOCAL->filesize);
  1.1628 +    fsync (LOCAL->fd);		/* force disk update */
  1.1629 +    mm_nocritical (stream);	/* release critical */
  1.1630 +    flock (LOCAL->fd,LOCK_SH);	/* allow sharers again */
  1.1631 +  }
  1.1632 +
  1.1633 +  else {			/* can't get exclusive */
  1.1634 +    flock (LOCAL->fd,LOCK_SH);	/* recover previous shared mailbox lock */
  1.1635 +				/* do hide-expunge when shared */
  1.1636 +    if (flags) for (i = 1; i <= stream->nmsgs; ) {
  1.1637 +      if (elt = mbx_elt (stream,i,T)) {
  1.1638 +				/* make the message invisible */
  1.1639 +	if (elt->deleted && ((flags > 0) || elt->sequence)) {
  1.1640 +	  mbx_update_status (stream,elt->msgno,LONGT);
  1.1641 +				/* notify upper levels */
  1.1642 +	  mail_expunged (stream,i);
  1.1643 +	  n++;			/* count up one more expunged message */
  1.1644 +	}
  1.1645 +	else {
  1.1646 +	  i++;			/* preserved message */
  1.1647 +	  if (elt->recent) ++recent;
  1.1648 +	}
  1.1649 +      }
  1.1650 +      else n++;			/* count up one more expunged message */
  1.1651 +    }
  1.1652 +    fsync (LOCAL->fd);		/* force disk update */
  1.1653 +  }
  1.1654 +  fstat (LOCAL->fd,&sbuf);	/* get new write time */
  1.1655 +  times.modtime = LOCAL->filetime = sbuf.st_mtime;
  1.1656 +  times.actime = time (0);	/* reset atime to now */
  1.1657 +  utime (stream->mailbox,&times);
  1.1658 +  unlockfd (ld,lock);		/* release exclusive parse/append permission */
  1.1659 +				/* notify upper level of new mailbox size */
  1.1660 +  mail_exists (stream,stream->nmsgs);
  1.1661 +  mail_recent (stream,recent);
  1.1662 +  return n;			/* return number of expunged messages */
  1.1663 +}
  1.1664 +
  1.1665 +/* MBX mail lock for flag updating
  1.1666 + * Accepts: stream
  1.1667 + * Returns: T if successful, NIL if failure
  1.1668 + */
  1.1669 +
  1.1670 +long mbx_flaglock (MAILSTREAM *stream)
  1.1671 +{
  1.1672 +  struct stat sbuf;
  1.1673 +  unsigned long i;
  1.1674 +  int ld;
  1.1675 +  char lock[MAILTMPLEN];
  1.1676 +				/* no-op if readonly or already locked */
  1.1677 +  if (!stream->rdonly && LOCAL && (LOCAL->fd >= 0) && (LOCAL->ld < 0)) {
  1.1678 +				/* lock now */
  1.1679 +    if ((ld = lockname (lock,stream->mailbox,LOCK_EX)) < 0) return NIL;
  1.1680 +    if (!LOCAL->flagcheck) {	/* don't do this if flagcheck already needed */
  1.1681 +      if (LOCAL->filetime) {	/* know previous time? */
  1.1682 +	fstat (LOCAL->fd,&sbuf);/* get current write time */
  1.1683 +	if (LOCAL->filetime < sbuf.st_mtime) LOCAL->flagcheck = T;
  1.1684 +	LOCAL->filetime = 0;	/* don't do this test for any other messages */
  1.1685 +      }
  1.1686 +      if (!mbx_parse (stream)) {/* parse mailbox */
  1.1687 +	unlockfd (ld,lock);	/* shouldn't happen */
  1.1688 +	return NIL;
  1.1689 +      }
  1.1690 +      if (LOCAL->flagcheck)	/* invalidate cache if flagcheck */
  1.1691 +	for (i = 1; i <= stream->nmsgs; ++i) mail_elt (stream,i)->valid = NIL;
  1.1692 +    }
  1.1693 +    LOCAL->ld = ld;		/* copy to stream for subsequent calls */
  1.1694 +    memcpy (LOCAL->lock,lock,MAILTMPLEN);
  1.1695 +  }
  1.1696 +  return LONGT;
  1.1697 +}

UW-IMAP'd extensions by yuuji