]> granicus.if.org Git - shadow/blobdiff - src/groupadd.c
* src/grpconv.c: Fail if not called correctly.
[shadow] / src / groupadd.c
index de8eec65e6afc65ba244a92e790a21ea22f51b99..7ec21e942d33bd95c3e8990f5ffb05593733b693 100644 (file)
@@ -1,5 +1,8 @@
 /*
- * Copyright 1991 - 1993, Julianne Frances Haugh
+ * Copyright (c) 1991 - 1993, Julianne Frances Haugh
+ * Copyright (c) 1996 - 2000, Marek Michałkiewicz
+ * Copyright (c) 2000 - 2006, Tomasz Kłoczko
+ * Copyright (c) 2007 - 2009, Nicolas François
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * 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. Neither the name of Julianne F. Haugh nor the names of its contributors
- *    may be used to endorse or promote products derived from this software
- *    without specific prior written permission.
+ * 3. The name of the copyright holders or contributors may not be used to
+ *    endorse or promote products derived from this software without
+ *    specific prior written permission.
  *
- * THIS SOFTWARE IS PROVIDED BY JULIE HAUGH AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS 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 JULIE HAUGH OR 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 IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESS 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 COPYRIGHT
+ * HOLDERS OR 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.
  */
 
 #include <config.h>
 
-#include "rcsid.h"
-RCSID (PKG_VER "$Id: groupadd.c,v 1.29 2004/10/11 06:26:40 kloczek Exp $")
-#include <sys/types.h>
-#include <stdio.h>
-#include <grp.h>
+#ident "$Id$"
+
 #include <ctype.h>
 #include <fcntl.h>
-#include "defines.h"
-#include "prototypes.h"
+#include <getopt.h>
+#include <grp.h>
+#include <stdio.h>
+#include <sys/types.h>
+#ifdef ACCT_TOOLS_SETUID
+#ifdef USE_PAM
+#include "pam_defs.h"
+#include <pwd.h>
+#endif                         /* USE_PAM */
+#endif                         /* ACCT_TOOLS_SETUID */
 #include "chkname.h"
+#include "defines.h"
 #include "getdef.h"
 #include "groupio.h"
 #include "nscd.h"
+#include "prototypes.h"
 #ifdef SHADOWGRP
 #include "sgroupio.h"
-#ifdef USE_PAM
-#include <security/pam_appl.h>
-#include <security/pam_misc.h>
-#include <pwd.h>
-#endif                         /* USE_PAM */
-static int is_shadow_grp;
 #endif
 
 /*
  * exit status values
  */
-
+/*@-exitarg@*/
 #define E_SUCCESS      0       /* success */
 #define E_USAGE                2       /* invalid command syntax */
 #define E_BAD_ARG      3       /* invalid argument to option */
@@ -63,44 +67,63 @@ static int is_shadow_grp;
 #define E_NAME_IN_USE  9       /* group name not unique */
 #define E_GRP_UPDATE   10      /* can't update group file */
 
-static char *group_name;
-static gid_t group_id;
-static char *empty_list = NULL;
+/*
+ * Global variables
+ */
+const char *Prog;
 
-static char *Prog;
+static /*@null@*/char *group_name;
+static gid_t group_id;
+static /*@null@*/char *group_passwd;
+static /*@null@*/char *empty_list = NULL;
 
-static int oflg = 0;           /* permit non-unique group ID to be specified with -g */
-static int gflg = 0;           /* ID value for the new group */
-static int fflg = 0;           /* if group already exists, do nothing and exit(0) */
+static bool oflg = false;      /* permit non-unique group ID to be specified with -g */
+static bool gflg = false;      /* ID value for the new group */
+static bool fflg = false;      /* if group already exists, do nothing and exit(0) */
+static bool rflg = false;      /* create a system account */
+static bool pflg = false;      /* new encrypted password */
 
-#ifdef NDBM
-extern int gr_dbm_mode;
-extern int sg_dbm_mode;
+#ifdef SHADOWGRP
+static bool is_shadow_grp;
 #endif
 
 /* local function prototypes */
-static void usage (void);
-static void new_grent (struct group *);
+static void usage (int status);
+static void new_grent (struct group *grent);
 
 #ifdef SHADOWGRP
-static void new_sgent (struct sgrp *);
+static void new_sgent (struct sgrp *sgent);
 #endif
 static void grp_update (void);
-static void find_new_gid (void);
 static void check_new_name (void);
-static void process_flags (int, char **);
 static void close_files (void);
 static void open_files (void);
-static void fail_exit (int);
+static void process_flags (int argc, char **argv);
+static void check_flags (void);
+static void check_perms (void);
 
 /*
  * usage - display usage message and exit
  */
-
-static void usage (void)
+static void usage (int status)
 {
-       fprintf (stderr, _("Usage: groupadd [-g gid [-o]] [-f] group\n"));
-       exit (E_USAGE);
+       FILE *usageout = (E_SUCCESS != status) ? stderr : stdout;
+       (void) fprintf (usageout,
+                       _("Usage: %s [options] GROUP\n"
+                         "\n"
+                         "Options:\n"),
+                       Prog);
+       (void) fputs (_("  -f, --force                   exit successfully if the group already exists,\n"
+                       "                                and cancel -g if the GID is already used\n"), usageout);
+       (void) fputs (_("  -g, --gid GID                 use GID for the new group\n"), usageout);
+       (void) fputs (_("  -h, --help                    display this help message and exit\n"), usageout);
+       (void) fputs (_("  -K, --key KEY=VALUE           override /etc/login.defs defaults\n"), usageout);
+       (void) fputs (_("  -o, --non-unique              allow to create groups with duplicate\n"
+                       "                                (non-unique) GID\n"), usageout);
+       (void) fputs (_("  -p, --password PASSWORD       use this encrypted password for the new group\n"), usageout);
+       (void) fputs (_("  -r, --system                  create a system account\n"), usageout);
+       (void) fputs ("\n", usageout);
+       exit (status);
 }
 
 /*
@@ -109,12 +132,15 @@ static void usage (void)
  *     new_grent() takes all of the values that have been entered and fills
  *     in a (struct group) with them.
  */
-
 static void new_grent (struct group *grent)
 {
        memzero (grent, sizeof *grent);
        grent->gr_name = group_name;
-       grent->gr_passwd = SHADOW_PASSWD_STRING;        /* XXX warning: const */
+       if (pflg) {
+               grent->gr_passwd = group_passwd;
+       } else {
+               grent->gr_passwd = SHADOW_PASSWD_STRING;        /* XXX warning: const */
+       }
        grent->gr_gid = group_id;
        grent->gr_mem = &empty_list;
 }
@@ -126,12 +152,15 @@ static void new_grent (struct group *grent)
  *     new_sgent() takes all of the values that have been entered and fills
  *     in a (struct sgrp) with them.
  */
-
 static void new_sgent (struct sgrp *sgent)
 {
        memzero (sgent, sizeof *sgent);
        sgent->sg_name = group_name;
-       sgent->sg_passwd = "!"; /* XXX warning: const */
+       if (pflg) {
+               sgent->sg_passwd = group_passwd;
+       } else {
+               sgent->sg_passwd = "!"; /* XXX warning: const */
+       }
        sgent->sg_adm = &empty_list;
        sgent->sg_mem = &empty_list;
 }
@@ -142,7 +171,6 @@ static void new_sgent (struct sgrp *sgent)
  *
  *     grp_update() writes the new records to the group files.
  */
-
 static void grp_update (void)
 {
        struct group grp;
@@ -152,453 +180,434 @@ static void grp_update (void)
 #endif                         /* SHADOWGRP */
 
        /*
-        * Create the initial entries for this new group.
+        * To add the group, we need to update /etc/group.
+        * Make sure failures will be reported.
         */
+       add_cleanup (cleanup_report_add_group_group, group_name);
+#ifdef SHADOWGRP
+       if (is_shadow_grp) {
+               /* We also need to update /etc/gshadow */
+               add_cleanup (cleanup_report_add_group_gshadow, group_name);
+       }
+#endif
 
+       /*
+        * Create the initial entries for this new group.
+        */
        new_grent (&grp);
 #ifdef SHADOWGRP
        new_sgent (&sgrp);
+       if (is_shadow_grp && pflg) {
+               grp.gr_passwd = SHADOW_PASSWD_STRING;   /* XXX warning: const */
+       }
 #endif                         /* SHADOWGRP */
 
        /*
         * Write out the new group file entry.
         */
-
-       if (!gr_update (&grp)) {
-               fprintf (stderr, _("%s: error adding new group entry\n"),
-                        Prog);
-               fail_exit (E_GRP_UPDATE);
-       }
-#ifdef NDBM
-
-       /*
-        * Update the DBM group file with the new entry as well.
-        */
-
-       if (gr_dbm_present () && !gr_dbm_update (&grp)) {
-               fprintf (stderr, _("%s: cannot add new dbm group entry\n"),
-                        Prog);
-               fail_exit (E_GRP_UPDATE);
+       if (gr_update (&grp) == 0) {
+               fprintf (stderr,
+                        _("%s: failed to prepare the new %s entry '%s'\n"),
+                        Prog, gr_dbname (), grp.gr_name);
+               exit (E_GRP_UPDATE);
        }
-       endgrent ();
-#endif                         /* NDBM */
-
 #ifdef SHADOWGRP
-
        /*
         * Write out the new shadow group entries as well.
         */
-
-       if (is_shadow_grp && !sgr_update (&sgrp)) {
-               fprintf (stderr, _("%s: error adding new group entry\n"),
-                        Prog);
-               fail_exit (E_GRP_UPDATE);
-       }
-#ifdef NDBM
-
-       /*
-        * Update the DBM group file with the new entry as well.
-        */
-
-       if (is_shadow_grp && sg_dbm_present () && !sg_dbm_update (&sgrp)) {
-               fprintf (stderr, _("%s: cannot add new dbm group entry\n"),
-                        Prog);
-               fail_exit (E_GRP_UPDATE);
+       if (is_shadow_grp && (sgr_update (&sgrp) == 0)) {
+               fprintf (stderr,
+                        _("%s: failed to prepare the new %s entry '%s'\n"),
+                        Prog, sgr_dbname (), sgrp.sg_name);
+               exit (E_GRP_UPDATE);
        }
-       endsgent ();
-#endif                         /* NDBM */
 #endif                         /* SHADOWGRP */
-       SYSLOG ((LOG_INFO, "new group: name=%s, gid=%u",
-                group_name, (unsigned int) group_id));
 }
 
 /*
- * find_new_gid - find the next available GID
+ * check_new_name - check the new name for validity
  *
- *     find_new_gid() locates the next highest unused GID in the group
- *     file, or checks the given group ID against the existing ones for
- *     uniqueness.
+ *     check_new_name() insures that the new name doesn't contain any
+ *     illegal characters.
  */
-
-static void find_new_gid (void)
+static void check_new_name (void)
 {
-       const struct group *grp;
-       gid_t gid_min, gid_max;
-
-       gid_min = getdef_unum ("GID_MIN", 100);
-       gid_max = getdef_unum ("GID_MAX", 60000);
+       if (is_valid_group_name (group_name)) {
+               return;
+       }
 
        /*
-        * Start with some GID value if the user didn't provide us with
-        * one already.
+        * All invalid group names land here.
         */
 
-       if (!gflg)
-               group_id = gid_min;
+       fprintf (stderr, _("%s: '%s' is not a valid group name\n"),
+                Prog, group_name);
 
-       /*
-        * Search the entire group file, either looking for this GID (if the
-        * user specified one with -g) or looking for the largest unused
-        * value.
-        */
+       exit (E_BAD_ARG);
+}
 
-#ifdef NO_GETGRENT
-       gr_rewind ();
-       while ((grp = gr_next ())) {
-#else
-       setgrent ();
-       while ((grp = getgrent ())) {
+/*
+ * close_files - close all of the files that were opened
+ *
+ *     close_files() closes all of the files that were opened for this new
+ *     group. This causes any modified entries to be written out.
+ */
+static void close_files (void)
+{
+       /* First, write the changes in the regular group database */
+       if (gr_close () == 0) {
+               fprintf (stderr,
+                        _("%s: failure while writing changes to %s\n"),
+                        Prog, gr_dbname ());
+               exit (E_GRP_UPDATE);
+       }
+#ifdef WITH_AUDIT
+       audit_logger (AUDIT_ADD_GROUP, Prog,
+                     "adding group to /etc/group",
+                     group_name, (unsigned int) group_id,
+                     SHADOW_AUDIT_SUCCESS);
 #endif
-               if (strcmp (group_name, grp->gr_name) == 0) {
-                       if (fflg) {
-                               fail_exit (E_SUCCESS);
-                       }
-                       fprintf (stderr, _("%s: name %s is not unique\n"),
-                                Prog, group_name);
-                       fail_exit (E_NAME_IN_USE);
+       SYSLOG ((LOG_INFO, "group added to %s: name=%s, GID=%u",
+                gr_dbname (), group_name, (unsigned int) group_id));
+       del_cleanup (cleanup_report_add_group_group);
+
+       cleanup_unlock_group (NULL);
+       del_cleanup (cleanup_unlock_group);
+
+       /* Now, write the changes in the shadow database */
+#ifdef SHADOWGRP
+       if (is_shadow_grp) {
+               if (sgr_close () == 0) {
+                       fprintf (stderr,
+                                _("%s: failure while writing changes to %s\n"),
+                                Prog, sgr_dbname ());
+                       exit (E_GRP_UPDATE);
                }
-               if (gflg && group_id == grp->gr_gid) {
-                       if (fflg) {
-                               /* turn off -g and search again */
-                               gflg = 0;
-#ifdef NO_GETGRENT
-                               gr_rewind ();
-#else
-                               setgrent ();
+#ifdef WITH_AUDIT
+               audit_logger (AUDIT_ADD_GROUP, Prog,
+                             "adding group to /etc/gshadow",
+                             group_name, (unsigned int) group_id,
+                             SHADOW_AUDIT_SUCCESS);
 #endif
-                               continue;
-                       }
-                       fprintf (stderr, _("%s: gid %u is not unique\n"),
-                                Prog, (unsigned int) group_id);
-                       fail_exit (E_GID_IN_USE);
-               }
-               if (!gflg && grp->gr_gid >= group_id) {
-                       if (grp->gr_gid > gid_max)
-                               continue;
-                       group_id = grp->gr_gid + 1;
-               }
+               SYSLOG ((LOG_INFO, "group added to %s: name=%s",
+                        sgr_dbname (), group_name));
+               del_cleanup (cleanup_report_add_group_gshadow);
+
+               cleanup_unlock_gshadow (NULL);
+               del_cleanup (cleanup_unlock_gshadow);
        }
-       if (!gflg && group_id == gid_max + 1) {
-               for (group_id = gid_min; group_id < gid_max; group_id++) {
-#ifdef NO_GETGRENT
-                       gr_rewind ();
-                       while ((grp = gr_next ())
-                              && grp->gr_gid != group_id);
-                       if (!grp)
-                               break;
-#else
-                       if (!getgrgid (group_id))
-                               break;
+#endif                         /* SHADOWGRP */
+
+       /* Report success at the system level */
+#ifdef WITH_AUDIT
+       audit_logger (AUDIT_ADD_GROUP, Prog,
+                     "",
+                     group_name, (unsigned int) group_id,
+                     SHADOW_AUDIT_SUCCESS);
 #endif
-               }
-               if (group_id == gid_max) {
-                       fprintf (stderr, _("%s: can't get unique gid\n"),
-                                Prog);
-                       fail_exit (E_GID_IN_USE);
-               }
-       }
+       SYSLOG ((LOG_INFO, "new group: name=%s, GID=%u",
+                group_name, (unsigned int) group_id));
+       del_cleanup (cleanup_report_add_group);
 }
 
 /*
- * check_new_name - check the new name for validity
+ * open_files - lock and open the group files
  *
- *     check_new_name() insures that the new name doesn't contain any
- *     illegal characters.
+ *     open_files() opens the two group files.
  */
-
-static void check_new_name (void)
+static void open_files (void)
 {
-       if (check_group_name (group_name))
-               return;
+       /* First, lock the databases */
+       if (gr_lock () == 0) {
+               fprintf (stderr,
+                        _("%s: cannot lock %s; try again later.\n"),
+                        Prog, gr_dbname ());
+               exit (E_GRP_UPDATE);
+       }
+       add_cleanup (cleanup_unlock_group, NULL);
+
+#ifdef SHADOWGRP
+       if (is_shadow_grp) {
+               if (sgr_lock () == 0) {
+                       fprintf (stderr,
+                                _("%s: cannot lock %s; try again later.\n"),
+                                Prog, sgr_dbname ());
+                       exit (E_GRP_UPDATE);
+               }
+               add_cleanup (cleanup_unlock_gshadow, NULL);
+       }
+#endif                         /* SHADOWGRP */
 
        /*
-        * All invalid group names land here.
+        * Now if the group is not added, it's our fault.
+        * Make sure failures will be reported.
         */
+       add_cleanup (cleanup_report_add_group, group_name);
 
-       fprintf (stderr, _("%s: %s is not a valid group name\n"),
-                Prog, group_name);
+       /* And now open the databases */
+       if (gr_open (O_RDWR) == 0) {
+               fprintf (stderr, _("%s: cannot open %s\n"), Prog, gr_dbname ());
+               SYSLOG ((LOG_WARN, "cannot open %s", gr_dbname ()));
+               exit (E_GRP_UPDATE);
+       }
 
-       exit (E_BAD_ARG);
+#ifdef SHADOWGRP
+       if (is_shadow_grp) {
+               if (sgr_open (O_RDWR) == 0) {
+                       fprintf (stderr,
+                                _("%s: cannot open %s\n"),
+                                Prog, sgr_dbname ());
+                       SYSLOG ((LOG_WARN, "cannot open %s", sgr_dbname ()));
+                       exit (E_GRP_UPDATE);
+               }
+       }
+#endif                         /* SHADOWGRP */
 }
 
 /*
- * process_flags - perform command line argument setting
+ * process_flags - parse the command line options
  *
- *     process_flags() interprets the command line arguments and sets the
- *     values that the user will be created with accordingly. The values
- *     are checked for sanity.
+ *     It will not return if an error is encountered.
  */
-
 static void process_flags (int argc, char **argv)
 {
+       /*
+        * Parse the command line options.
+        */
        char *cp;
-       int arg;
-
-       while ((arg = getopt (argc, argv, "og:O:f")) != EOF) {
-               switch (arg) {
+       int option_index = 0;
+       int c;
+       static struct option long_options[] = {
+               {"force", no_argument, NULL, 'f'},
+               {"gid", required_argument, NULL, 'g'},
+               {"help", no_argument, NULL, 'h'},
+               {"key", required_argument, NULL, 'K'},
+               {"non-unique", no_argument, NULL, 'o'},
+               {"password", required_argument, NULL, 'p'},
+               {"system", no_argument, NULL, 'r'},
+               {NULL, 0, NULL, '\0'}
+       };
+
+       while ((c =
+               getopt_long (argc, argv, "fg:hK:op:r", long_options,
+                            &option_index)) != -1) {
+               switch (c) {
+               case 'f':
+                       /*
+                        * "force" - do nothing, just exit(0), if the
+                        * specified group already exists. With -g, if
+                        * specified gid already exists, choose another
+                        * (unique) gid (turn off -g). Based on the RedHat's
+                        * patch from shadow-utils-970616-9.
+                        */
+                       fflg = true;
+                       break;
                case 'g':
-                       gflg++;
-                       if (!isdigit (optarg[0]))
-                               usage ();
-
-                       group_id = strtoul (optarg, &cp, 10);
-                       if (*cp != '\0') {
+                       gflg = true;
+                       if (   (get_gid (optarg, &group_id) == 0)
+                           || (group_id == (gid_t)-1)) {
                                fprintf (stderr,
-                                        _("%s: invalid group %s\n"), Prog,
-                                        optarg);
-                               fail_exit (E_BAD_ARG);
+                                        _("%s: invalid group ID '%s'\n"),
+                                        Prog, optarg);
+                               exit (E_BAD_ARG);
                        }
                        break;
-               case 'o':
-                       oflg++;
+               case 'h':
+                       usage (E_SUCCESS);
                        break;
-               case 'O':
+               case 'K':
                        /*
-                        * override login.defs defaults (-O name=value)
-                        * example: -O GID_MIN=100 -O GID_MAX=499
-                        * note: -O GID_MIN=10,GID_MAX=499 doesn't work yet
+                        * override login.defs defaults (-K name=value)
+                        * example: -K GID_MIN=100 -K GID_MAX=499
+                        * note: -K GID_MIN=10,GID_MAX=499 doesn't work yet
                         */
                        cp = strchr (optarg, '=');
-                       if (!cp) {
+                       if (NULL == cp) {
                                fprintf (stderr,
-                                        _("%s: -O requires NAME=VALUE\n"),
-                                        Prog);
+                                        _("%s: -K requires KEY=VALUE\n"),
+                                        Prog);
                                exit (E_BAD_ARG);
                        }
                        /* terminate name, point to value */
                        *cp++ = '\0';
-                       if (putdef_str (optarg, cp) < 0)
+                       if (putdef_str (optarg, cp) < 0) {
                                exit (E_BAD_ARG);
+                       }
                        break;
-               case 'f':
-                       /*
-                        * "force" - do nothing, just exit(0), if the
-                        * specified group already exists. With -g, if
-                        * specified gid already exists, choose another
-                        * (unique) gid (turn off -g). Based on the RedHat's
-                        * patch from shadow-utils-970616-9.
-                        */
-                       fflg++;
+               case 'o':
+                       oflg = true;
+                       break;
+               case 'p':
+                       pflg = true;
+                       group_passwd = optarg;
+                       break;
+               case 'r':
+                       rflg = true;
                        break;
                default:
-                       usage ();
+                       usage (E_USAGE);
                }
        }
 
-       if (oflg && !gflg)
-               usage ();
-
-       if (optind != argc - 1)
-               usage ();
+       /*
+        * Check the flags consistency
+        */
+       if (optind != argc - 1) {
+               usage (E_USAGE);
+       }
+       group_name = argv[optind];
 
-       group_name = argv[argc - 1];
-       check_new_name ();
+       check_flags ();
 }
 
 /*
- * close_files - close all of the files that were opened
+ * check_flags - check flags and parameters consistency
  *
- *     close_files() closes all of the files that were opened for this new
- *     group. This causes any modified entries to be written out.
+ *     It will not return if an error is encountered.
  */
-
-static void close_files (void)
+static void check_flags (void)
 {
-       if (!gr_close ()) {
-               fprintf (stderr, _("%s: cannot rewrite group file\n"),
-                        Prog);
-               fail_exit (E_GRP_UPDATE);
-       }
-       gr_unlock ();
-#ifdef SHADOWGRP
-       if (is_shadow_grp && !sgr_close ()) {
-               fprintf (stderr,
-                        _("%s: cannot rewrite shadow group file\n"),
-                        Prog);
-               fail_exit (E_GRP_UPDATE);
+       /* -o does not make sense without -g */
+       if (oflg && !gflg) {
+               usage (E_USAGE);
        }
-       if (is_shadow_grp)
-               sgr_unlock ();
-#endif                         /* SHADOWGRP */
-}
 
-/*
- * open_files - lock and open the group files
- *
- *     open_files() opens the two group files.
- */
+       check_new_name ();
 
-static void open_files (void)
-{
-       if (!gr_lock ()) {
-               fprintf (stderr, _("%s: unable to lock group file\n"),
-                        Prog);
-               exit (E_GRP_UPDATE);
-       }
-       if (!gr_open (O_RDWR)) {
-               fprintf (stderr, _("%s: unable to open group file\n"),
-                        Prog);
-               fail_exit (E_GRP_UPDATE);
-       }
-#ifdef SHADOWGRP
-       if (is_shadow_grp && !sgr_lock ()) {
-               fprintf (stderr,
-                        _("%s: unable to lock shadow group file\n"),
-                        Prog);
-               fail_exit (E_GRP_UPDATE);
-       }
-       if (is_shadow_grp && !sgr_open (O_RDWR)) {
+       /*
+        * Check if the group already exist.
+        */
+       /* local, no need for xgetgrnam */
+       if (getgrnam (group_name) != NULL) {
+               /* The group already exist */
+               if (fflg) {
+                       /* OK, no need to do anything */
+                       exit (E_SUCCESS);
+               }
                fprintf (stderr,
-                        _("%s: unable to open shadow group file\n"),
-                        Prog);
-               fail_exit (E_GRP_UPDATE);
+                        _("%s: group '%s' already exists\n"),
+                        Prog, group_name);
+               exit (E_NAME_IN_USE);
        }
-#endif                         /* SHADOWGRP */
-}
-
-/*
- * fail_exit - exit with an error code after unlocking files
- */
 
-static void fail_exit (int code)
-{
-       (void) gr_unlock ();
-#ifdef SHADOWGRP
-       if (is_shadow_grp)
-               sgr_unlock ();
-#endif
-       exit (code);
+       if (gflg && (getgrgid (group_id) != NULL)) {
+               /* A GID was specified, and a group already exist with that GID
+                *  - either we will use this GID anyway (-o)
+                *  - either we ignore the specified GID and
+                *    we will use another one (-f)
+                *  - either it is a failure
+                */
+               if (oflg) {
+                       /* Continue with this GID */
+               } else if (fflg) {
+                       /* Turn off -g, we can use any GID */
+                       gflg = false;
+               } else {
+                       fprintf (stderr,
+                                _("%s: GID '%lu' already exists\n"),
+                                Prog, (unsigned long int) group_id);
+                       exit (E_GID_IN_USE);
+               }
+       }
 }
 
-#ifdef USE_PAM
-static struct pam_conv conv = {
-       misc_conv,
-       NULL
-};
-#endif                         /* USE_PAM */
-
 /*
- * main - groupadd command
+ * check_perms - check if the caller is allowed to add a group
+ *
+ *     With PAM support, the setuid bit can be set on groupadd to allow
+ *     non-root users to groups.
+ *     Without PAM support, only users who can write in the group databases
+ *     can add groups.
+ *
+ *     It will not return if the user is not allowed.
  */
-
-int main (int argc, char **argv)
+static void check_perms (void)
 {
+#ifdef ACCT_TOOLS_SETUID
 #ifdef USE_PAM
        pam_handle_t *pamh = NULL;
-       struct passwd *pampw;
        int retval;
-#endif
-
-       /*
-        * Get my name so that I can use it to report errors.
-        */
-
-       Prog = Basename (argv[0]);
-
-       setlocale (LC_ALL, "");
-       bindtextdomain (PACKAGE, LOCALEDIR);
-       textdomain (PACKAGE);
-
-       OPENLOG("groupadd");
-
-       process_flags(argc, argv);
-
-#ifdef USE_PAM
-       retval = PAM_SUCCESS;
+       struct passwd *pampw;
 
-       pampw = getpwuid (getuid ());
-       if (pampw == NULL) {
-               retval = PAM_USER_UNKNOWN;
+       pampw = getpwuid (getuid ()); /* local, no need for xgetpwuid */
+       if (NULL == pampw) {
+               fprintf (stderr,
+                        _("%s: Cannot determine your user name.\n"),
+                        Prog);
+               exit (1);
        }
 
-       if (retval == PAM_SUCCESS) {
-               retval =
-                   pam_start ("groupadd", pampw->pw_name, &conv, &pamh);
-       }
+       retval = pam_start ("groupadd", pampw->pw_name, &conv, &pamh);
 
-       if (retval == PAM_SUCCESS) {
+       if (PAM_SUCCESS == retval) {
                retval = pam_authenticate (pamh, 0);
-               if (retval != PAM_SUCCESS) {
-                       pam_end (pamh, retval);
-               }
        }
 
-       if (retval == PAM_SUCCESS) {
+       if (PAM_SUCCESS == retval) {
                retval = pam_acct_mgmt (pamh, 0);
-               if (retval != PAM_SUCCESS) {
-                       pam_end (pamh, retval);
-               }
        }
 
-       if (retval != PAM_SUCCESS) {
-               fprintf (stderr, _("%s: PAM authentication failed\n"),
-                        Prog);
+       if (NULL != pamh) {
+               (void) pam_end (pamh, retval);
+       }
+       if (PAM_SUCCESS != retval) {
+               fprintf (stderr, _("%s: PAM authentication failed\n"), Prog);
                exit (1);
        }
-
-       OPENLOG ("groupadd");
 #endif                         /* USE_PAM */
+#endif                         /* ACCT_TOOLS_SETUID */
+}
 
-#ifdef SHADOWGRP
-       is_shadow_grp = sgr_file_present ();
+/*
+ * main - groupadd command
+ */
+int main (int argc, char **argv)
+{
+#ifdef WITH_AUDIT
+       audit_help_open ();
 #endif
+       atexit (do_cleanups);
 
        /*
-        * The open routines for the DBM files don't use read-write as the
-        * mode, so we have to clue them in.
+        * Get my name so that I can use it to report errors.
         */
+       Prog = Basename (argv[0]);
 
-#ifdef NDBM
-       gr_dbm_mode = O_RDWR;
-#ifdef SHADOWGRP
-       sg_dbm_mode = O_RDWR;
-#endif                         /* SHADOWGRP */
-#endif                         /* NDBM */
+       (void) setlocale (LC_ALL, "");
+       (void) bindtextdomain (PACKAGE, LOCALEDIR);
+       (void) textdomain (PACKAGE);
+
+       OPENLOG ("groupadd");
 
        /*
-        * Start with a quick check to see if the group exists.
+        * Parse the command line options.
         */
+       process_flags (argc, argv);
 
-       if (getgrnam (group_name)) {
-               if (fflg) {
-                       exit (E_SUCCESS);
-               }
-               fprintf (stderr, _("%s: group %s exists\n"), Prog,
-                        group_name);
-               exit (E_NAME_IN_USE);
-       }
+       check_perms ();
+
+#ifdef SHADOWGRP
+       is_shadow_grp = sgr_file_present ();
+#endif
 
        /*
         * Do the hard stuff - open the files, create the group entries,
         * then close and update the files.
         */
-
        open_files ();
 
-       if (!gflg || !oflg)
-               find_new_gid ();
+       if (!gflg) {
+               if (find_new_gid (rflg, &group_id, NULL) < 0) {
+                       exit (E_GID_IN_USE);
+               }
+       }
 
        grp_update ();
-       nscd_flush_cache ("group");
-
        close_files ();
 
-#ifdef USE_PAM
-       if (retval == PAM_SUCCESS) {
-               retval = pam_chauthtok (pamh, 0);
-               if (retval != PAM_SUCCESS) {
-                       pam_end (pamh, retval);
-               }
-       }
-
-       if (retval != PAM_SUCCESS) {
-               fprintf (stderr, _("%s: PAM chauthtok failed\n"), Prog);
-               exit (1);
-       }
+       nscd_flush_cache ("group");
 
-       if (retval == PAM_SUCCESS)
-               pam_end (pamh, PAM_SUCCESS);
-#endif                         /* USE_PAM */
        exit (E_SUCCESS);
-       /* NOT REACHED */
+       /*@notreached@*/
 }
+