home *** CD-ROM | disk | FTP | other *** search
/ ftp.uv.es / 2014.11.ftp.uv.es.tar / ftp.uv.es / pub / unix / aix-rs6000 / elm2.3.11.AIX3.1.5.Z / elm2.3.11.AIX3.1.5 / src / leavembox.c < prev    next >
C/C++ Source or Header  |  1991-11-26  |  30KB  |  991 lines

  1.  
  2. static char rcsid[] = "@(#)$Id: leavembox.c,v 4.1.1.6 90/12/06 13:38:55 syd Exp $";
  3.  
  4. /*******************************************************************************
  5.  *  The Elm Mail System  -  $Revision: 4.1.1.6 $   $State: Exp $
  6.  *
  7.  *             Copyright (c) 1986, 1987 Dave Taylor
  8.  *             Copyright (c) 1988, 1989, 1990 USENET Community Trust
  9.  *******************************************************************************
  10.  * Bug reports, patches, comments, suggestions should be sent to:
  11.  *
  12.  *    Syd Weinstein, Elm Coordinator
  13.  *    elm@DSI.COM            dsinc!elm
  14.  *
  15.  *******************************************************************************
  16.  * $Log:    leavembox.c,v $
  17.  * Revision 4.1.1.6  90/12/06  13:38:55  syd
  18.  * disable stop signal around writeback to avoid corrupted file
  19.  * From: Syd via report from Tom Davis <tdd@endure.cl.msu.edu>
  20.  * 
  21.  * Revision 4.1.1.5  90/10/10  12:49:46  syd
  22.  * Fix calling sequence to copy_message calls for
  23.  * new MMDF argument
  24.  * From: Syd
  25.  * 
  26.  * Revision 4.1.1.4  90/08/15  21:00:07  syd
  27.  * Change elm to not delete empty folders on a resync
  28.  * From: Syd
  29.  * 
  30.  * Revision 4.1.1.3  90/06/21  22:51:52  syd
  31.  * Add time.h to includes as some OSs include needed substructure only
  32.  * from time.h
  33.  * From: Syd
  34.  * 
  35.  * Revision 4.1.1.2  90/06/21  22:48:14  syd
  36.  * patch to fix up the Log headers.
  37.  * From: pdc%lunch.wpd@sgi.com (Paul Close)
  38.  * 
  39.  * Revision 4.1.1.1  90/06/09  21:33:23  syd
  40.  * Some flock()s refuse to exclusively lock a fd open for read-only access.
  41.  * From: pdc%lunch.wpd@sgi.com (Paul Close)
  42.  * 
  43.  * Revision 4.1  90/04/28  22:43:18  syd
  44.  * checkin of Elm 2.3 as of Release PL0
  45.  * 
  46.  *
  47.  ******************************************************************************/
  48.  
  49. /** leave current folder, updating etc. as needed...
  50.   
  51. **/
  52.  
  53. #include "headers.h"
  54. #include <sys/types.h>
  55. #include <sys/stat.h>
  56. #ifdef LOCK_BY_FLOCK
  57. #include <sys/file.h>
  58. #endif
  59. #include <errno.h>
  60. #ifdef I_TIME
  61. #  include <time.h>
  62. #endif
  63. #ifdef I_SYSTIME
  64. #  include <sys/time.h>
  65. #endif
  66.  
  67.  
  68. /**********
  69.    Since a number of machines don't seem to bother to define the utimbuf
  70.    structure for some *very* obscure reason.... 
  71.  
  72.    Suprise, though, BSD has a different utime() entirely...*sigh*
  73. **********/
  74.  
  75. #ifndef BSD
  76. # ifdef NOUTIMBUF
  77.  
  78. struct utimbuf {
  79.     time_t    actime;        /** access time       **/ 
  80.     time_t    modtime;    /** modification time **/
  81.        };
  82.  
  83.  
  84. # endif /* NOUTIMBUF */
  85. #endif /* BSD */
  86.  
  87. extern int errno;
  88.  
  89. char *error_name(), *error_description(),/* *strcpy(),*/ *rindex();
  90. unsigned short getegid();
  91. #ifndef    _POSIX_SOURCE
  92. unsigned long sleep();
  93. #endif
  94.  
  95. int
  96. leave_mbox(resyncing, quitting, prompt)
  97. int resyncing, quitting, prompt;
  98. {
  99.     /** Close folder, deleting some messages, storing others in mbox,
  100.         and keeping others, as directed by user input and elmrc options.
  101.  
  102.         Return    1    Folder altered
  103.             0    Folder not altered
  104.             -1    New mail arrived during the process and
  105.                     closing was aborted.
  106.         If "resyncing" we are just writing out folder to reopen it. We
  107.         therefore only consider deletes and keeps, not stores to mbox.
  108.         Also we don't remove NEW status so that it can be preserved
  109.         across the resync.
  110.  
  111.         If "quitting" and "prompt" is false, then no prompting is done.
  112.         Otherwise prompting is dependent upon the variable
  113.         question_me, as set by an elmrc option.  This behavior makes
  114.         the 'q' command prompt just like 'c' and '$', while
  115.         retaining the 'Q' command for a quick exit that never
  116.         prompts.
  117.     **/
  118.  
  119.     FILE *temp;
  120.     char temp_keep_file[SLEN], buffer[SLEN];
  121.     struct stat    buf;        /* stat command  */
  122. #ifdef BSD
  123.     time_t utime_buffer[2];        /* utime command */
  124. #else
  125.     struct utimbuf utime_buffer;    /* utime command */
  126. #endif
  127. #ifdef VOIDSIG
  128.     void    (*oldstop)();
  129. #else
  130.     int    (*oldstop)();
  131. #endif
  132.     register int to_delete = 0, to_store = 0, to_keep = 0, i,
  133.              marked_deleted, marked_read, marked_unread,
  134.              last_sortby, ask_questions,  asked_storage_q,
  135.              num_chgd_status, need_to_copy;
  136.     char answer;
  137.     long bytes();
  138.  
  139.     dprint(1, (debugfile, "\n\n-- leaving folder --\n\n"));
  140.  
  141.     if (message_count == 0)
  142.       return(0);    /* nothing changed */
  143.  
  144.     ask_questions = ((quitting && !prompt) ? FALSE : question_me);
  145.  
  146.     /* YES or NO on softkeys */
  147.     if (hp_softkeys && ask_questions) {
  148.       define_softkeys(YESNO);
  149.       softkeys_on();
  150.     }
  151.  
  152.     /* Clear the exit dispositions of all messages, just in case
  153.      * they were left set by a previous call to this function
  154.      * that was interrupted by the receipt of new mail.
  155.      */
  156.     for(i = 0; i < message_count; i++)
  157.       headers[i]->exit_disposition = UNSET;
  158.       
  159.     /* Determine if deleted messages are really to be deleted */
  160.  
  161.     /* we need to know if there are none, or one, or more to delete */
  162.     for (marked_deleted=0, i=0; i<message_count && marked_deleted<2; i++)
  163.       if (ison(headers[i]->status, DELETED))
  164.         marked_deleted++;
  165.  
  166.         if(marked_deleted) {
  167.       answer = (always_del ? 'y' : 'n');    /* default answer */
  168.       if(ask_questions) {
  169.         sprintf(buffer, "Delete message%s? (y/n) ", plural(marked_deleted));
  170.         answer = want_to(buffer, answer);
  171.       }
  172.  
  173.       if(answer == 'y') {
  174.         for (i = 0; i < message_count; i++) {
  175.           if (ison(headers[i]->status, DELETED)) {
  176.         headers[i]->exit_disposition = DELETE;
  177.         to_delete++;
  178.           }
  179.         }
  180.       }
  181.     }
  182.     dprint(3, (debugfile, "Messages to delete: %d\n", to_delete));
  183.  
  184.     /* If this is a non spool file, or if we are merely resyncing,
  185.      * all messages with an unset disposition (i.e. not slated for
  186.      * deletion) are to be kept.
  187.      * Otherwise, we need to determine if read and unread messages
  188.      * are to be stored or kept.
  189.      */
  190.     if(folder_type == NON_SPOOL || resyncing) {
  191.       to_store = 0;
  192.       for (i = 0; i < message_count; i++) {
  193.         if(headers[i]->exit_disposition == UNSET) {
  194.           headers[i]->exit_disposition = KEEP;
  195.           to_keep++;
  196.         }
  197.       }
  198.     } else {
  199.  
  200.       /* Let's first see if user wants to store read messages 
  201.        * that aren't slated for deletion */
  202.  
  203.       asked_storage_q = FALSE;
  204.  
  205.       /* we need to know if there are none, or one, or more marked read */
  206.       for (marked_read=0, i=0; i < message_count && marked_read < 2; i++) {
  207.         if((isoff(headers[i]->status, UNREAD))
  208.           && (headers[i]->exit_disposition == UNSET))
  209.         marked_read++;
  210.       }
  211.       if(marked_read) {
  212.         answer = (always_store ? 'y' : 'n');    /* default answer */
  213.         if(ask_questions) {
  214.           sprintf(buffer, "Move read message%s to \"received\" folder? (y/n) ",
  215.             plural(marked_read));
  216.           answer = want_to(buffer, answer);
  217.           asked_storage_q = TRUE;
  218.         }
  219.  
  220.         for (i = 0; i < message_count; i++) {
  221.           if((isoff(headers[i]->status, UNREAD)) 
  222.         && (headers[i]->exit_disposition == UNSET)) {
  223.  
  224.           if(answer == 'y') {
  225.             headers[i]->exit_disposition = STORE;
  226.             to_store++;
  227.           } else {
  228.             headers[i]->exit_disposition = KEEP;
  229.             to_keep++;
  230.           }
  231.           }
  232.         } 
  233.       }
  234.  
  235.       /* If we asked the user if read messages should be stored,
  236.        * and if the user wanted them kept instead, then certainly the
  237.        * user would want the unread messages kept as well.
  238.        */
  239.       if(asked_storage_q && answer == 'n') {
  240.  
  241.         for (i = 0; i < message_count; i++) {
  242.           if((ison(headers[i]->status, UNREAD))
  243.         && (headers[i]->exit_disposition == UNSET)) {
  244.           headers[i]->exit_disposition = KEEP;
  245.           to_keep++;
  246.           }
  247.         }
  248.  
  249.       } else {
  250.  
  251.         /* Determine if unread messages are to be kept */
  252.  
  253.         /* we need to know if there are none, or one, or more unread */
  254.         for (marked_unread=0, i=0; i<message_count && marked_unread<2; i++)
  255.           if((ison(headers[i]->status, UNREAD))
  256.         && (headers[i]->exit_disposition == UNSET))
  257.           marked_unread++;
  258.  
  259.         if(marked_unread) {
  260.           answer = (always_keep ? 'y' : 'n');    /* default answer */
  261.           if(ask_questions) {
  262.         sprintf(buffer,
  263.           "Keep unread message%s in incoming mailbox? (y/n) ",
  264.           plural(marked_unread));
  265.         answer = want_to(buffer, answer);
  266.           }
  267.  
  268.           for (i = 0; i < message_count; i++) {
  269.         if((ison(headers[i]->status, UNREAD))
  270.           && (headers[i]->exit_disposition == UNSET)) {
  271.  
  272.             if(answer == 'n') {
  273.               headers[i]->exit_disposition = STORE;
  274.               to_store++;
  275.             } else {
  276.               headers[i]->exit_disposition = KEEP;
  277.               to_keep++;
  278.             }
  279.           
  280.         }
  281.           }
  282.         }
  283.       }
  284.     }
  285.  
  286.     dprint(3, (debugfile, "Messages to store: %d\n", to_store));
  287.     dprint(3, (debugfile, "Messages to keep: %d\n", to_keep));
  288.  
  289.     if(to_delete + to_store + to_keep != message_count) {
  290.       dprint(1, (debugfile,
  291.       "Error: %d to delete + %d to store + %d to keep != %d message cnt\n",
  292.         to_delete, to_store, to_keep, message_count));
  293.       error("Something wrong in message counts! Folder unchanged.");
  294.       emergency_exit();
  295.     }
  296.       
  297.  
  298.     /* If we are not resyncing, we are leaving the mailfile and
  299.      * the new messages are new no longer. Note that this changes
  300.      * their status.
  301.      */
  302.     if(!resyncing) {
  303.       for (i = 0; i < message_count; i++) {
  304.         if (ison(headers[i]->status, NEW)) {
  305.           clearit(headers[i]->status, NEW);
  306.           headers[i]->status_chgd = TRUE;
  307.         }
  308.       }
  309.     }
  310.  
  311.     /* If all messages are to be kept and none have changed status
  312.      * we don't need to do anything because the current folder won't
  313.      * be changed by our writing it out - unless we are resyncing, in
  314.      * which case we force the writing out of the mailfile.
  315.      */
  316.  
  317.     for (num_chgd_status = 0, i = 0; i < message_count; i++)
  318.       if(headers[i]->status_chgd == TRUE)
  319.         num_chgd_status++;
  320.     
  321.     if(!to_delete && !to_store && !num_chgd_status && !resyncing) {
  322.       dprint(3, (debugfile, "Folder keep as is!\n"));
  323.       error("Folder unchanged.");
  324.       return(0);
  325.     }
  326.  
  327.     /** we have to check to see what the sorting order was...so that
  328.         the order in which we write messages is the same as the order
  329.         of the messages originally.
  330.         We only need to do this if there are any messages to be
  331.         written out (either to keep or to store). **/
  332.  
  333.     if ((to_keep || to_store ) && sortby != MAILBOX_ORDER) {
  334.       last_sortby = sortby;
  335.       sortby = MAILBOX_ORDER;
  336.       sort_mailbox(message_count, FALSE);
  337.       sortby = last_sortby;
  338.     }
  339.  
  340.     /* Formulate message as to number of keeps, stores, and deletes.
  341.      * This is only complex so that the message is good English.
  342.      */
  343.     if (to_keep > 0) {
  344.       if (to_store > 0) {
  345.         if (to_delete > 0)
  346.           sprintf(buffer,
  347.                 "[Keeping %d message%s, storing %d, and deleting %d.]", 
  348.             to_keep, plural(to_keep), to_store, to_delete);
  349.         else
  350.           sprintf(buffer, "[Keeping %d message%s and storing %d.]", 
  351.             to_keep, plural(to_keep), to_store);
  352.       } else {
  353.         if (to_delete > 0)
  354.           sprintf(buffer, "[Keeping %d message%s and deleting %d.]", 
  355.             to_keep, plural(to_keep), to_delete);
  356.         else
  357.           sprintf(buffer, "[Keeping %s.]",
  358.             to_keep > 1 ? "all messages" : "message");
  359.       }
  360.     } else if (to_store > 0) {
  361.       if (to_delete > 0)
  362.         sprintf(buffer, "[Storing %d message%s and deleting %d.]", 
  363.           to_store, plural(to_store), to_delete);
  364.       else 
  365.         sprintf(buffer, "[Storing %s.]",
  366.           to_store > 1? "all messages" : "message");
  367.  
  368.     } else {
  369.       if (to_delete > 0)
  370.         sprintf(buffer, "[Deleting all messages.]");
  371.       else
  372.         buffer[0] = '\0';
  373.     }
  374.     /* NOTE: don't use variable "buffer" till message is output later */
  375.  
  376.     /** next, let's lock the file up and make one last size check **/
  377.  
  378.     if (folder_type == SPOOL)
  379.       lock(OUTGOING);
  380.     
  381.     if (mailfile_size != bytes(cur_folder)) {
  382.       unlock();
  383.       error("New mail has just arrived. Resynchronizing...");
  384.       return(-1);
  385.     }
  386.     
  387.     /* Everything's GO - so ouput that user message and go to it. */
  388.  
  389. #ifdef SIGTSTP
  390.     oldstop = signal(SIGTSTP, SIGIGN);
  391. #endif
  392.     
  393.     dprint(2, (debugfile, "Action: %s\n", buffer));
  394.     error(buffer);
  395.  
  396.     /* Store messages slated for storage in received mail folder */
  397.     if (to_store > 0) {
  398.       if ((errno = can_open(recvd_mail, "a"))) {
  399.         error1(
  400.           "Permission to append to %s denied!  Leaving folder intact.\n",
  401.           recvd_mail);
  402.         dprint(1, (debugfile,
  403.           "Error: Permission to append to folder %s denied!! (%s)\n",
  404.           recvd_mail, "leavembox"));
  405.         dprint(1, (debugfile, "** %s - %s **\n", error_name(errno),
  406.           error_description(errno)));
  407.         unlock();
  408. #ifdef SIGTSTP
  409.         signal(SIGTSTP, oldstop);
  410. #endif
  411.         return(0);
  412.       }
  413.       if ((temp = fopen(recvd_mail,"a")) == NULL) {
  414.         unlock();
  415.         dprint(1, (debugfile, "Error: could not append to file %s\n", 
  416.           recvd_mail));
  417.         dprint(1, (debugfile, "** %s - %s **\n", error_name(errno),
  418.           error_description(errno)));
  419.         sprintf(buffer, "Could not append to folder %s!", recvd_mail);
  420.         Centerline(LINES-1, buffer);
  421.         emergency_exit();
  422.       }
  423.       dprint(2, (debugfile, "Storing message%s ", plural(to_store)));
  424.       for (i = 0; i < message_count; i++) {
  425.         if(headers[i]->exit_disposition == STORE) {
  426.           current = i+1;
  427.           dprint(2, (debugfile, "#%d, ", current));
  428.           copy_message("", temp, FALSE, FALSE, TRUE, FALSE, FALSE);
  429.         }
  430.       }
  431.       fclose(temp);
  432.       dprint(2, (debugfile, "\n\n"));
  433.       chown(recvd_mail, userid, groupid);
  434.     }
  435.  
  436.     /* If there are any messages to keep, first copy them to a
  437.      * temp file, then remove original and copy whole temp file over.
  438.      */
  439.     if (to_keep > 0) {
  440.       sprintf(temp_keep_file, "%s%s%d", temp_dir, temp_file, getpid());
  441.       if ((errno = can_open(temp_keep_file, "w"))) {
  442.         error1(
  443. "Permission to create temp file %s for writing denied! Leaving folder intact.",
  444.           temp_keep_file);
  445.         dprint(1, (debugfile,
  446.           "Error: Permission to create temp file %s denied!! (%s)\n",
  447.           temp_keep_file, "leavembox"));
  448.         dprint(1, (debugfile, "** %s - %s **\n", error_name(errno),
  449.           error_description(errno)));
  450.         unlock();
  451. #ifdef SIGTSTP
  452.         signal(SIGTSTP, oldstop);
  453. #endif
  454.         return(0);
  455.       }
  456.       if ((temp = fopen(temp_keep_file,"w")) == NULL) {
  457.         unlock();
  458.         dprint(1, (debugfile, "Error: could not create file %s\n", 
  459.           temp_keep_file));
  460.         dprint(1, (debugfile, "** %s - %s **\n", error_name(errno),
  461.           error_description(errno)));
  462.         sprintf(buffer, "Could not create temp file %s!", temp_keep_file);
  463.         Centerline(LINES-1, buffer);
  464.         emergency_exit();
  465.       }
  466.       dprint(2, (debugfile, "Copying to temp file message%s to be kept ",
  467.         plural(to_keep)));
  468.       for (i = 0; i < message_count; i++) {
  469.         if(headers[i]->exit_disposition == KEEP) {
  470.           current = i+1;
  471.           dprint(2, (debugfile, "#%d, ", current));
  472.           copy_message("", temp, FALSE, FALSE, TRUE, FALSE, FALSE);
  473.         }
  474.       }
  475.       if ( fclose(temp) == EOF ) {
  476.         Write_to_screen("\n\rClose failed on temp keep file in leavembox\n\r", 0);
  477.         perror(temp_keep_file);
  478.         dprint(2, (debugfile, "\n\rfclose err on temp_keep_file - leavembox\n\r"));
  479.         rm_temps_exit();
  480.       }
  481.       dprint(2, (debugfile, "\n\n"));
  482.  
  483.     } else if (folder_type == NON_SPOOL && !keep_empty_files && !resyncing) {
  484.  
  485.       /* i.e. if no messages were to be kept and this is not a spool
  486.        * folder and we aren't keeping empty non-spool folders,
  487.        * simply remove the old original folder and that's it!
  488.        */
  489.       (void)unlink(cur_folder);
  490. #ifdef SIGTSTP
  491.       signal(SIGTSTP, oldstop);
  492. #endif
  493.       return(1);
  494.     }
  495.  
  496.     /* Otherwise we have some work left to do! */
  497.  
  498.     /* Get original permissions and access time of the original
  499.      * mail folder before we remove it.
  500.      */
  501.     if(save_file_stats(cur_folder) != 0) {
  502.       error1("Problems saving permissions of folder %s!", cur_folder);
  503.       sleep(2);
  504.     }
  505.       
  506.         if (stat(cur_folder, &buf) != 0) {
  507.       dprint(1, (debugfile, "Error: errno %s attempting to stat file %s\n", 
  508.              error_name(errno), cur_folder));
  509.           error3("Error %s (%s) on stat(%s).", error_name(errno), 
  510.         error_description(errno), cur_folder);
  511.     }
  512.  
  513.     /* Close and remove the original folder.
  514.      * However, if we are going to copy a temp file of kept messages
  515.      * to it, and this is a locked (spool) mailbox, we need to keep
  516.      * it locked during this process. Unfortunately,
  517.      * if we did our LOCK_BY_FLOCK, unlinking the original will kill the
  518.      * lock, so we have to resort to copying the temp file to the original
  519.      * file while keeping the original open.
  520.      * Also, if the file has a link count > 1, then it has links, so to
  521.      * prevent destroying the links, we do a copy back, even though its
  522.      * slower.
  523.      */
  524.  
  525.     fclose(mailfile);
  526.  
  527.     if(to_keep) {
  528. #ifdef LOCK_BY_FLOCK
  529.       need_to_copy = (folder_type == SPOOL ? TRUE : FALSE);
  530. #else
  531.       need_to_copy = FALSE;
  532. #endif
  533.       if (buf.st_nlink > 1)
  534.         need_to_copy = TRUE;
  535.  
  536.       if(!need_to_copy) {
  537.         unlink(cur_folder);
  538.         if (link(temp_keep_file, cur_folder) != 0) {
  539.           if(errno == EXDEV || errno == EEXIST) {
  540.         /* oops - can't link across file systems - use copy instead */
  541.         need_to_copy = TRUE;
  542.           } else {
  543.         dprint(1, (debugfile, "link(%s, %s) failed (leavembox)\n", 
  544.                temp_keep_file, cur_folder));
  545.         dprint(1, (debugfile, "** %s - %s **\n", error_name(errno),
  546.               error_description(errno)));
  547.         error2("Link failed! %s - %s.", error_name(errno),
  548.           error_description(errno));
  549.         unlock();
  550.         emergency_exit();
  551.           }
  552.         }
  553.       }
  554.  
  555.       if(need_to_copy) {
  556.  
  557.         if (copy(temp_keep_file, cur_folder) != 0) {
  558.  
  559.           /* copy to cur_folder failed - try to copy to special file */
  560.           dprint(1, (debugfile, "leavembox: copy(%s, %s) failed;",
  561.               temp_keep_file, cur_folder));
  562.           dprint(1, (debugfile, "** %s - %s **\n", error_name(errno),
  563.            error_description(errno)));
  564.           error("Couldn't modify folder!");
  565.           sleep(1);
  566.           sprintf(cur_folder,"%s/%s", home, unedited_mail);
  567.           if (copy(temp_keep_file, cur_folder) != 0) {
  568.  
  569.         /* couldn't copy to special file either */
  570.         dprint(1, (debugfile, 
  571.             "leavembox: couldn't copy to %s either!!  Help;", 
  572.             cur_folder));
  573.         dprint(1, (debugfile, "** %s - %s **\n", error_name(errno),
  574.             error_description(errno)));
  575.         error("Can't copy mailbox, system trouble!!!");
  576.         unlock();
  577.         emergency_exit();
  578.           } else {
  579.         dprint(1, (debugfile,
  580.             "\nWoah! Confused - Saved mail in %s (leavembox)\n", 
  581.             cur_folder));
  582.         error1("Saved mail in %s.", cur_folder);
  583.         sleep(1);
  584.           }
  585.         }
  586.       }
  587.  
  588.       /* link or copy complete - remove temp keep file */
  589.       unlink(temp_keep_file);
  590.  
  591.     } else if(folder_type == SPOOL || keep_empty_files || resyncing) {
  592.  
  593.       /* if this is an empty spool file, or if this is an empty non spool 
  594.        * file and we keep empty non spool files (we always keep empty
  595.        * spool files), create an empty file */
  596.  
  597.       if(folder_type == NON_SPOOL)
  598.         error1("Keeping empty folder '%s'.", cur_folder);
  599.       temp = fopen(cur_folder, "w");
  600.       fclose(temp);
  601.     }
  602.  
  603.     /* restore permissions and access times of folder */
  604.  
  605.     if(restore_file_stats(cur_folder) != 1) {
  606.       error1("Problems restoring permissions of folder %s!", cur_folder);
  607.       sleep(2);
  608.     }
  609.  
  610. #ifdef BSD
  611.     utime_buffer[0]     = buf.st_atime;
  612.     utime_buffer[1]     = buf.st_mtime;
  613. #else
  614.     utime_buffer.actime = buf.st_atime;
  615.     utime_buffer.modtime= buf.st_mtime;
  616. #endif
  617.  
  618. #ifdef BSD
  619.     if (utime(cur_folder, utime_buffer) != 0) {
  620. #else
  621.     if (utime(cur_folder, &utime_buffer) != 0) {
  622. #endif
  623.       dprint(1, (debugfile, 
  624.          "Error: encountered error doing utime (leavmbox)\n"));
  625.       dprint(1, (debugfile, "** %s - %s **\n", error_name(errno), 
  626.            error_description(errno)));
  627.       error2("Error %s trying to change file %s access time.", 
  628.            error_name(errno), cur_folder);
  629.     }
  630.  
  631.  
  632.     mailfile_size = bytes(cur_folder);
  633.     unlock();    /* remove the lock on the file ASAP! */
  634.  
  635. #ifdef SIGTSTP
  636.     signal(SIGTSTP, oldstop);
  637. #endif
  638.     return(1);    
  639. }
  640.  
  641. static int  lock_state = OFF;
  642.  
  643. static char lock_name[SLEN];
  644.  
  645. char *
  646. mk_lockname(file_to_lock)
  647. char *file_to_lock;
  648. {
  649.     /** Create the proper name of the lock file for file_to_lock,
  650.         which is presumed to be a spool file full path (see
  651.         get_folder_type()), and put it in the static area lock_name.
  652.         Return lock_name for informational purposes.
  653.      **/
  654.  
  655. #ifdef XENIX
  656.     /* lock is /tmp/[basename of file_to_lock].mlk */
  657.     sprintf(lock_name, "/tmp/%.10s.mlk", rindex(file_to_lock, '/')+1);
  658. #else
  659.     /* lock is [file_to_lock].lock */
  660.     sprintf(lock_name, "%s.lock", file_to_lock);
  661. #endif
  662.     return(lock_name);
  663. }
  664.  
  665.  
  666. static int flock_fd,    /* file descriptor for flocking mailbox itself */
  667.        create_fd;    /* file descriptor for creating lock file */
  668.  
  669. lock(direction)
  670. int direction;
  671. {
  672.       /** Create lock file to ensure that we don't get any mail 
  673.       while altering the folder contents!
  674.       If it already exists sit and spin until 
  675.          either the lock file is removed...indicating new mail
  676.       or
  677.          we have iterated MAX_ATTEMPTS times, in which case we
  678.          either fail or remove it and make our own (determined
  679.          by if REMOVE_AT_LAST is defined in header file
  680.  
  681.       If direction == INCOMING then DON'T remove the lock file
  682.       on the way out!  (It'd mess up whatever created it!).
  683.  
  684.       But if that succeeds and if we are also locking by flock(),
  685.       follow a similar algorithm. Now if we can't lock by flock(),
  686.       we DO need to remove the lock file, since if we got this far,
  687.       we DID create it, not another process.
  688.       **/
  689.  
  690.       register int create_iteration = 0,
  691.            flock_iteration = 0;
  692.       char pid_buffer[SHORT];
  693.  
  694. #ifndef    LOCK_FLOCK_ONLY        /* { LOCK_FLOCK_ONLY    */
  695.       /* formulate lock file name */
  696.       mk_lockname(cur_folder);
  697.  
  698. #ifdef PIDCHECK
  699.       /** first, try to read the lock file, and if possible, check the pid.
  700.       If we can validate that the pid is no longer active, then remove
  701.       the lock file.
  702.        **/
  703.       if((create_fd=open(lock_name,O_RDONLY)) != -1) {
  704.     if (read(create_fd, pid_buffer, SHORT) > 0) {
  705.       create_iteration = atoi(pid_buffer);
  706.       if (create_iteration) {
  707.         if (kill(create_iteration, 0)) {
  708.           close(create_fd);
  709.           if (unlink(lock_name) != 0) {
  710.         dprint(1, (debugfile,
  711.           "Error %s (%s)\n\ttrying to unlink file %s (%s)\n", 
  712.           error_name(errno), error_description(errno), lock_name, "lock"));
  713.         PutLine1(LINES, 0, 
  714.           "\n\rCouldn't remove the current lock file %s\n\r", lock_name);
  715.         PutLine2(LINES, 0, "** %s - %s **\n\r", error_name(errno),
  716.           error_description(errno));
  717.         if (direction == INCOMING)
  718.           leave();
  719.         else
  720.           emergency_exit();
  721.           }
  722.         }
  723.       }
  724.     }
  725.     create_iteration = 0;
  726.       }
  727. #endif
  728.           
  729.       /* try to assert create lock file MAX_ATTEMPTS times */
  730.       do {
  731.  
  732.     errno = 0;
  733.     if((create_fd=open(lock_name,O_WRONLY | O_CREAT | O_EXCL,0444)) != -1)
  734.       break;
  735.     else {
  736.       if(errno != EEXIST) {
  737.         /* Creation of lock failed NOT because it already exists!!! */
  738.  
  739.         if (direction == OUTGOING) {
  740.           dprint(1, (debugfile, 
  741.         "Error encountered attempting to create lock %s\n", lock_name));
  742.           dprint(1, (debugfile, "** %s - %s **\n", error_name(errno),
  743.             error_description(errno)));
  744.           MoveCursor(LINES, 0);
  745.           printf(
  746.        "\n\rError encountered while attempting to create lock file %s;\n\r",
  747.         lock_name);
  748.           printf("** %s - %s.**\n\r\n\r",
  749.         error_name(errno), error_description(errno));
  750.         } else {    /* incoming - permission denied in the middle?  Odd. */
  751.           dprint(1, (debugfile,
  752.            "Can't create lock file: creat(%s) raises error %s (lock)\n", 
  753.         lock_name, error_name(errno)));
  754.           error1(
  755.            "Can't create lock file! Need write permission in \"%s\".\n\r",
  756.         mailhome);
  757.         }
  758.         leave();
  759.       }
  760.     }
  761.     dprint(2, (debugfile,"File '%s' already exists!  Waiting...(lock)\n", 
  762.       lock_name));
  763.     error1(
  764.       "Waiting to read mailbox while mail is being received: attempt #%d",
  765.       create_iteration);
  766.     sleep(5);
  767.       } while (create_iteration++ < MAX_ATTEMPTS);
  768.       clear_error();
  769.  
  770.       if(errno != 0) {
  771.     
  772.     /* we weren't able to create the lock file */
  773.  
  774. #ifdef REMOVE_AT_LAST
  775.  
  776.     /** time to waste the lock file!  Must be there in error! **/
  777.     dprint(2, (debugfile, 
  778.        "Warning: I'm giving up waiting - removing lock file(lock)\n"));
  779.     if (direction == INCOMING)
  780.       PutLine0(LINES, 0,"\nTimed out - removing current lock file...");
  781.     else
  782.       error("Throwing away the current lock file!");
  783.  
  784.     if (unlink(lock_name) != 0) {
  785.       dprint(1, (debugfile,
  786.         "Error %s (%s)\n\ttrying to unlink file %s (%s)\n", 
  787.         error_name(errno), error_description(errno), lock_name, "lock"));
  788.       PutLine1(LINES, 0, 
  789.         "\n\rCouldn't remove the current lock file %s\n\r", lock_name);
  790.       PutLine2(LINES, 0, "** %s - %s **\n\r", error_name(errno),
  791.         error_description(errno));
  792.       if (direction == INCOMING)
  793.         leave();
  794.       else
  795.         emergency_exit();
  796.     }
  797.  
  798.     /* we've removed the bad lock, let's try to assert lock once more */
  799.     if((create_fd=open(lock_name,O_WRONLY | O_CREAT | O_EXCL,0444)) == -1){
  800.  
  801.       /* still can't lock it - just give up */
  802.       dprint(1, (debugfile, 
  803.         "Error encountered attempting to create lock %s\n", lock_name));
  804.       dprint(1, (debugfile, "** %s - %s **\n", error_name(errno),
  805.         error_description(errno)));
  806.       MoveCursor(LINES, 0);
  807.       printf(
  808.       "\n\rError encountered while attempting to create lock file %s;\n\r",
  809.         lock_name);
  810.       printf("** %s - %s.**\n\r\n\r", error_name(errno),
  811.         error_description(errno));
  812.       leave();
  813.     }
  814. #else
  815.     /* Okay...we die and leave, not updating the mailfile mbox or
  816.        any of those! */
  817.  
  818.     if (direction == INCOMING) {
  819.       PutLine1(LINES, 0, "\n\r\n\rGiving up after %d iterations.\n\r", 
  820.         create_iteration);
  821.       PutLine0(LINES, 0, 
  822.       "\n\rPlease try to read your mail again in a few minutes.\n\r\n\r");
  823.       dprint(1, (debugfile, 
  824.         "Warning: bailing out after %d iterations...(lock)\n",
  825.         create_iteration));
  826.       leave_locked(0);
  827.     } else {
  828.       dprint(1, (debugfile, 
  829.        "Warning: after %d iterations, timed out! (lock)\n",
  830.        create_iteration));
  831.       leave(error("Timed out on locking mailbox.  Leaving program."));
  832.     }
  833. #endif
  834.       }
  835.  
  836.       /* If we're here we successfully created the lock file */
  837.       dprint(5,
  838.     (debugfile, "Lock %s %s for file %s on.\n", lock_name,
  839.     (direction == INCOMING ? "incoming" : "outgoing"), cur_folder));
  840.  
  841.       /* Place the pid of Elm into the lock file for SVR3.2 and its ilk */
  842.       sprintf(pid_buffer, "%d", getpid());
  843.       write(create_fd, pid_buffer, strlen(pid_buffer));
  844.  
  845.       (void)close(create_fd);
  846. #endif                /* } LOCK_FLOCK_ONLY */
  847.  
  848. #ifdef LOCK_BY_FLOCK
  849.       /* Now we also need to lock the file with flock(2) */
  850.  
  851.       /* Open mail file separately for locking */
  852.       if((flock_fd = open(cur_folder, O_RDWR)) < 0) {
  853.     dprint(1, (debugfile, 
  854.         "Error encountered attempting to reopen %s for lock\n", cur_folder));
  855.     dprint(1, (debugfile, "** %s - %s **\n", error_name(errno),
  856.         error_description(errno)));
  857.     MoveCursor(LINES, 0);
  858.     printf(
  859.  "\n\rError encountered while attempting to reopen mailbox %s for lock;\n\r", 
  860.           cur_folder);
  861.     printf("** %s - %s.**\n\r\n\r", error_name(errno),
  862.           error_description(errno));
  863.     (void)unlink(lock_name);
  864.     leave();
  865.       }
  866.  
  867.       /* try to assert lock MAX_ATTEMPTS times */
  868.       do {
  869.  
  870.     errno = 0;
  871.     if(flock(flock_fd, LOCK_NB | LOCK_EX) != -1)
  872.       break;
  873.     else {
  874.       if(errno != EWOULDBLOCK && errno != EAGAIN) {
  875.  
  876.         /* Creation of lock failed NOT because it already exists!!! */
  877.  
  878.         dprint(1, (debugfile, 
  879.           "Error encountered attempting to flock %s\n", cur_folder));
  880.         dprint(1, (debugfile, "** %s - %s **\n", error_name(errno),
  881.           error_description(errno)));
  882.         MoveCursor(LINES, 0);
  883.         printf(
  884.      "\n\rError encountered while attempting to flock mailbox %s;\n\r", 
  885.           cur_folder);
  886.         printf("** %s - %s.**\n\r\n\r", error_name(errno),
  887.           error_description(errno));
  888.         (void)unlink(lock_name);
  889.         leave();
  890.       }
  891.     }
  892.     dprint(2, (debugfile,
  893.       "Mailbox '%s' already locked!  Waiting...(lock)\n", cur_folder));
  894.     error1(
  895.       "Waiting to read mailbox while mail is being received: attempt #%d",
  896.       flock_iteration);
  897.     sleep(5);
  898.       } while (flock_iteration++ < MAX_ATTEMPTS);
  899.       clear_error();
  900.  
  901.       if(errno != 0) {
  902.  
  903.     /* We couldn't lock the file. We die and leave not updating
  904.      * the mailfile mbox or any of those! */
  905.  
  906.     if (direction == INCOMING) {
  907.       PutLine1(LINES, 0, "\n\r\n\rGiving up after %d iterations.\n\r", 
  908.         flock_iteration);
  909.       PutLine0(LINES, 0, 
  910.       "\n\rPlease try to read your mail again in a few minutes.\n\r\n\r");
  911.       dprint(1, (debugfile, 
  912.         "Warning: bailing out after %d iterations...(lock)\n",
  913.         flock_iteration));
  914.     } else {
  915.       dprint(1, (debugfile, 
  916.        "Warning: after %d iterations, timed out! (lock)\n",
  917.        flock_iteration));
  918.     }
  919. #ifndef    LOCK_FLOCK_ONLY
  920.     (void)unlink(lock_name);
  921. #endif
  922.     leave(error("Timed out on locking mailbox. Leaving program."));
  923.       }
  924.  
  925.       /* We locked the file */
  926.       dprint(5,
  927.     (debugfile, "Lock %s on file %s on.\n",
  928.     (direction == INCOMING ? "incoming" : "outgoing"), cur_folder));
  929. #endif
  930.  
  931.       dprint(5,
  932.     (debugfile, "Lock %s for file %s on successfully.\n",
  933.     (direction == INCOMING ? "incoming" : "outgoing"), cur_folder));
  934.       lock_state = ON;
  935.       return(0);
  936. }
  937.  
  938. int
  939. unlock()
  940. {
  941.     /** Remove the lock file!    This must be part of the interrupt
  942.         processing routine to ensure that the lock file is NEVER
  943.         left sitting in the mailhome directory!
  944.  
  945.         If also using flock(), remove the file lock as well.
  946.      **/
  947.  
  948.     int retcode = 0;
  949.  
  950.     dprint(5,
  951.       (debugfile, "Lock %s for file %s %s off.\n",
  952.         (*lock_name ? lock_name : "none"), cur_folder,
  953.         (lock_state == ON ? "going" : "already")));
  954.  
  955.     if(lock_state == ON) {
  956.  
  957. #ifdef LOCK_BY_FLOCK
  958.       if((retcode = flock(flock_fd, LOCK_UN)) == -1) {
  959.         dprint(1, (debugfile,
  960.           "Error %s (%s)\n\ttrying to unlock file %s (%s)\n", 
  961.           error_name(errno), error_description(errno), cur_folder, "unlock"));
  962.  
  963.         /* try to force unlock by closing file */
  964.         if(close(flock_fd) == -1) {
  965.           dprint(1, (debugfile,
  966.       "Error %s (%s)\n\ttrying to force unlock file %s via close() (%s)\n", 
  967.           error_name(errno), error_description(errno), cur_folder, "unlock"));
  968.           error1("Couldn't unlock my own mailbox %s!", cur_folder);
  969.           return(retcode);
  970.         }
  971.       }
  972.       (void)close(flock_fd);
  973. #endif
  974. #ifdef    LOCK_FLOCK_ONLY    /* { LOCK_FLOCK_ONLY */
  975.       *lock_name = '\0';        /* null lock file name */
  976.        lock_state = OFF;        /* indicate we don't have a lock on */
  977. #else
  978.       if((retcode = unlink(lock_name)) == 0) {    /* remove lock file */
  979.         *lock_name = '\0';        /* null lock file name */
  980.         lock_state = OFF;        /* indicate we don't have a lock on */
  981.       } else {
  982.         dprint(1, (debugfile,
  983.           "Error %s (%s)\n\ttrying to unlink file %s (%s)\n", 
  984.           error_name(errno), error_description(errno), lock_name,"unlock"));
  985.           error1("Couldn't remove my own lock file %s!", lock_name);
  986.       }
  987. #endif    /* } LOCK_FLOCK_ONLY */
  988.     }
  989.     return(retcode);
  990. }
  991.