Commit a2e343e2 authored by jan.koester's avatar jan.koester
Browse files

groupadd: add groups to /etc/group.yaml

groupadd [-g ID] [-r] [-f] NAME, the counterpart of useradd: -r picks a
free system gid from 999 down, -f succeeds when the group exists (for
package scriptlets such as alsa-lib's audio group).

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent a0a62ab4
Loading
Loading
Loading
Loading
+2 −1
Changes for commands/auth/CMakeLists.txt: 2 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -4,6 +4,7 @@ target_sources(fresh PRIVATE
  ${CMAKE_CURRENT_SOURCE_DIR}/passwd.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/getty.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/useradd.cpp
  ${CMAKE_CURRENT_SOURCE_DIR}/groupadd.cpp
)
target_include_directories(fresh PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})

@@ -31,4 +32,4 @@ install(TARGETS su DESTINATION bin
        PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE
                    WORLD_READ WORLD_EXECUTE SETUID)

set(FRESH_APPLETS ${FRESH_APPLETS} login passwd getty useradd PARENT_SCOPE)
set(FRESH_APPLETS ${FRESH_APPLETS} login passwd getty useradd groupadd PARENT_SCOPE)
+160 −0
Changes for commands/auth/groupadd.cpp: 160 added lines, 0 removed lines.
Original line number Diff line number Diff line
/*******************************************************************************
Copyright (c) 2026, Jan Koester jan.koester@gmx.net
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * 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.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

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 <COPYRIGHT HOLDER> 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.
*******************************************************************************/

// groupadd [-g ID] [-r] [-f] NAME
//
// Adds the group NAME to /etc/group.yaml (systempp's group database). -g
// takes an id in text form (a number, a UUID or a GUID in braces, see
// ids.h); without it the first free classic gid from 1000 up, or with -r
// (a system group) the first free one from 999 down. -f: success if NAME
// already exists (and, if -g's id is taken, a free id instead) -- what
// package scriptlets use (alsa-lib's "audio" group). Root only.

#include <iostream>
#include <string>
#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <unistd.h>
#include <grp.h>
#include <shadow.h>
#include <sys/uid_r.h>

#include "shell.h"
#include "ids.h"

namespace fresh { namespace cmd {

    class GroupaddCommand : public ShellCommand {
    public:
        GroupaddCommand():ShellCommand("groupadd"){}

        static const char *groupPath(){
            const char *p=getenv("SYSTEMPP_GROUP_YAML");
            return p ? p : _PATH_GROUP;
        }

        static bool gidTaken(const gid_r_t &id){ return getgrgid_id_r(&id)!=nullptr; }

        static gid_r_t freeLegacy(bool system){
            if(system){
                for(unsigned v=999;v>=100;--v){
                    gid_r_t id=uid_r_legacy(v);
                    if(!gidTaken(id)) return id;
                }
            }else{
                for(unsigned v=1000;v<60000;++v){
                    gid_r_t id=uid_r_legacy(v);
                    if(!gidTaken(id)) return id;
                }
            }
            return uid_r_none();
        }

        int runCommand(int argc,const char **argv){
            std::string gidSpec,name;
            bool system=false,force=false;
            for(int i=1;i<argc;++i){
                std::string a=argv[i];
                if(a=="-g"){
                    if(i+1>=argc){ std::cerr << "groupadd: -g needs an argument" << std::endl; return 2; }
                    gidSpec=argv[++i];
                }
                else if(a=="-r" || a=="--system") system=true;
                else if(a=="-f" || a=="--force") force=true;
                else if(!a.empty() && a[0]=='-'){
                    std::cerr << "groupadd: unknown option " << a << std::endl;
                    return 2;
                }
                else name=a;
            }
            if(name.empty()){
                std::cerr << "groupadd: usage: groupadd [-g ID] [-r] [-f] NAME" << std::endl;
                return 2;
            }
            if(!ids::isRoot(ids::euid())){
                std::cerr << "groupadd: permission denied" << std::endl;
                return 1;
            }
            if(lckpwdf()!=0){
                std::cerr << "groupadd: cannot lock the account database" << std::endl;
                return 1;
            }
            int rc=add(name,gidSpec,system,force);
            ulckpwdf();
            return rc;
        }

        int add(const std::string &name,const std::string &gidSpec,bool system,bool force){
            if(getgrnam_id_r(name.c_str())){
                if(force) return 0;
                std::cerr << "groupadd: group '" << name << "' already exists" << std::endl;
                return 1;
            }
            gid_r_t gid=uid_r_none();
            if(!gidSpec.empty()){
                if(uid_r_from_str(gidSpec.c_str(),&gid)!=0){
                    std::cerr << "groupadd: invalid id '" << gidSpec << "'" << std::endl;
                    return 1;
                }
                if(gidTaken(gid)){
                    if(!force){
                        std::cerr << "groupadd: id " << ids::str(gid) << " is taken" << std::endl;
                        return 1;
                    }
                    gid=freeLegacy(system);
                }
            }else{
                gid=freeLegacy(system);
            }
            if(gid.type==UID_R_NONE){
                std::cerr << "groupadd: no free gid" << std::endl;
                return 1;
            }
            FILE *f=fopen(groupPath(),"a");
            if(!f){
                std::cerr << "groupadd: " << groupPath() << ": " << strerror(errno) << std::endl;
                return 1;
            }
            char *noMembers[]={nullptr};
            struct group_id_r gr={const_cast<char *>(name.c_str()),const_cast<char *>("x"),gid,noMembers};
            int rc=putgrent_id_r(&gr,f);
            if(fclose(f)!=0) rc=-1;
            if(rc!=0){
                std::cerr << "groupadd: cannot write " << groupPath() << std::endl;
                return 1;
            }
            std::cout << "groupadd: added " << name << " gid=" << ids::str(gid) << std::endl;
            return 0;
        }
    };

    FRESH_REGISTER_COMMAND(GroupaddCommand);

}}