]> granicus.if.org Git - apache/blobdiff - support/htpasswd.c
Merge r1351737 from trunk:
[apache] / support / htpasswd.c
index f760d6631a26d0e572bcfb69bdefbc43c11088eb..16e55a0630b1d5881bd9706eda99093884390a6a 100644 (file)
@@ -1,59 +1,17 @@
-/* ====================================================================
- * The Apache Software License, Version 1.1
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
  *
- * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights
- * reserved.
+ *     http://www.apache.org/licenses/LICENSE-2.0
  *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * 3. The end-user documentation included with the redistribution,
- *    if any, must include the following acknowledgment:
- *       "This product includes software developed by the
- *        Apache Software Foundation (http://www.apache.org/)."
- *    Alternately, this acknowledgment may appear in the software itself,
- *    if and wherever such third-party acknowledgments normally appear.
- *
- * 4. The names "Apache" and "Apache Software Foundation" must
- *    not be used to endorse or promote products derived from this
- *    software without prior written permission. For written
- *    permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache",
- *    nor may "Apache" appear in their name, without prior written
- *    permission of the Apache Software Foundation.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation.  For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- * Portions of this software are based upon public domain software
- * originally written at the National Center for Supercomputing Applications,
- * University of Illinois, Urbana-Champaign.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
  */
 
 /******************************************************************************
@@ -65,7 +23,7 @@
 /*
  * htpasswd.c: simple program for manipulating password file for
  * the Apache HTTP server
- * 
+ *
  * Originally by Rob McCool
  *
  * Exit values:
@@ -77,6 +35,7 @@
  *  5: Failure; buffer would overflow (username, filename, or computed
  *     record too long)
  *  6: Failure; username contains illegal or reserved characters
+ *  7: Failure; file is not a valid htpasswd file
  */
 
 #include "apr.h"
 #define ALG_PLAIN 0
 #define ALG_CRYPT 1
 #define ALG_APMD5 2
-#define ALG_APSHA 3 
+#define ALG_APSHA 3
 
 #define ERR_FILEPERM 1
 #define ERR_SYNTAX 2
 #define ERR_INTERRUPTED 4
 #define ERR_OVERFLOW 5
 #define ERR_BADUSER 6
+#define ERR_INVALID 7
 
 #define APHTP_NEWFILE        1
 #define APHTP_NOFILE         2
 #define APHTP_NONINTERACTIVE 4
+#define APHTP_DELUSER        8
 
 apr_file_t *errfile;
 apr_file_t *ftemp = NULL;
 
+#define NL APR_EOL_STR
+
+#if defined(WIN32) || defined(NETWARE)
+#define CRYPT_ALGO_SUPPORTED 0
+#else
+#define CRYPT_ALGO_SUPPORTED 1
+#endif
+
+#if CRYPT_ALGO_SUPPORTED
 static void to64(char *s, unsigned long v, int n)
 {
     static unsigned char itoa64[] =         /* 0 ... 63 => ASCII - 64 */
@@ -151,10 +121,43 @@ static void to64(char *s, unsigned long v, int n)
         v >>= 6;
     }
 }
+#endif
+
+static void generate_salt(char *s, size_t size)
+{
+    static unsigned char tbl[] =
+        "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+    size_t i;
+    for (i = 0; i < size; ++i) {
+        int idx = (int) (64.0 * rand() / (RAND_MAX + 1.0));
+        s[i] = tbl[idx];
+    }
+}
+
+static apr_status_t seed_rand(void)
+{
+    int seed = 0;
+    apr_status_t rv;
+    rv = apr_generate_random_bytes((unsigned char*) &seed, sizeof(seed));
+    if (rv) {
+        apr_file_printf(errfile, "Unable to generate random bytes: %pm" NL, &rv);
+        return rv;
+    }
+    srand(seed);
+    return rv;
+}
 
 static void putline(apr_file_t *f, const char *l)
 {
-    apr_file_puts(l, f);
+    apr_status_t rc;
+    rc = apr_file_puts(l, f);
+    if (rc != APR_SUCCESS) {
+        char errstr[MAX_STRING_LEN];
+        apr_strerror(rc, errstr, MAX_STRING_LEN);
+        apr_file_printf(errfile, "Error writing temp file: %s" NL, errstr);
+        apr_file_close(f);
+        exit(ERR_FILEPERM);
+    }
 }
 
 /*
@@ -162,7 +165,7 @@ static void putline(apr_file_t *f, const char *l)
  * indicates success; failure means that the output buffer contains an
  * error message instead.
  */
-static int mkrecord(char *user, char *record, size_t rlen, char *passwd,
+static int mkrecord(char *user, char *record, apr_size_t rlen, char *passwd,
                     int alg)
 {
     char *pw;
@@ -170,7 +173,10 @@ static int mkrecord(char *user, char *record, size_t rlen, char *passwd,
     char pwin[MAX_STRING_LEN];
     char pwv[MAX_STRING_LEN];
     char salt[9];
-    size_t bufsize;
+    apr_size_t bufsize;
+#if CRYPT_ALGO_SUPPORTED
+    char *cbuf;
+#endif
 
     if (passwd != NULL) {
         pw = passwd;
@@ -178,8 +184,8 @@ static int mkrecord(char *user, char *record, size_t rlen, char *passwd,
     else {
         bufsize = sizeof(pwin);
         if (apr_password_get("New password: ", pwin, &bufsize) != 0) {
-            apr_snprintf(record, (rlen - 1), "password too long (>%" APR_SIZE_T_FMT
-                ")", sizeof(pwin) - 1);
+            apr_snprintf(record, (rlen - 1), "password too long (>%"
+                         APR_SIZE_T_FMT ")", sizeof(pwin) - 1);
             return ERR_OVERFLOW;
         }
         bufsize = sizeof(pwv);
@@ -198,9 +204,11 @@ static int mkrecord(char *user, char *record, size_t rlen, char *passwd,
         apr_sha1_base64(pw,strlen(pw),cpw);
         break;
 
-    case ALG_APMD5: 
-        (void) srand((int) time((time_t *) NULL));
-        to64(&salt[0], rand(), 8);
+    case ALG_APMD5:
+        if (seed_rand()) {
+            break;
+        }
+        generate_salt(&salt[0], 8);
         salt[8] = '\0';
 
         apr_md5_encode((const char *)pw, (const char *)salt,
@@ -212,16 +220,36 @@ static int mkrecord(char *user, char *record, size_t rlen, char *passwd,
         apr_cpystrn(cpw,pw,sizeof(cpw));
         break;
 
-#if !(defined(WIN32) || defined(NETWARE))
+#if CRYPT_ALGO_SUPPORTED
     case ALG_CRYPT:
     default:
-        (void) srand((int) time((time_t *) NULL));
+        if (seed_rand()) {
+            break;
+        }
         to64(&salt[0], rand(), 8);
         salt[8] = '\0';
 
-        apr_cpystrn(cpw, (char *)crypt(pw, salt), sizeof(cpw) - 1);
+        cbuf = crypt(pw, salt);
+        if (cbuf == NULL) {
+            char errbuf[128];
+
+            apr_snprintf(record, rlen-1, "crypt() failed: %s", 
+                         apr_strerror(errno, errbuf, sizeof errbuf));
+            return ERR_PWMISMATCH;
+        }
+
+        apr_cpystrn(cpw, cbuf, sizeof(cpw) - 1);
+        if (strlen(pw) > 8) {
+            char *truncpw = strdup(pw);
+            truncpw[8] = '\0';
+            if (!strcmp(cpw, crypt(truncpw, salt))) {
+                apr_file_printf(errfile, "Warning: Password truncated to 8 characters "
+                                "by CRYPT algorithm." NL);
+            }
+            free(truncpw);
+        }
         break;
-#endif
+#endif /* CRYPT_ALGO_SUPPORTED */
     }
     memset(pw, '\0', strlen(pw));
 
@@ -236,36 +264,37 @@ static int mkrecord(char *user, char *record, size_t rlen, char *passwd,
     strcpy(record, user);
     strcat(record, ":");
     strcat(record, cpw);
+    strcat(record, "\n");
     return 0;
 }
 
 static void usage(void)
 {
-    apr_file_printf(errfile, "Usage:\n");
-    apr_file_printf(errfile, "\thtpasswd [-cmdps] passwordfile username\n");
-    apr_file_printf(errfile, "\thtpasswd -b[cmdps] passwordfile username password\n\n");
-    apr_file_printf(errfile, "\thtpasswd -n[mdps] username\n");
-    apr_file_printf(errfile, "\thtpasswd -nb[mdps] username password\n");
-    apr_file_printf(errfile, " -c  Create a new file.\n");
-    apr_file_printf(errfile, " -n  Don't update file; display results on stdout.\n");
+    apr_file_printf(errfile, "Usage:" NL);
+    apr_file_printf(errfile, "\thtpasswd [-cmdpsD] passwordfile username" NL);
+    apr_file_printf(errfile, "\thtpasswd -b[cmdpsD] passwordfile username "
+                    "password" NL NL);
+    apr_file_printf(errfile, "\thtpasswd -n[mdps] username" NL);
+    apr_file_printf(errfile, "\thtpasswd -nb[mdps] username password" NL);
+    apr_file_printf(errfile, " -c  Create a new file." NL);
+    apr_file_printf(errfile, " -n  Don't update file; display results on "
+                    "stdout." NL);
     apr_file_printf(errfile, " -m  Force MD5 encryption of the password"
-#if defined(WIN32) || defined(TPF) || defined(NETWARE)
         " (default)"
-#endif
-        ".\n");
+        "." NL);
     apr_file_printf(errfile, " -d  Force CRYPT encryption of the password"
-#if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
-            " (default)"
-#endif
-            ".\n");
-    apr_file_printf(errfile, " -p  Do not encrypt the password (plaintext).\n");
-    apr_file_printf(errfile, " -s  Force SHA encryption of the password.\n");
-    apr_file_printf(errfile, " -b  Use the password from the command line rather "
-            "than prompting for it.\n");
+            "." NL);
+    apr_file_printf(errfile, " -p  Do not encrypt the password (plaintext)." NL);
+    apr_file_printf(errfile, " -s  Force SHA encryption of the password." NL);
+    apr_file_printf(errfile, " -b  Use the password from the command line "
+            "rather than prompting for it." NL);
+    apr_file_printf(errfile, " -D  Delete the specified user." NL);
     apr_file_printf(errfile,
-            "On Windows, NetWare and TPF systems the '-m' flag is used by default.\n");
+            "On other systems than Windows and NetWare the '-p' flag will "
+            "probably not work." NL);
     apr_file_printf(errfile,
-            "On all other systems, the '-p' flag will probably not work.\n");
+            "The SHA algorithm does not use a salt and is less secure than "
+            "the MD5 algorithm." NL);
     exit(ERR_SYNTAX);
 }
 
@@ -284,22 +313,6 @@ static int accessible(apr_pool_t *pool, char *fname, int mode)
     return 1;
 }
 
-/*
- * Return true if a file is readable.
- */
-static int readable(apr_pool_t *pool, char *fname)
-{
-    return accessible(pool, fname, APR_READ);
-}
-
-/*
- * Return true if the specified file can be opened for write access.
- */
-static int writable(apr_pool_t *pool, char *fname)
-{
-    return accessible(pool, fname, APR_APPEND);
-}
-
 /*
  * Return true if the named file exists, regardless of permissions.
  */
@@ -312,15 +325,16 @@ static int exists(char *fname, apr_pool_t *pool)
     return ((check || sbuf.filetype != APR_REG) ? 0 : 1);
 }
 
-#ifdef NETWARE
-void nwTerminate()
+static void terminate(void)
 {
+    apr_terminate();
+#ifdef NETWARE
     pressanykey();
-}
 #endif
+}
 
-static void check_args(apr_pool_t *pool, int argc, const char *const argv[], 
-                       int *alg, int *mask, char **user, char **pwfilename, 
+static void check_args(apr_pool_t *pool, int argc, const char *const argv[],
+                       int *alg, int *mask, char **user, char **pwfilename,
                        char **password)
 {
     const char *arg;
@@ -329,7 +343,7 @@ static void check_args(apr_pool_t *pool, int argc, const char *const argv[],
 
     /*
      * Preliminary check to make sure they provided at least
-     * three arguments, we'll do better argument checking as 
+     * three arguments, we'll do better argument checking as
      * we parse the command line.
      */
     if (argc < 3) {
@@ -369,6 +383,9 @@ static void check_args(apr_pool_t *pool, int argc, const char *const argv[],
                 *mask |= APHTP_NONINTERACTIVE;
                 args_left++;
             }
+            else if (*arg == 'D') {
+                *mask |= APHTP_DELUSER;
+            }
             else {
                 usage();
             }
@@ -376,7 +393,15 @@ static void check_args(apr_pool_t *pool, int argc, const char *const argv[],
     }
 
     if ((*mask & APHTP_NEWFILE) && (*mask & APHTP_NOFILE)) {
-        apr_file_printf(errfile, "%s: -c and -n options conflict\n", argv[0]);
+        apr_file_printf(errfile, "%s: -c and -n options conflict" NL, argv[0]);
+        exit(ERR_SYNTAX);
+    }
+    if ((*mask & APHTP_NEWFILE) && (*mask & APHTP_DELUSER)) {
+        apr_file_printf(errfile, "%s: -c and -D options conflict" NL, argv[0]);
+        exit(ERR_SYNTAX);
+    }
+    if ((*mask & APHTP_NOFILE) && (*mask & APHTP_DELUSER)) {
+        apr_file_printf(errfile, "%s: -n and -D options conflict" NL, argv[0]);
         exit(ERR_SYNTAX);
     }
     /*
@@ -393,25 +418,25 @@ static void check_args(apr_pool_t *pool, int argc, const char *const argv[],
     }
     else {
         if (strlen(argv[i]) > (APR_PATH_MAX - 1)) {
-            apr_file_printf(errfile, "%s: filename too long\n", argv[0]);
+            apr_file_printf(errfile, "%s: filename too long" NL, argv[0]);
             exit(ERR_OVERFLOW);
         }
         *pwfilename = apr_pstrdup(pool, argv[i]);
         if (strlen(argv[i + 1]) > (MAX_STRING_LEN - 1)) {
-            apr_file_printf(errfile, "%s: username too long (> %d)\n",
+            apr_file_printf(errfile, "%s: username too long (> %d)" NL,
                 argv[0], MAX_STRING_LEN - 1);
             exit(ERR_OVERFLOW);
         }
     }
     *user = apr_pstrdup(pool, argv[i + 1]);
     if ((arg = strchr(*user, ':')) != NULL) {
-        apr_file_printf(errfile, "%s: username contains illegal character '%c'\n",
-                argv[0], *arg);
+        apr_file_printf(errfile, "%s: username contains illegal "
+                        "character '%c'" NL, argv[0], *arg);
         exit(ERR_BADUSER);
     }
     if (*mask & APHTP_NONINTERACTIVE) {
         if (strlen(argv[i + 2]) > (MAX_STRING_LEN - 1)) {
-            apr_file_printf(errfile, "%s: password too long (> %d)\n",
+            apr_file_printf(errfile, "%s: password too long (> %d)" NL,
                 argv[0], MAX_STRING_LEN);
             exit(ERR_OVERFLOW);
         }
@@ -432,40 +457,38 @@ int main(int argc, const char * const argv[])
     char *pwfilename = NULL;
     char *user = NULL;
     char tn[] = "htpasswd.tmp.XXXXXX";
-    char scratch[MAX_STRING_LEN];
-    char *str = NULL;
+    char *dirname;
+    char *scratch, cp[MAX_STRING_LEN];
     int found = 0;
     int i;
-    int alg = ALG_CRYPT;
+    int alg = ALG_APMD5;
     int mask = 0;
     apr_pool_t *pool;
+    int existing_file = 0;
 #if APR_CHARSET_EBCDIC
     apr_status_t rv;
     apr_xlate_t *to_ascii;
 #endif
 
     apr_app_initialize(&argc, &argv, NULL);
-    atexit(apr_terminate);
-#ifdef NETWARE
-    atexit(nwTerminate);
-#endif
+    atexit(terminate);
     apr_pool_create(&pool, NULL);
     apr_file_open_stderr(&errfile, pool);
 
 #if APR_CHARSET_EBCDIC
-    rv = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, pool);
+    rv = apr_xlate_open(&to_ascii, "ISO-8859-1", APR_DEFAULT_CHARSET, pool);
     if (rv) {
-        apr_file_printf(errfile, "apr_xlate_open(to ASCII)->%d\n", rv);
+        apr_file_printf(errfile, "apr_xlate_open(to ASCII)->%d" NL, rv);
         exit(1);
     }
     rv = apr_SHA1InitEBCDIC(to_ascii);
     if (rv) {
-        apr_file_printf(errfile, "apr_SHA1InitEBCDIC()->%d\n", rv);
+        apr_file_printf(errfile, "apr_SHA1InitEBCDIC()->%d" NL, rv);
         exit(1);
     }
     rv = apr_MD5InitEBCDIC(to_ascii);
     if (rv) {
-        apr_file_printf(errfile, "apr_MD5InitEBCDIC()->%d\n", rv);
+        apr_file_printf(errfile, "apr_MD5InitEBCDIC()->%d" NL, rv);
         exit(1);
     }
 #endif /*APR_CHARSET_EBCDIC*/
@@ -473,64 +496,53 @@ int main(int argc, const char * const argv[])
     check_args(pool, argc, argv, &alg, &mask, &user, &pwfilename, &password);
 
 
-#if defined(WIN32) || defined(NETWARE)
+#if !CRYPT_ALGO_SUPPORTED
     if (alg == ALG_CRYPT) {
         alg = ALG_APMD5;
-        apr_file_printf(errfile, "Automatically using MD5 format.\n");
+        apr_file_printf(errfile, "Automatically using MD5 format." NL);
     }
 #endif
 
-#if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
+#if CRYPT_ALGO_SUPPORTED
     if (alg == ALG_PLAIN) {
-        apr_file_printf(errfile,"Warning: storing passwords as plain text might "
-                "just not work on this platform.\n");
+        apr_file_printf(errfile,"Warning: storing passwords as plain text "
+                        "might just not work on this platform." NL);
     }
 #endif
-    if (! mask & APHTP_NOFILE) {
-        /*
-         * Only do the file checks if we're supposed to frob it.
-         *
-         * Verify that the file exists if -c was omitted.  We give a special
-         * message if it doesn't.
-         */
-        if ((! mask & APHTP_NEWFILE) && (! exists(pwfilename, pool))) {
-            apr_file_printf(errfile,
-                    "%s: cannot modify file %s; use '-c' to create it\n",
-                    argv[0], pwfilename);
-            perror("apr_file_open");
-            exit(ERR_FILEPERM);
-        }
-        /*
-         * Verify that we can read the existing file in the case of an update
-         * to it (rather than creation of a new one).
-         */
-        if ((! mask & APHTP_NEWFILE) && (! readable(pool, pwfilename))) {
-            apr_file_printf(errfile, "%s: cannot open file %s for read access\n",
-                    argv[0], pwfilename);
-            perror("apr_file_open");
-            exit(ERR_FILEPERM);
-        }
-        /*
-         * Now check to see if we can preserve an existing file in case
-         * of password verification errors on a -c operation.
-         */
-        if ((mask & APHTP_NEWFILE) && exists(pwfilename, pool) && 
-            (! readable(pool, pwfilename))) {
-            apr_file_printf(errfile, "%s: cannot open file %s for read access\n"
-                    "%s: existing auth data would be lost on "
-                    "password mismatch",
-                    argv[0], pwfilename, argv[0]);
-            perror("apr_file_open");
-            exit(ERR_FILEPERM);
+
+    /*
+     * Only do the file checks if we're supposed to frob it.
+     */
+    if (!(mask & APHTP_NOFILE)) {
+        existing_file = exists(pwfilename, pool);
+        if (existing_file) {
+            /*
+             * Check that this existing file is readable and writable.
+             */
+            if (!accessible(pool, pwfilename, APR_READ | APR_APPEND)) {
+                apr_file_printf(errfile, "%s: cannot open file %s for "
+                                "read/write access" NL, argv[0], pwfilename);
+                exit(ERR_FILEPERM);
+            }
         }
-        /*
-         * Now verify that the file is writable!
-         */
-        if (! writable(pool, pwfilename)) {
-            apr_file_printf(errfile, "%s: cannot open file %s for write access\n",
-                    argv[0], pwfilename);
-            perror("apr_file_open");
-            exit(ERR_FILEPERM);
+        else {
+            /*
+             * Error out if -c was omitted for this non-existant file.
+             */
+            if (!(mask & APHTP_NEWFILE)) {
+                apr_file_printf(errfile,
+                        "%s: cannot modify file %s; use '-c' to create it" NL,
+                        argv[0], pwfilename);
+                exit(ERR_FILEPERM);
+            }
+            /*
+             * As it doesn't exist yet, verify that we can create it.
+             */
+            if (!accessible(pool, pwfilename, APR_CREATE | APR_WRITE)) {
+                apr_file_printf(errfile, "%s: cannot create file %s" NL,
+                                argv[0], pwfilename);
+                exit(ERR_FILEPERM);
+            }
         }
     }
 
@@ -541,24 +553,33 @@ int main(int argc, const char * const argv[])
      * Any error message text is returned in the record buffer, since
      * the mkrecord() routine doesn't have access to argv[].
      */
-    i = mkrecord(user, record, sizeof(record) - 1,
-                 password, alg);
-    if (i != 0) {
-        apr_file_printf(errfile, "%s: %s\n", argv[0], record);
-        exit(i);
-    }
-    if (mask & APHTP_NOFILE) {
-        printf("%s\n", record);
-        exit(0);
+    if (!(mask & APHTP_DELUSER)) {
+        i = mkrecord(user, record, sizeof(record) - 1,
+                     password, alg);
+        if (i != 0) {
+            apr_file_printf(errfile, "%s: %s" NL, argv[0], record);
+            exit(i);
+        }
+        if (mask & APHTP_NOFILE) {
+            printf("%s" NL, record);
+            exit(0);
+        }
     }
 
     /*
      * We can access the files the right way, and we have a record
      * to add or update.  Let's do it..
      */
-    if (apr_file_mktemp(&ftemp, tn, 0, pool) != APR_SUCCESS) {
-        apr_file_printf(errfile, "%s: unable to create temporary file '%s'\n", 
-                        argv[0], tn);
+    if (apr_temp_dir_get((const char**)&dirname, pool) != APR_SUCCESS) {
+        apr_file_printf(errfile, "%s: could not determine temp dir" NL,
+                        argv[0]);
+        exit(ERR_FILEPERM);
+    }
+    dirname = apr_psprintf(pool, "%s/%s", dirname, tn);
+
+    if (apr_file_mktemp(&ftemp, dirname, 0, pool) != APR_SUCCESS) {
+        apr_file_printf(errfile, "%s: unable to create temporary file %s" NL,
+                        argv[0], dirname);
         exit(ERR_FILEPERM);
     }
 
@@ -566,16 +587,26 @@ int main(int argc, const char * const argv[])
      * If we're not creating a new file, copy records from the existing
      * one to the temporary file until we find the specified user.
      */
-    if (apr_file_open(&fpw, pwfilename, APR_READ, APR_OS_DEFAULT, 
-                      pool) == APR_SUCCESS) {
-        while (! (apr_file_gets(line, sizeof(line), fpw))) {
+    if (existing_file && !(mask & APHTP_NEWFILE)) {
+        if (apr_file_open(&fpw, pwfilename, APR_READ | APR_BUFFERED,
+                          APR_OS_DEFAULT, pool) != APR_SUCCESS) {
+            apr_file_printf(errfile, "%s: unable to read file %s" NL,
+                            argv[0], pwfilename);
+            exit(ERR_FILEPERM);
+        }
+        while (apr_file_gets(line, sizeof(line), fpw) == APR_SUCCESS) {
             char *colon;
 
-            if ((line[0] == '#') || (line[0] == '\0')) {
+            strcpy(cp, line);
+            scratch = cp;
+            while (apr_isspace(*scratch)) {
+                ++scratch;
+            }
+
+            if (!*scratch || (*scratch == '#')) {
                 putline(ftemp, line);
                 continue;
             }
-            strcpy(scratch, line);
             /*
              * See if this is our user.
              */
@@ -583,33 +614,60 @@ int main(int argc, const char * const argv[])
             if (colon != NULL) {
                 *colon = '\0';
             }
+            else {
+                /*
+                 * If we've not got a colon on the line, this could well
+                 * not be a valid htpasswd file.
+                 * We should bail at this point.
+                 */
+                apr_file_printf(errfile, "%s: The file %s does not appear "
+                                         "to be a valid htpasswd file." NL,
+                                argv[0], pwfilename);
+                apr_file_close(fpw);
+                exit(ERR_INVALID);
+            }
             if (strcmp(user, scratch) != 0) {
                 putline(ftemp, line);
                 continue;
             }
             else {
-                /* We found the user we were looking for, add him to the file.
-                 */
-                apr_file_printf(errfile, "Updating ");
-                putline(ftemp, record);
+                if (!(mask & APHTP_DELUSER)) {
+                    /* We found the user we were looking for.
+                     * Add him to the file.
+                    */
+                    apr_file_printf(errfile, "Updating ");
+                    putline(ftemp, record);
+                    found++;
+                }
+                else {
+                    /* We found the user we were looking for.
+                     * Delete them from the file.
+                     */
+                    apr_file_printf(errfile, "Deleting ");
+                    found++;
+                }
             }
         }
+        apr_file_close(fpw);
     }
-    if (!found) {
+    if (!found && !(mask & APHTP_DELUSER)) {
         apr_file_printf(errfile, "Adding ");
         putline(ftemp, record);
     }
-    apr_file_printf(errfile, "password for user %s\n", user);
-    apr_file_close(fpw);
+    else if (!found && (mask & APHTP_DELUSER)) {
+        apr_file_printf(errfile, "User %s not found" NL, user);
+        exit(0);
+    }
+    apr_file_printf(errfile, "password for user %s" NL, user);
 
     /* The temporary file has all the data, just copy it to the new location.
      */
-#if defined(OS2) || defined(WIN32)
-    str = apr_psprintf(pool, "copy \"%s\" \"%s\"", tn, pwfilename);
-#else
-    str = apr_psprintf(pool, "cp %s %s", tn, pwfilename);
-#endif
-    system(str);
+    if (apr_file_copy(dirname, pwfilename, APR_FILE_SOURCE_PERMS, pool) !=
+        APR_SUCCESS) {
+        apr_file_printf(errfile, "%s: unable to update file %s" NL,
+                        argv[0], pwfilename);
+        exit(ERR_FILEPERM);
+    }
     apr_file_close(ftemp);
     return 0;
 }