* src/syntax.c (SETUP_SYNTAX_TABLE): Move truncation...
[emacs.git] / lib-src / movemail.c
blobc25db625387e5eded3813d699fbea439d481f40f
1 /* movemail foo bar -- move file foo to file bar,
2 locking file foo the way /bin/mail respects.
4 Copyright (C) 1986, 1992-1994, 1996, 1999, 2001-2015 Free Software
5 Foundation, Inc.
7 This file is part of GNU Emacs.
9 GNU Emacs is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
14 GNU Emacs is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
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/lockf 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.
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. */
36 * Modified January, 1986 by Michael R. Gretzinger (Project Athena)
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.
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
51 * Modified August, 1993 by Jonathan Kamens (OpenVision Technologies)
53 * Move all of the POP code into a separate file, "pop.c".
54 * Use strerror instead of get_errmsg.
58 #include <config.h>
59 #include <sys/types.h>
60 #include <sys/stat.h>
61 #include <sys/file.h>
62 #include <stdbool.h>
63 #include <stdio.h>
64 #include <errno.h>
65 #include <time.h>
67 #include <getopt.h>
68 #include <unistd.h>
69 #include <fcntl.h>
70 #include <signal.h>
71 #include <string.h>
72 #include "syswait.h"
73 #ifdef MAIL_USE_POP
74 #include "pop.h"
75 #endif
77 #ifdef MSDOS
78 #undef access
79 #endif /* MSDOS */
81 #ifdef WINDOWSNT
82 #include "ntlib.h"
83 #undef access
84 #undef unlink
85 #define fork() 0
86 #define waitpid(child, var, flags) (*(var) = 0)
87 /* Unfortunately, Samba doesn't seem to properly lock Unix files even
88 though the locking call succeeds (and indeed blocks local access from
89 other NT programs). If you have direct file access using an NFS
90 client or something other than Samba, the locking call might work
91 properly - make sure it does before you enable this!
93 [18-Feb-97 andrewi] I now believe my comment above to be incorrect,
94 since it was based on a misunderstanding of how locking calls are
95 implemented and used on Unix. */
96 //#define DISABLE_DIRECT_ACCESS
98 #include <fcntl.h>
99 #endif /* WINDOWSNT */
101 #ifdef WINDOWSNT
102 #include <sys/locking.h>
103 #endif
105 /* If your system uses the `flock' or `lockf' system call for mail locking,
106 define MAIL_USE_SYSTEM_LOCK. If your system type should always define
107 MAIL_USE_LOCKF or MAIL_USE_FLOCK but configure does not do this,
108 please make a bug report. */
110 #ifdef MAIL_USE_LOCKF
111 #define MAIL_USE_SYSTEM_LOCK
112 #endif
114 #ifdef MAIL_USE_FLOCK
115 #define MAIL_USE_SYSTEM_LOCK
116 #endif
118 #if (!defined MAIL_USE_SYSTEM_LOCK \
119 && (defined HAVE_LIBMAIL || defined HAVE_LIBLOCKFILE) \
120 && defined HAVE_MAILLOCK_H)
121 #include <maillock.h>
122 /* We can't use maillock unless we know what directory system mail
123 files appear in. */
124 #ifdef MAILDIR
125 #define MAIL_USE_MAILLOCK
126 static char *mail_spool_name (char *);
127 #endif
128 #endif
130 static _Noreturn void fatal (const char *s1, const char *s2, const char *s3);
131 static void error (const char *s1, const char *s2, const char *s3);
132 static _Noreturn void pfatal_with_name (char *name);
133 static _Noreturn void pfatal_and_delete (char *name);
134 #ifdef MAIL_USE_POP
135 static int popmail (char *, char *, bool, char *, bool);
136 static bool pop_retr (popserver, int, FILE *);
137 static bool mbx_write (char *, int, FILE *);
138 static bool mbx_delimit_begin (FILE *);
139 static bool mbx_delimit_end (FILE *);
140 #endif
142 #if (defined MAIL_USE_MAILLOCK \
143 || (!defined DISABLE_DIRECT_ACCESS && !defined MAIL_USE_SYSTEM_LOCK))
144 /* Like malloc but get fatal error if memory is exhausted. */
146 static void *
147 xmalloc (size_t size)
149 void *result = malloc (size);
150 if (!result)
151 fatal ("virtual memory exhausted", 0, 0);
152 return result;
154 #endif
156 /* Nonzero means this is name of a lock file to delete on fatal error. */
157 static char *delete_lockname;
160 main (int argc, char **argv)
162 char *inname, *outname;
163 int indesc, outdesc;
164 ssize_t nread;
165 int wait_status;
166 int c;
167 bool preserve_mail = false;
169 #ifndef MAIL_USE_SYSTEM_LOCK
170 struct stat st;
171 int tem;
172 char *tempname;
173 size_t inname_len, inname_dirlen;
174 int desc;
175 #endif /* not MAIL_USE_SYSTEM_LOCK */
177 #ifdef MAIL_USE_POP
178 bool pop_reverse_order = false;
179 # define ARGSTR "pr"
180 #else /* ! MAIL_USE_POP */
181 # define ARGSTR "p"
182 #endif /* MAIL_USE_POP */
184 uid_t real_gid = getgid ();
185 uid_t priv_gid = getegid ();
187 delete_lockname = 0;
189 while (0 <= (c = getopt (argc, argv, ARGSTR)))
191 switch (c) {
192 #ifdef MAIL_USE_POP
193 case 'r':
194 pop_reverse_order = true;
195 break;
196 #endif
197 case 'p':
198 preserve_mail = true;
199 break;
200 default:
201 return EXIT_FAILURE;
205 if (
206 #ifdef MAIL_USE_POP
207 (argc - optind < 2) || (argc - optind > 3)
208 #else
209 (argc - optind != 2)
210 #endif
213 #ifdef MAIL_USE_POP
214 fprintf (stderr, "Usage: movemail [-p] [-r] inbox destfile%s\n",
215 " [POP-password]");
216 #else
217 fprintf (stderr, "Usage: movemail [-p] inbox destfile%s\n", "");
218 #endif
219 return EXIT_FAILURE;
222 inname = argv[optind];
223 outname = argv[optind+1];
225 if (*outname == 0)
226 fatal ("Destination file name is empty", 0, 0);
228 #ifdef MAIL_USE_POP
229 if (!strncmp (inname, "po:", 3))
231 int status;
233 status = popmail (inname + 3, outname, preserve_mail,
234 (argc - optind == 3) ? argv[optind+2] : NULL,
235 pop_reverse_order);
236 return status;
239 if (setuid (getuid ()) < 0)
240 fatal ("Failed to drop privileges", 0, 0);
242 #endif /* MAIL_USE_POP */
244 #ifndef DISABLE_DIRECT_ACCESS
246 char *lockname = 0;
248 #ifdef MAIL_USE_MAILLOCK
249 char *spool_name = 0;
250 #endif
252 #ifndef MAIL_USE_SYSTEM_LOCK
253 #ifdef MAIL_USE_MAILLOCK
254 spool_name = mail_spool_name (inname);
255 #endif
256 if (! spool_name)
258 /* Use a lock file named after our first argument with .lock appended:
259 If it exists, the mail file is locked. */
260 /* Note: this locking mechanism is *required* by the mailer
261 (on systems which use it) to prevent loss of mail.
263 On systems that use a lock file, extracting the mail without locking
264 WILL occasionally cause loss of mail due to timing errors!
266 So, if creation of the lock file fails due to access
267 permission on the mail spool directory, you simply MUST
268 change the permission and/or make movemail a setgid program
269 so it can create lock files properly.
271 You might also wish to verify that your system is one which
272 uses lock files for this purpose. Some systems use other methods. */
274 inname_len = strlen (inname);
275 lockname = xmalloc (inname_len + sizeof ".lock");
276 strcpy (lockname, inname);
277 strcpy (lockname + inname_len, ".lock");
278 for (inname_dirlen = inname_len;
279 inname_dirlen && !IS_DIRECTORY_SEP (inname[inname_dirlen - 1]);
280 inname_dirlen--)
281 continue;
282 tempname = xmalloc (inname_dirlen + sizeof "EXXXXXX");
284 while (true)
286 /* Create the lock file, but not under the lock file name. */
287 /* Give up if cannot do that. */
289 memcpy (tempname, inname, inname_dirlen);
290 strcpy (tempname + inname_dirlen, "EXXXXXX");
291 desc = mkostemp (tempname, O_BINARY);
292 if (desc < 0)
294 int mkostemp_errno = errno;
295 error ("error while creating what would become the lock file",
296 0, 0);
297 errno = mkostemp_errno;
298 pfatal_with_name (tempname);
300 close (desc);
302 tem = link (tempname, lockname);
304 if (tem < 0 && errno != EEXIST)
305 pfatal_with_name (lockname);
307 unlink (tempname);
308 if (tem >= 0)
309 break;
310 sleep (1);
312 /* If lock file is five minutes old, unlock it.
313 Five minutes should be good enough to cope with crashes
314 and wedgitude, and long enough to avoid being fooled
315 by time differences between machines. */
316 if (stat (lockname, &st) >= 0)
318 time_t now = time (0);
319 if (st.st_ctime < now - 300)
321 unlink (lockname);
322 lockname = 0;
327 delete_lockname = lockname;
329 #endif /* not MAIL_USE_SYSTEM_LOCK */
331 #ifdef SIGCHLD
332 signal (SIGCHLD, SIG_DFL);
333 #endif
335 pid_t child = fork ();
336 if (child < 0)
337 fatal ("Error in fork; %s", strerror (errno), 0);
339 if (child == 0)
341 int lockcount = 0;
342 int status = 0;
343 #if defined (MAIL_USE_MAILLOCK) && defined (HAVE_TOUCHLOCK)
344 time_t touched_lock IF_LINT (= 0);
345 #endif
347 if (setuid (getuid ()) < 0 || setregid (-1, real_gid) < 0)
348 fatal ("Failed to drop privileges", 0, 0);
350 #ifdef MAIL_USE_SYSTEM_LOCK
351 indesc = open (inname, O_RDWR | O_BINARY);
352 #else /* if not MAIL_USE_SYSTEM_LOCK */
353 indesc = open (inname, O_RDONLY | O_BINARY);
354 #endif /* not MAIL_USE_SYSTEM_LOCK */
356 if (indesc < 0)
357 pfatal_with_name (inname);
359 /* Make sure the user can read the output file. */
360 umask (umask (0) & 0377);
362 outdesc = open (outname, O_WRONLY | O_BINARY | O_CREAT | O_EXCL, 0666);
363 if (outdesc < 0)
364 pfatal_with_name (outname);
366 if (setregid (-1, priv_gid) < 0)
367 fatal ("Failed to regain privileges", 0, 0);
369 /* This label exists so we can retry locking
370 after a delay, if it got EAGAIN or EBUSY. */
371 retry_lock:
373 /* Try to lock it. */
374 #ifdef MAIL_USE_MAILLOCK
375 if (spool_name)
377 /* The "-" is to make it a negative number if maillock returns
378 non-zero. */
379 status = - maillock (spool_name, 1);
380 #ifdef HAVE_TOUCHLOCK
381 touched_lock = time (0);
382 #endif
383 lockcount = 5;
385 else
386 #endif /* MAIL_USE_MAILLOCK */
388 #ifdef MAIL_USE_SYSTEM_LOCK
389 #ifdef MAIL_USE_LOCKF
390 status = lockf (indesc, F_LOCK, 0);
391 #else /* not MAIL_USE_LOCKF */
392 #ifdef WINDOWSNT
393 status = locking (indesc, LK_RLCK, -1L);
394 #else
395 status = flock (indesc, LOCK_EX);
396 #endif
397 #endif /* not MAIL_USE_LOCKF */
398 #endif /* MAIL_USE_SYSTEM_LOCK */
401 /* If it fails, retry up to 5 times
402 for certain failure codes. */
403 if (status < 0)
405 if (++lockcount <= 5 && (errno == EAGAIN || errno == EBUSY))
407 sleep (1);
408 goto retry_lock;
411 pfatal_with_name (inname);
415 char buf[1024];
417 while (true)
419 nread = read (indesc, buf, sizeof buf);
420 if (nread < 0)
421 pfatal_with_name (inname);
422 if (nread != write (outdesc, buf, nread))
424 int saved_errno = errno;
425 unlink (outname);
426 errno = saved_errno;
427 pfatal_with_name (outname);
429 if (nread < sizeof buf)
430 break;
431 #if defined (MAIL_USE_MAILLOCK) && defined (HAVE_TOUCHLOCK)
432 if (spool_name)
434 time_t now = time (0);
435 if (now - touched_lock > 60)
437 touchlock ();
438 touched_lock = now;
441 #endif /* MAIL_USE_MAILLOCK */
445 if (fsync (outdesc) != 0 && errno != EINVAL)
446 pfatal_and_delete (outname);
448 /* Prevent symlink attacks truncating other users' mailboxes */
449 if (setregid (-1, real_gid) < 0)
450 fatal ("Failed to drop privileges", 0, 0);
452 /* Check to make sure no errors before we zap the inbox. */
453 if (close (outdesc) != 0)
454 pfatal_and_delete (outname);
456 #ifdef MAIL_USE_SYSTEM_LOCK
457 if (! preserve_mail)
459 if (ftruncate (indesc, 0) != 0)
460 pfatal_with_name (inname);
462 #endif /* MAIL_USE_SYSTEM_LOCK */
464 close (indesc);
466 #ifndef MAIL_USE_SYSTEM_LOCK
467 if (! preserve_mail)
469 /* Delete the input file; if we can't, at least get rid of its
470 contents. */
471 #ifdef MAIL_UNLINK_SPOOL
472 /* This is generally bad to do, because it destroys the permissions
473 that were set on the file. Better to just empty the file. */
474 if (unlink (inname) < 0 && errno != ENOENT)
475 #endif /* MAIL_UNLINK_SPOOL */
476 creat (inname, 0600);
478 #endif /* not MAIL_USE_SYSTEM_LOCK */
480 /* End of mailbox truncation */
481 if (setregid (-1, priv_gid) < 0)
482 fatal ("Failed to regain privileges", 0, 0);
484 #ifdef MAIL_USE_MAILLOCK
485 /* This has to occur in the child, i.e., in the process that
486 acquired the lock! */
487 if (spool_name)
488 mailunlock ();
489 #endif
490 return EXIT_SUCCESS;
493 if (waitpid (child, &wait_status, 0) < 0)
494 fatal ("Error in waitpid; %s", strerror (errno), 0);
495 if (!WIFEXITED (wait_status))
496 return EXIT_FAILURE;
497 else if (WEXITSTATUS (wait_status) != 0)
498 return WEXITSTATUS (wait_status);
500 if (lockname)
501 unlink (lockname);
503 #endif /* ! DISABLE_DIRECT_ACCESS */
505 return EXIT_SUCCESS;
508 #ifdef MAIL_USE_MAILLOCK
509 /* This function uses stat to confirm that the mail directory is
510 identical to the directory of the input file, rather than just
511 string-comparing the two paths, because one or both of them might
512 be symbolic links pointing to some other directory. */
513 static char *
514 mail_spool_name (char *inname)
516 struct stat stat1, stat2;
517 char *indir, *fname;
518 int status;
520 if (! (fname = strrchr (inname, '/')))
521 return NULL;
523 fname++;
525 if (stat (MAILDIR, &stat1) < 0)
526 return NULL;
528 indir = xmalloc (fname - inname + 1);
529 memcpy (indir, inname, fname - inname);
530 indir[fname-inname] = '\0';
533 status = stat (indir, &stat2);
535 free (indir);
537 if (status < 0)
538 return NULL;
540 if (stat1.st_dev == stat2.st_dev
541 && stat1.st_ino == stat2.st_ino)
542 return fname;
544 return NULL;
546 #endif /* MAIL_USE_MAILLOCK */
548 /* Print error message and exit. */
550 static void
551 fatal (const char *s1, const char *s2, const char *s3)
553 if (delete_lockname)
554 unlink (delete_lockname);
555 error (s1, s2, s3);
556 exit (EXIT_FAILURE);
559 /* Print error message. `s1' is printf control string, `s2' and `s3'
560 are args for it or null. */
562 static void
563 error (const char *s1, const char *s2, const char *s3)
565 fprintf (stderr, "movemail: ");
566 if (s3)
567 fprintf (stderr, s1, s2, s3);
568 else if (s2)
569 fprintf (stderr, s1, s2);
570 else
571 fprintf (stderr, "%s", s1);
572 fprintf (stderr, "\n");
575 static void
576 pfatal_with_name (char *name)
578 fatal ("%s for %s", strerror (errno), name);
581 static void
582 pfatal_and_delete (char *name)
584 char *s = strerror (errno);
585 unlink (name);
586 fatal ("%s for %s", s, name);
589 /* This is the guts of the interface to the Post Office Protocol. */
591 #ifdef MAIL_USE_POP
593 #ifndef WINDOWSNT
594 #include <sys/socket.h>
595 #include <netinet/in.h>
596 #include <netdb.h>
597 #else
598 #undef _WINSOCKAPI_
599 #include <winsock.h>
600 #endif
601 #include <pwd.h>
602 #include <string.h>
605 * The full valid syntax for a POP mailbox specification for movemail
606 * is "po:username:hostname". The ":hostname" is optional; if it is
607 * omitted, the MAILHOST environment variable will be consulted. Note
608 * that by the time popmail() is called the "po:" has been stripped
609 * off of the front of the mailbox name.
611 * If the mailbox is in the form "po:username:hostname", then it is
612 * modified by this function -- the second colon is replaced by a
613 * null.
615 * Return a value suitable for passing to `exit'.
618 static int
619 popmail (char *mailbox, char *outfile, bool preserve, char *password,
620 bool reverse_order)
622 int nmsgs, nbytes;
623 int i;
624 int mbfi;
625 FILE *mbf;
626 popserver server;
627 int start, end, increment;
628 char *user, *hostname;
630 user = mailbox;
631 if ((hostname = strchr (mailbox, ':')))
632 *hostname++ = '\0';
634 server = pop_open (hostname, user, password, POP_NO_GETPASS);
635 if (! server)
637 error ("Error connecting to POP server: %s", pop_error, 0);
638 return EXIT_FAILURE;
641 if (pop_stat (server, &nmsgs, &nbytes))
643 error ("Error getting message count from POP server: %s", pop_error, 0);
644 return EXIT_FAILURE;
647 if (!nmsgs)
649 pop_close (server);
650 return EXIT_SUCCESS;
653 mbfi = open (outfile, O_WRONLY | O_BINARY | O_CREAT | O_EXCL, 0666);
654 if (mbfi < 0)
656 pop_close (server);
657 error ("Error in open: %s, %s", strerror (errno), outfile);
658 return EXIT_FAILURE;
661 if (fchown (mbfi, getuid (), -1) != 0)
663 int fchown_errno = errno;
664 struct stat st;
665 if (fstat (mbfi, &st) != 0 || st.st_uid != getuid ())
667 pop_close (server);
668 error ("Error in fchown: %s, %s", strerror (fchown_errno), outfile);
669 return EXIT_FAILURE;
673 mbf = fdopen (mbfi, "wb");
674 if (!mbf)
676 pop_close (server);
677 error ("Error in fdopen: %s", strerror (errno), 0);
678 close (mbfi);
679 unlink (outfile);
680 return EXIT_FAILURE;
683 if (reverse_order)
685 start = nmsgs;
686 end = 1;
687 increment = -1;
689 else
691 start = 1;
692 end = nmsgs;
693 increment = 1;
696 for (i = start; i * increment <= end * increment; i += increment)
697 if (! (mbx_delimit_begin (mbf)
698 && pop_retr (server, i, mbf)
699 && mbx_delimit_end (mbf)
700 && fflush (mbf) == 0))
702 if (errno)
703 error ("Error in POP retrieving: %s", strerror (errno), 0);
704 pop_close (server);
705 fclose (mbf);
706 return EXIT_FAILURE;
709 if (fsync (mbfi) != 0 && errno != EINVAL)
711 error ("Error in fsync: %s", strerror (errno), 0);
712 fclose (mbf);
713 return EXIT_FAILURE;
716 if (fclose (mbf) != 0)
718 error ("Error in fclose: %s", strerror (errno), 0);
719 return EXIT_FAILURE;
722 if (! preserve)
723 for (i = 1; i <= nmsgs; i++)
725 if (pop_delete (server, i))
727 error ("Error from POP server: %s", pop_error, 0);
728 pop_close (server);
729 return EXIT_FAILURE;
733 if (pop_quit (server))
735 error ("Error from POP server: %s", pop_error, 0);
736 return EXIT_FAILURE;
739 return EXIT_SUCCESS;
742 static bool
743 pop_retr (popserver server, int msgno, FILE *arg)
745 char *line;
746 int ret;
748 if (pop_retrieve_first (server, msgno, &line))
750 error ("Error from POP server: %s", pop_error, 0);
751 errno = 0;
752 return false;
755 while ((ret = pop_retrieve_next (server, &line)) >= 0)
757 if (! line)
758 break;
760 if (! mbx_write (line, ret, arg))
762 int write_errno = errno;
763 pop_close (server);
764 errno = write_errno;
765 return false;
769 if (ret)
771 error ("Error from POP server: %s", pop_error, 0);
772 errno = 0;
773 return false;
776 return true;
779 static bool
780 mbx_write (char *line, int len, FILE *mbf)
782 #ifdef MOVEMAIL_QUOTE_POP_FROM_LINES
783 /* Do this as a macro instead of using strcmp to save on execution time. */
784 # define IS_FROM_LINE(a) ((a[0] == 'F') \
785 && (a[1] == 'r') \
786 && (a[2] == 'o') \
787 && (a[3] == 'm') \
788 && (a[4] == ' '))
789 if (IS_FROM_LINE (line))
791 if (fputc ('>', mbf) < 0)
792 return false;
794 #endif
795 if (line[0] == '\037')
797 if (fputs ("^_", mbf) < 0)
798 return false;
799 line++;
800 len--;
802 return fwrite (line, 1, len, mbf) == len && 0 <= fputc ('\n', mbf);
805 static bool
806 mbx_delimit_begin (FILE *mbf)
808 time_t now = time (NULL);
809 struct tm *ltime = localtime (&now);
810 if (!ltime)
811 return false;
813 char fromline[100];
814 if (! strftime (fromline, sizeof fromline,
815 "From movemail %a %b %e %T %Y\n", ltime))
817 errno = EOVERFLOW;
818 return false;
820 return 0 <= fputs (fromline, mbf);
823 static bool
824 mbx_delimit_end (FILE *mbf)
826 return 0 <= putc ('\n', mbf);
829 #endif /* MAIL_USE_POP */