root/trunk/lib-src/movemail.c

Revision 4220, 22.3 kB (checked in by miyoshi, 8 months ago)

Sync up with Emacs22.2.

  • Property svn:eol-style set to native
<
Line 
1 /* movemail foo bar -- move file foo to file bar,
2    locking file foo the way /bin/mail respects.
3    Copyright (C) 1986, 1992, 1993, 1994, 1996, 1999, 2001, 2002, 2003, 2004,
4                  2005, 2006, 2007, 2008  Free Software Foundation, Inc.
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs; see the file COPYING.  If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA.  */
22
23 /* Important notice: defining MAIL_USE_FLOCK or MAIL_USE_LOCKF *will
24    cause loss of mail* if you do it on a system that does not normally
25    use flock as its way of interlocking access to inbox files.  The
26    setting of MAIL_USE_FLOCK and MAIL_USE_LOCKF *must agree* with the
27    system's own conventions.  It is not a choice that is up to you.
28
29    So, if your system uses lock files rather than flock, then the only way
30    you can get proper operation is to enable movemail to write lockfiles there.
31    This means you must either give that directory access modes
32    that permit everyone to write lockfiles in it, or you must make movemail
33    a setuid or setgid program.  */
34
35 /*
36  * Modified January, 1986 by Michael R. Gretzinger (Project Athena)
37  *
38  * Added POP (Post Office Protocol) service.  When compiled -DMAIL_USE_POP
39  * movemail will accept input filename arguments of the form
40  * "po:username".  This will cause movemail to open a connection to
41  * a pop server running on $MAILHOST (environment variable).  Movemail
42  * must be setuid to root in order to work with POP.
43  *
44  * New module: popmail.c
45  * Modified routines:
46  *      main - added code within #ifdef MAIL_USE_POP; added setuid (getuid ())
47  *              after POP code.
48  * New routines in movemail.c:
49  *      get_errmsg - return pointer to system error message
50  *
51  * Modified August, 1993 by Jonathan Kamens (OpenVision Technologies)
52  *
53  * Move all of the POP code into a separate file, "pop.c".
54  * Use strerror instead of get_errmsg.
55  *
56  */
57
58 #define NO_SHORTNAMES   /* Tell config not to load remap.h */
59 #include <config.h>
60 #include <sys/types.h>
61 #include <sys/stat.h>
62 #include <sys/file.h>
63 #include <stdio.h>
64 #include <errno.h>
65
66 #include <getopt.h>
67 #ifdef HAVE_UNISTD_H
68 #include <unistd.h>
69 #endif
70 #ifdef HAVE_FCNTL_H
71 #include <fcntl.h>
72 #endif
73 #include "syswait.h"
74 #ifdef MAIL_USE_POP
75 #include "pop.h"
76 #endif
77
78 #ifdef MSDOS
79 #undef access
80 #endif /* MSDOS */
81
82 #ifndef DIRECTORY_SEP
83 #define DIRECTORY_SEP '/'
84 #endif
85 #ifndef IS_DIRECTORY_SEP
86 #define IS_DIRECTORY_SEP(_c_) ((_c_) == DIRECTORY_SEP)
87 #endif
88
89 #ifdef WINDOWSNT
90 #include "ntlib.h"
91 #ifndef MEADOW
92 #undef access
93 #undef unlink
94 #endif
95 #define fork() 0
96 #define wait(var) (*(var) = 0)
97 /* Unfortunately, Samba doesn't seem to properly lock Unix files even
98    though the locking call succeeds (and indeed blocks local access from
99    other NT programs).  If you have direct file access using an NFS
100    client or something other than Samba, the locking call might work
101    properly - make sure it does before you enable this!
102
103    [18-Feb-97 andrewi] I now believe my comment above to be incorrect,
104    since it was based on a misunderstanding of how locking calls are
105    implemented and used on Unix.  */
106 //#define DISABLE_DIRECT_ACCESS
107
108 #include <fcntl.h>
109 #endif /* WINDOWSNT */
110
111 #ifndef F_OK
112 #define F_OK 0
113 #define X_OK 1
114 #define W_OK 2
115 #define R_OK 4
116 #endif
117
118 #if defined (XENIX) || defined (WINDOWSNT)
119 #include <sys/locking.h>
120 #endif
121
122 #ifdef MAIL_USE_LOCKF
123 #define MAIL_USE_SYSTEM_LOCK
124 #endif
125
126 #ifdef MAIL_USE_FLOCK
127 #define MAIL_USE_SYSTEM_LOCK
128 #endif
129
130 #ifdef MAIL_USE_MMDF
131 extern int lk_open (), lk_close ();
132 #endif
133
134 #if !defined (MAIL_USE_SYSTEM_LOCK) && !defined (MAIL_USE_MMDF) && \
135         (defined (HAVE_LIBMAIL) || defined (HAVE_LIBLOCKFILE)) && \
136         defined (HAVE_MAILLOCK_H)
137 #include <maillock.h>
138 /* We can't use maillock unless we know what directory system mail
139    files appear in. */
140 #ifdef MAILDIR
141 #define MAIL_USE_MAILLOCK
142 static char *mail_spool_name ();
143 #endif
144 #endif
145
146 #ifndef errno
147 extern int errno;
148 #endif
149 char *strerror ();
150 #ifdef HAVE_INDEX
151 extern char *index __P ((const char *, int));
152 #endif
153 #ifdef HAVE_RINDEX
154 extern char *rindex __P((const char *, int));
155 #endif
156
157 void fatal ();
158 void error ();
159 void pfatal_with_name ();
160 void pfatal_and_delete ();
161 char *concat ();
162 long *xmalloc ();
163 int popmail ();
164 int pop_retr ();
165 int mbx_write ();
166 int mbx_delimit_begin ();
167 int mbx_delimit_end ();
168
169 /* Nonzero means this is name of a lock file to delete on fatal error.  */
170 char *delete_lockname;
171
172 #ifdef MEADOW
173 #define USE_POP_OPT
174 #endif /* MEADOW */
175
176 int
177 main (argc, argv)
178      int argc;
179      char **argv;
180 {
181   char *inname, *outname;
182   int indesc, outdesc;
183   int nread;
184   WAITTYPE status;
185   int c, preserve_mail = 0;
186
187 #ifndef MAIL_USE_SYSTEM_LOCK
188   struct stat st;
189   long now;
190   int tem;
191   char *lockname, *p;
192   char *tempname;
193   int desc;
194 #endif /* not MAIL_USE_SYSTEM_LOCK */
195
196 #ifdef MAIL_USE_MAILLOCK
197   char *spool_name;
198 #endif
199
200 #ifdef MAIL_USE_POP
201   int pop_reverse_order = 0;
202 # define ARGSTR "pr"
203 #else /* ! MAIL_USE_POP */
204 # define ARGSTR "p"
205 #endif /* MAIL_USE_POP */
206
207 #ifdef WINDOWSNT
208   /* Ensure all file i/o is in binary mode. */
209   _fmode = _O_BINARY;
210 #endif
211
212   delete_lockname = 0;
213
214   while ((c = getopt (argc, argv, ARGSTR)) != EOF)
215     {
216       switch (c) {
217 #ifdef MAIL_USE_POP
218       case 'r':
219         pop_reverse_order = 1;
220         break;
221 #endif
222       case 'p':
223         preserve_mail++;
224         break;
225       default:
226         exit (EXIT_FAILURE);
227       }
228     }
229
230   if (
231 #ifdef MAIL_USE_POP
232       (argc - optind < 2) || (argc - optind > 3)
233 #else
234       (argc - optind != 2)
235 #endif
236       )
237     {
238 #ifdef MAIL_USE_POP
239       fprintf (stderr, "Usage: movemail [-p] inbox destfile%s\n",
240                " [POP-password]");
241 #else
242       fprintf (stderr, "Usage: movemail [-p] inbox destfile%s\n", "");
243 #endif
244       exit (EXIT_FAILURE);
245     }
246
247   inname = argv[optind];
248   outname = argv[optind+1];
249
250 #ifdef MAIL_USE_MMDF
251   mmdf_init (argv[0]);
252 #endif
253
254   if (*outname == 0)
255     fatal ("Destination file name is empty", 0, 0);
256
257   /* Check access to output file.  */
258   if (access (outname, F_OK) == 0 && access (outname, W_OK) != 0)
259     pfatal_with_name (outname);
260
261   /* Also check that outname's directory is writable to the real uid.  */
262   {
263     char *buf = (char *) xmalloc (strlen (outname) + 1);
264     char *p;
265     strcpy (buf, outname);
266     p = buf + strlen (buf);
267     while (p > buf && !IS_DIRECTORY_SEP (p[-1]))
268       *--p = 0;
269     if (p == buf)
270       *p++ = '.';
271     if (access (buf, W_OK) != 0)
272       pfatal_with_name (buf);
273     free (buf);
274   }
275
276 #ifdef MAIL_USE_POP
277   if (!strncmp (inname, "po:", 3))
278     {
279       int status;
280
281       status = popmail (inname + 3, outname, preserve_mail,
282                         (argc - optind == 3) ? argv[optind+2] : NULL,
283                         pop_reverse_order);
284       exit (status);
285     }
286
287   setuid (getuid ());
288 #endif /* MAIL_USE_POP */
289
290 #ifndef DISABLE_DIRECT_ACCESS
291
292   /* Check access to input file.  */
293   if (access (inname, R_OK | W_OK) != 0)
294     pfatal_with_name (inname);
295
296 #ifndef MAIL_USE_MMDF
297 #ifndef MAIL_USE_SYSTEM_LOCK
298 #ifdef MAIL_USE_MAILLOCK
299   spool_name = mail_spool_name (inname);
300   if (! spool_name)
301 #endif
302     {
303       /* Use a lock file named after our first argument with .lock appended:
304          If it exists, the mail file is locked.  */
305       /* Note: this locking mechanism is *required* by the mailer
306          (on systems which use it) to prevent loss of mail.
307
308          On systems that use a lock file, extracting the mail without locking
309          WILL occasionally cause loss of mail due to timing errors!
310
311          So, if creation of the lock file fails
312          due to access permission on the mail spool directory,
313          you simply MUST change the permission
314          and/or make movemail a setgid program
315          so it can create lock files properly.
316
317          You might also wish to verify that your system is one
318          which uses lock files for this purpose.  Some systems use other methods.
319
320          If your system uses the `flock' system call for mail locking,
321          define MAIL_USE_SYSTEM_LOCK in config.h or the s-*.h file
322          and recompile movemail.  If the s- file for your system
323          should define MAIL_USE_SYSTEM_LOCK but does not, send a bug report
324          to bug-gnu-emacs@prep.ai.mit.edu so we can fix it.  */
325
326       lockname = concat (inname, ".lock", "");
327       tempname = (char *) xmalloc (strlen (inname) + strlen ("EXXXXXX") + 1);
328       strcpy (tempname, inname);
329       p = tempname + strlen (tempname);
330       while (p != tempname && !IS_DIRECTORY_SEP (p[-1]))
331         p--;
332       *p = 0;
333       strcpy (p, "EXXXXXX");
334       mktemp (tempname);
335       unlink (tempname);
336
337       while (1)
338         {
339           /* Create the lock file, but not under the lock file name.  */
340           /* Give up if cannot do that.  */
341           desc = open (tempname, O_WRONLY | O_CREAT | O_EXCL, 0666);
342           if (desc < 0)
343             {
344               char *message = (char *) xmalloc (strlen (tempname) + 50);
345               sprintf (message, "creating %s, which would become the lock file",
346                        tempname);
347               pfatal_with_name (message);
348             }
349           close (desc);
350
351           tem = link (tempname, lockname);
352           unlink (tempname);
353           if (tem >= 0)
354             break;
355           sleep (1);
356
357           /* If lock file is five minutes old, unlock it.
358              Five minutes should be good enough to cope with crashes
359              and wedgitude, and long enough to avoid being fooled
360              by time differences between machines.  */
361           if (stat (lockname, &st) >= 0)
362             {
363               now = time (0);
364               if (st.st_ctime < now - 300)
365                 unlink (lockname);
366             }
367         }
368
369       delete_lockname = lockname;
370     }
371 #endif /* not MAIL_USE_SYSTEM_LOCK */
372 #endif /* not MAIL_USE_MMDF */
373
374   if (fork () == 0)
375     {
376       int lockcount = 0;
377       int status = 0;
378 #if defined (MAIL_USE_MAILLOCK) && defined (HAVE_TOUCHLOCK)
379       long touched_lock, now;
380 #endif
381
382       setuid (getuid ());
383
384 #ifndef MAIL_USE_MMDF
385 #ifdef MAIL_USE_SYSTEM_LOCK
386       indesc = open (inname, O_RDWR);
387 #else  /* if not MAIL_USE_SYSTEM_LOCK */
388       indesc = open (inname, O_RDONLY);
389 #endif /* not MAIL_USE_SYSTEM_LOCK */
390 #else  /* MAIL_USE_MMDF */
391       indesc = lk_open (inname, O_RDONLY, 0, 0, 10);
392 #endif /* MAIL_USE_MMDF */
393
394       if (indesc < 0)
395         pfatal_with_name (inname);
396
397 #if defined (BSD_SYSTEM) || defined (XENIX)
398       /* In case movemail is setuid to root, make sure the user can
399          read the output file.  */
400       /* This is desirable for all systems
401          but I don't want to assume all have the umask system call */
402       umask (umask (0) & 0333);
403 #endif /* BSD_SYSTEM || XENIX */
404       outdesc = open (outname, O_WRONLY | O_CREAT | O_EXCL, 0666);
405       if (outdesc < 0)
406         pfatal_with_name (outname);
407
408       /* This label exists so we can retry locking
409          after a delay, if it got EAGAIN or EBUSY.  */
410     retry_lock:
411
412       /* Try to lock it.  */
413 #ifdef MAIL_USE_MAILLOCK
414       if (spool_name)
415         {
416           /* The "0 - " is to make it a negative number if maillock returns
417              non-zero. */
418           status = 0 - maillock (spool_name, 1);
419 #ifdef HAVE_TOUCHLOCK
420           touched_lock = time (0);
421 #endif
422           lockcount = 5;
423         }
424       else
425 #endif /* MAIL_USE_MAILLOCK */
426         {
427 #ifdef MAIL_USE_SYSTEM_LOCK
428 #ifdef MAIL_USE_LOCKF
429           status = lockf (indesc, F_LOCK, 0);
430 #else /* not MAIL_USE_LOCKF */
431 #ifdef XENIX
432           status = locking (indesc, LK_RLCK, 0L);
433 #else
434 #ifdef WINDOWSNT
435           status = locking (indesc, LK_RLCK, -1L);
436 #else
437           status = flock (indesc, LOCK_EX);
438 #endif
439 #endif
440 #endif /* not MAIL_USE_LOCKF */
441 #endif /* MAIL_USE_SYSTEM_LOCK */
442         }
443
444       /* If it fails, retry up to 5 times
445          for certain failure codes.  */
446       if (status < 0)
447         {
448           if (++lockcount <= 5)
449             {
450 #ifdef EAGAIN
451               if (errno == EAGAIN)
452                 {
453                   sleep (1);
454                   goto retry_lock;
455                 }
456 #endif
457 #ifdef EBUSY
458               if (errno == EBUSY)
459                 {
460                   sleep (1);
461                   goto retry_lock;
462                 }
463 #endif
464             }
465
466           pfatal_with_name (inname);
467         }
468
469       {
470         char buf[1024];
471
472         while (1)
473           {
474             nread = read (indesc, buf, sizeof buf);
475             if (nread < 0)
476               pfatal_with_name (inname);
477             if (nread != write (outdesc, buf, nread))
478               {
479                 int saved_errno = errno;
480                 unlink (outname);
481                 errno = saved_errno;
482                 pfatal_with_name (outname);
483               }
484             if (nread < sizeof buf)
485               break;
486 #if defined (MAIL_USE_MAILLOCK) && defined (HAVE_TOUCHLOCK)
487             if (spool_name)
488               {
489                 now = time (0);
490                 if (now - touched_lock > 60)
491                   {
492                     touchlock ();
493                     touched_lock = now;
494                   }
495               }
496 #endif /* MAIL_USE_MAILLOCK */
497           }
498       }
499
500 #ifdef BSD_SYSTEM
501       if (fsync (outdesc) < 0)
502         pfatal_and_delete (outname);
503 #endif
504
505       /* Check to make sure no errors before we zap the inbox.  */
506       if (close (outdesc) != 0)
507         pfatal_and_delete (outname);
508
509 #ifdef MAIL_USE_SYSTEM_LOCK
510       if (! preserve_mail)
511         {
512 #if defined (STRIDE) || defined (XENIX)
513           /* Stride, xenix have file locking, but no ftruncate.
514              This mess will do. */
515           close (open (inname, O_CREAT | O_TRUNC | O_RDWR, 0666));
516 #else
517           ftruncate (indesc, 0L);
518 #endif /* STRIDE or XENIX */
519         }
520 #endif /* MAIL_USE_SYSTEM_LOCK */
521
522 #ifdef MAIL_USE_MMDF
523       lk_close (indesc, 0, 0, 0);
524 #else
525       close (indesc);
526 #endif
527
528 #ifndef MAIL_USE_SYSTEM_LOCK
529       if (! preserve_mail)
530         {
531           /* Delete the input file; if we can't, at least get rid of its
532              contents.  */
533 #ifdef MAIL_UNLINK_SPOOL
534           /* This is generally bad to do, because it destroys the permissions
535              that were set on the file.  Better to just empty the file.  */
536           if (unlink (inname) < 0 && errno != ENOENT)
537 #endif /* MAIL_UNLINK_SPOOL */
538             creat (inname, 0600);
539         }
540 #endif /* not MAIL_USE_SYSTEM_LOCK */
541
542 #ifdef MAIL_USE_MAILLOCK
543       /* This has to occur in the child, i.e., in the process that
544          acquired the lock! */
545       if (spool_name)
546         mailunlock ();
547 #endif
548       exit (EXIT_SUCCESS);
549     }
550
551   wait (&status);
552   if (!WIFEXITED (status))
553     exit (EXIT_FAILURE);
554   else if (WRETCODE (status) != 0)
555     exit (WRETCODE (status));
556
557 #if !defined (MAIL_USE_MMDF) && !defined (MAIL_USE_SYSTEM_LOCK)
558 #ifdef MAIL_USE_MAILLOCK
559   if (! spool_name)
560 #endif /* MAIL_USE_MAILLOCK */
561     unlink (lockname);
562 #endif /* not MAIL_USE_MMDF and not MAIL_USE_SYSTEM_LOCK */
563
564 #endif /* ! DISABLE_DIRECT_ACCESS */
565
566   return EXIT_SUCCESS;
567 }
568
569 #ifdef MAIL_USE_MAILLOCK
570 /* This function uses stat to confirm that the mail directory is
571    identical to the directory of the input file, rather than just
572    string-comparing the two paths, because one or both of them might
573    be symbolic links pointing to some other directory. */
574 static char *
575 mail_spool_name (inname)
576      char *inname;
577 {
578   struct stat stat1, stat2;
579   char *indir, *fname;
580   int status;
581
582   if (! (fname = rindex (inname, '/')))
583     return NULL;
584
585   fname++;
586
587   if (stat (MAILDIR, &stat1) < 0)
588     return NULL;
589
590   indir = (char *) xmalloc (fname - inname + 1);
591   strncpy (indir, inname, fname - inname);
592   indir[fname-inname] = '\0';
593
594
595   status = stat (indir, &stat2);
596
597   free (indir);
598
599   if (status < 0)
600     return NULL;
601
602   if (stat1.st_dev == stat2.st_dev
603       && stat1.st_ino == stat2.st_ino)
604     return fname;
605
606   return NULL;
607 }
608 #endif /* MAIL_USE_MAILLOCK */
609
610 /* Print error message and exit.  */
611
612 void
613 fatal (s1, s2, s3)
614      char *s1, *s2, *s3;
615 {
616   if (delete_lockname)
617     unlink (delete_lockname);
618   error (s1, s2, s3);
619   exit (EXIT_FAILURE);
620 }
621
622 /* Print error message.  `s1' is printf control string, `s2' and `s3'
623    are args for it or null. */
624
625 void
626 error (s1, s2, s3)
627      char *s1, *s2, *s3;
628 {
629   fprintf (stderr, "movemail: ");
630   if (s3)
631     fprintf (stderr, s1, s2, s3);
632   else if (s2)
633     fprintf (stderr, s1, s2);
634   else
635     fprintf (stderr, s1);
636   fprintf (stderr, "\n");
637 }
638
639 void
640 pfatal_with_name (name)
641      char *name;
642 {
643   fatal ("%s for %s", strerror (errno), name);
644 }
645
646 void
647 pfatal_and_delete (name)
648      char *name;
649 {
650   char *s = strerror (errno);
651   unlink (name);
652   fatal ("%s for %s", s, name);
653 }
654
655 /* Return a newly-allocated string whose contents concatenate those of s1, s2, s3.  */
656
657 char *
658 concat (s1, s2, s3)
659      char *s1, *s2, *s3;
660 {
661   int len1 = strlen (s1), len2 = strlen (s2), len3 = strlen (s3);
662   char *result = (char *) xmalloc (len1 + len2 + len3 + 1);
663
664   strcpy (result, s1);
665   strcpy (result + len1, s2);
666   strcpy (result + len1 + len2, s3);
667   *(result + len1 + len2 + len3) = 0;