/*
*         OpenPBS (Portable Batch System) v2.3 Software License
*
* Copyright (c) 1999-2000 Veridian Information Solutions, Inc.
* All rights reserved.
*
* ---------------------------------------------------------------------------
* For a license to use or redistribute the OpenPBS software under conditions
* other than those described below, or to purchase support for this software,
* please contact Veridian Systems, PBS Products Department ("Licensor") at:
*
*    www.OpenPBS.org  +1 650 967-4675                  sales@OpenPBS.org
*                        877 902-4PBS (US toll-free)
* ---------------------------------------------------------------------------
*
* This license covers use of the OpenPBS v2.3 software (the "Software") at
* your site or location, and, for certain users, redistribution of the
* Software to other sites and locations.  Use and redistribution of
* OpenPBS v2.3 in source and binary forms, with or without modification,
* are permitted provided that all of the following conditions are met.
* After December 31, 2001, only conditions 3-6 must be met:
*
* 1. Commercial and/or non-commercial use of the Software is permitted
*    provided a current software registration is on file at www.OpenPBS.org.
*    If use of this software contributes to a publication, product, or
*    service, proper attribution must be given; see www.OpenPBS.org/credit.html
*
* 2. Redistribution in any form is only permitted for non-commercial,
*    non-profit purposes.  There can be no charge for the Software or any
*    software incorporating the Software.  Further, there can be no
*    expectation of revenue generated as a consequence of redistributing
*    the Software.
*
* 3. Any Redistribution of source code must retain the above copyright notice
*    and the acknowledgment contained in paragraph 6, this list of conditions
*    and the disclaimer contained in paragraph 7.
*
* 4. Any Redistribution in binary form must reproduce the above copyright
*    notice and the acknowledgment contained in paragraph 6, this list of
*    conditions and the disclaimer contained in paragraph 7 in the
*    documentation and/or other materials provided with the distribution.
*
* 5. Redistributions in any form must be accompanied by information on how to
*    obtain complete source code for the OpenPBS software and any
*    modifications and/or additions to the OpenPBS software.  The source code
*    must either be included in the distribution or be available for no more
*    than the cost of distribution plus a nominal fee, and all modifications
*    and additions to the Software must be freely redistributable by any party
*    (including Licensor) without restriction.
*
* 6. All advertising materials mentioning features or use of the Software must
*    display the following acknowledgment:
*
*     "This product includes software developed by NASA Ames Research Center,
*     Lawrence Livermore National Laboratory, and Veridian Information
*     Solutions, Inc.
*     Visit www.OpenPBS.org for OpenPBS software support,
*     products, and information."
*
* 7. DISCLAIMER OF WARRANTY
*
* THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT
* ARE EXPRESSLY DISCLAIMED.
*
* IN NO EVENT SHALL VERIDIAN CORPORATION, ITS AFFILIATED COMPANIES, OR THE
* U.S. GOVERNMENT OR ANY OF ITS AGENCIES BE LIABLE FOR ANY DIRECT OR 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 license will be governed by the laws of the Commonwealth of Virginia,
* without reference to its choice of law rules.
*/
#include <pbs_config.h>   /* the master config generated by configure */

#include <errno.h>
#include <sys/param.h>
#include "pbs_ifl.h"
#include <stdio.h>
#include <grp.h>
#include <pwd.h>
#include <stdlib.h>
#include <string.h>
#ifdef _CRAY
#include <udb.h>
#endif /* _CRAY */
#include "svrfunc.h" /* get_svr_attr_* */
#include <string>
#include <pthread.h>

#include "server_limits.h"
#include "list_link.h"
#include "attribute.h"
#include "pbs_job.h"
#include "server.h"
#include "pbs_error.h"
#include "svrfunc.h"
#include "log.h"
#include "../lib/Liblog/pbs_log.h"
#include "utils.h"
#include "pbs_ifl.h"

pthread_mutex_t ruserok_mutex;

/* External Data */

extern char *msg_orighost;
extern char  server_host[];



int initialize_ruserok_mutex()
  {
  int rc;
  
  rc = pthread_mutex_init(&ruserok_mutex, NULL);
  return(rc);
  }



bool is_permitted_by_node_submit(
    
  const char *orighost,
  int         logging)

  {
  bool allow_node_submit = false;

  get_svr_attr_b(SRV_ATR_AllowNodeSubmit, &allow_node_submit);

  if ((allow_node_submit == TRUE) &&
      (node_exists(orighost) == true))
    {
    /* job submitted from compute host, access allowed */
    struct array_strings *arst = NULL;

    get_svr_attr_arst(SRV_ATR_node_submit_exceptions, &arst);

    if (arst != NULL)
      {
      // If we find this node's name in the disallowed nodes for submission, forbid it.
      for (int i = 0; i < arst->as_usedptr; i++)
        {
        if (!strcmp(orighost, arst->as_string[i]))
          {
          return(false);
          }
        }
      }

    return(true);
    }

  return(false);
  } // END is_permitted_by_node_submit()


/*
 * geteusernam - get effective user name
 * Get the user name under which the job should be run on this host:
 *   1. from user_list use name with host name that matches this host
 *   2. from user_list use name with no host specification
 *   3. user owner name
 *
 * Returns pointer to the user name
 */

static bool geteusernam(

  job           *pjob,
  pbs_attribute *pattr,
  std::string&   ret_user) /* pointer to User_List pbs_attribute */

  {
  bool  rule3 = false;
  char *hit = 0;
  int  i;

  struct array_strings *parst;
  char *pn;
  char *ptr;
  char  username[PBS_MAXUSER + 1];

  /* search the user-list pbs_attribute */

  if ((pattr->at_flags & ATR_VFLAG_SET) &&
      (parst = pattr->at_val.at_arst))
    {
    for (i = 0;i < parst->as_usedptr;i++)
      {
      pn = parst->as_string[i];
      ptr = strchr(pn, '@');

      if (ptr != NULL)
        {
        /* has host specification */

        if (!strncmp(server_host, ptr + 1, strlen(ptr + 1)))
          {
          hit = pn; /* option 1. */

          break;
          }
        }
      else
        {
        /* wildcard host (null) */
        hit = pn; /* option 2. */
        }
      }
    }

  if (!hit)
    {
    /* default to the job owner ( 3.) */

    hit = pjob->ji_wattr[JOB_ATR_job_owner].at_val.at_str;

    rule3 = true;
    }

  /* copy user name into return buffer, strip off host name */

  get_jobowner(hit, username);

  if (rule3 == true)
    {
    ptr = site_map_user(username, get_variable(pjob, (char *)"PBS_O_HOST"));

    if (ptr != username)
      snprintf(username, sizeof(username), "%s", ptr);
    }

  ret_user = username;
  return true;
  }  /* END geteusernam() */



/*
 * getegroup - get specified effective group name
 * Get the group name under which the job is specified to be run on
 * this host:
 *   1. from group_list use name with host name that matches this host
 *   2. from group_list use name with no host specification
 *   3. NULL, not specified.
 *
 * Returns pointer to the group name or null
 */

bool getegroup(

  job           *pjob,  /* I */
  pbs_attribute *pattr,
  std::string&   ret_group) /* I group_list pbs_attribute */

  {
  char *hit = 0;
  int  i;

  struct array_strings *parst;
  char *pn;
  char *ptr;
  char  groupname[PBS_MAXUSER + 1];

  /* search the group-list pbs_attribute */

  if ((pattr->at_flags & ATR_VFLAG_SET) &&
      (parst = pattr->at_val.at_arst))
    {
    for (i = 0;i < parst->as_usedptr;i++)
      {
      pn = parst->as_string[i];
      ptr = strchr(pn, '@');

      if (ptr != NULL)
        {
        /* has host specification */

        if (!strncmp(server_host, ptr + 1, strlen(ptr + 1)))
          {
          hit = pn; /* option 1. */

          break;
          }
        }
      else
        {
        /* wildcard host (null) */

        hit = pn; /* option 2. */
        }
      }
    }

  if (!hit)   /* nothing specified, return null */
    {
    return false;
    }

  /* copy group name into return buffer, strip off host name */
  /* get_jobowner() works for group as well, same size    */

  get_jobowner(hit, groupname);

  ret_group = groupname;

  return true;
  }  /* END getegroup() */


/*
 * get_user_host_from_user
 *
 * @param user_host  - receives the host name associated with the user.
 * @param user       - user name with or without the host name.
 *
 */

void get_user_host_from_user(
    
  std::string      &user_host,
  const std::string user)

  {
  char  *ptr;
  char  *tmp_name = strdup(user.c_str());

  user_host.clear();
  ptr = strchr(tmp_name, '@');
  if (ptr != NULL)
    {
    ptr++;
    user_host = ptr;
    }

  free(tmp_name);

  }




/*
 * Verifies that the job's user is acceptable
 *
 * @return true if allowed, else false
 */

bool is_user_allowed_to_submit_jobs(

  job        *pjob,    /* I */
  const char *luser,   /* I */
  char       *EMsg,    /* O optional */
  int         logging) /* I */

  {
  char           *orighost;
  std::string     user_host;  /* this is a back up to orighost in case we need FQDN */
  std::string     user(pjob->ji_wattr[JOB_ATR_job_owner].at_val.at_str);
  std::size_t     at_pos = user.find('@');
  int             rc = PBSE_NONE;
  bool            ProxyAllowed = false;
  bool            ProxyRequested = false;
  bool            HostAllowed = false;
  char           *dptr;

  char            log_buf[256];

#ifdef MUNGE_AUTH
  char            uh[PBS_MAXUSER + PBS_MAXHOSTNAME + 2];
#endif
    
  if (LOGLEVEL >= 10)
    {
    sprintf(log_buf, "job id: %s - luser: %s", pjob->ji_qs.ji_jobid, luser);
    log_event(PBSEVENT_JOB, PBS_EVENTCLASS_JOB, __func__, log_buf);
    }
    
  if (EMsg != NULL)
    EMsg[0] = '\0';

  get_user_host_from_user(user_host, user);

  if (at_pos != std::string::npos)
    user.erase(at_pos);

  orighost = get_variable(pjob, ATTR_pbs_o_host);

  if (orighost == NULL)
    {
    /* access denied */

    log_event(PBSEVENT_JOB, PBS_EVENTCLASS_JOB, pjob->ji_qs.ji_jobid, msg_orighost);

    if (EMsg != NULL)
      strcpy(EMsg, "source host not specified");

    return(false);
    }

  /* check to see if we are allowing a proxy user to submit the job */
  if ((server.sv_attr[SRV_ATR_AllowProxyUser].at_flags & ATR_VFLAG_SET) && \
      (server.sv_attr[SRV_ATR_AllowProxyUser].at_val.at_bool == true))
    {
    ProxyAllowed = true;
    }

  /* If the users are different and allow_proxy_user is set we have a proxy submission */
  if (strcmp(user.c_str(), luser) != 0)
    {
    ProxyRequested = true;
    }

  if (!strcmp(orighost, server_host) && !strcmp(user.c_str(), luser))
    {
    /* submitting from server host, access allowed */

    if ((ProxyRequested == false) || (ProxyAllowed == true))
      {
      return(true);
      }

    /* host is fine, must validate proxy via ruserok() */

    HostAllowed = true;
    }

  /* make short host name */
  if ((dptr = strchr(orighost, '.')) != NULL)
    {
    *dptr = '\0';
    }

  if ((HostAllowed == false) &&
      (is_permitted_by_node_submit(orighost, logging)))
    {
    /* job submitted from compute host, access allowed */
    if (dptr != NULL)
      *dptr = '.';

    if ((ProxyRequested == false) ||
        (ProxyAllowed == true))
      {
      return(true);
      }

    /* host is fine, must validate proxy via ruserok() */

    HostAllowed = false;
    }

  if ((HostAllowed == false) &&
      (server.sv_attr[SRV_ATR_SubmitHosts].at_flags & ATR_VFLAG_SET))
    {
    struct array_strings *submithosts = NULL;
    char                 *testhost;
    int                   hostnum = 0;

    submithosts = server.sv_attr[SRV_ATR_SubmitHosts].at_val.at_arst;

    for (hostnum = 0;hostnum < submithosts->as_usedptr;hostnum++)
      {
      testhost = submithosts->as_string[hostnum];

      int cmpRet = strcasecmp(testhost, orighost);

      if ((cmpRet != 0) &&
          (dptr != NULL))
        {
        *dptr = '.';
        cmpRet = strcasecmp(testhost, orighost);
        *dptr = '\0';
        }

      if (cmpRet == 0)
        {
        /* job submitted from host found in trusted submit host list, access allowed */

        if (dptr != NULL)
          *dptr = '.';

        if ((ProxyRequested == false) ||
            (ProxyAllowed == true))
          {
          return(true);
          }

        /* host is fine, must validate proxy via ruserok() */

        HostAllowed = true;

        break;
        }
      }  /* END for (hostnum) */
    }    /* END if (SRV_ATR_SubmitHosts) */

  // Check limited acls
  if (limited_acls.is_authorized(orighost, user) == true)
    return(true);
  else if (limited_acls.is_authorized(user_host.c_str(), user) == true)
    return(true);

  if (dptr != NULL)
    *dptr = '.';

#ifdef MUNGE_AUTH
  sprintf(uh, "%s@%s", user.c_str(), orighost);
  rc = acl_check(&server.sv_attr[SRV_ATR_authusers], uh, ACL_User_Host);
  if (rc <= 0)
    {
    /* rc == 0 means we did not find a match.
       this is a failure */
    if (EMsg != NULL)
      {
      snprintf(EMsg, 1024, "could not authorize user %s from %s",
        user.c_str(), orighost);
      }
    rc = -1; /* -1 is what set_jobexid is expecting for a failure*/
    }
  else
    {
    /*SUCCESS*/
    rc = 0; /* the call to ruserok below was in the code first. ruserok returns 
               0 on success but acl_check returns a positive value on success. 
               We set rc to 0 to be consistent with the original ruserok functionality */
    }
#else

  /* ruserok is the last chance the incoming submission can work. 
     check to see if the user hosts combination is allowed */
  /* ruserok is not thread safe. mutex it */
  pthread_mutex_lock(&ruserok_mutex);
  rc = ruserok(orighost, 0, user.c_str(), luser);
  pthread_mutex_unlock(&ruserok_mutex);

  if (rc != 0)
    {
    /* Test rc so as to not fill this message in the case of success, since other
     * callers might not fill this message in the case of their errors and
     * very misleading error message will go into the logs.
     */
    if (EMsg != NULL)
      snprintf(EMsg, 1024, "ruserok failed validating %s/%s from %s",
        user.c_str(), luser, orighost);
    rc = -1;
    }
#endif

#ifdef sun
  /* broken Sun ruserok() sets process so it appears to be owned */
  /* by the luser, change it back for cosmetic reasons           */

  setuid(0);
#endif /* sun */

  return(rc == 0);
  } // END is_user_allowed_to_submit_jobs()



/*
 * set_jobexid - validate and set the execution user (JOB_ATR_euser) and
 * execution group (JOB_ATR_egroup) job attributes.
 *
 * 1.  Get the execution user name.
 * 1a. Get the corresponding password entry.
 * 1b. Uid of 0 (superuser) is not allowed, might cause root-rot
 * 1c. If job owner name is not being used, does the job owner have
 *     permission to map to the execution name?
 * 1d. Set JOB_ATR_euser to the execution user name.
 * 2.  Get the execution group name.
 * 2a. Is the execution user name a member of this group?
 * 2b. Set JOB_ATR_egroup to the execution group name.
 *
 * Returns: 0 if set, non-zero error number if any error
 */

int set_jobexid(

  job           *pjob,    /* I */
  pbs_attribute *attrry,  /* I */
  char          *EMsg)    /* O (optional,minsize=1024) */

  {
  int             addflags = 0;
  pbs_attribute  *pattr;
  char          **pmem;

  char           *grp_buf = NULL;
  struct group   *gpent;
  std::string    puser = "";
  char           *at;
  char           *usr_at_host = NULL;
  int             len;


  struct passwd  *pwent = NULL;
  char           *buf = NULL;
  std::string      pgrpn = "";
  char            gname[PBS_MAXGRPN + 1];
#ifdef _CRAY

  struct udb     *pudb;
#endif

  char            tmpLine[1024 + 1];
  char            log_buf[LOCAL_LOG_BUF_SIZE];

  bool            disable_id_check = false;
  bool            CheckID = true;  
  
  if (EMsg != NULL)
    EMsg[0] = '\0';

  /* use the passed User_List if set, may be a newly modified one     */
  /* if not set, fall back to the job's actual User_List, may be same */
  if (get_svr_attr_b(SRV_ATR_DisableServerIdCheck, &disable_id_check) == PBSE_NONE)
    CheckID = !disable_id_check;

  if (CheckID == false)
    {
    /* NOTE: use owner, not userlist - should this be changed? */
    /* Yes, changed 10/17/2007 */

    if (pjob->ji_wattr[JOB_ATR_job_owner].at_val.at_str != NULL)
      {
      /* start of change to use userlist instead of owner 10/17/2007 */

      if ((attrry + JOB_ATR_userlst)->at_flags & ATR_VFLAG_SET)
        pattr = attrry + JOB_ATR_userlst;
      else
        pattr = &pjob->ji_wattr[JOB_ATR_userlst];

      if (pjob->ji_wattr[JOB_ATR_proxy_user].at_flags & ATR_VFLAG_SET)
        {
        puser = pjob->ji_wattr[JOB_ATR_proxy_user].at_val.at_str;

        /* set the job's owner as the new user, appending @host if
         * the job's owner has that */
        at = strchr(pjob->ji_wattr[JOB_ATR_job_owner].at_val.at_str,'@');
        len = strlen(puser.c_str()) + 1;
        if (at != NULL)
          {
          len += strlen(at);
          usr_at_host = (char *)calloc(len, sizeof(char));
          snprintf(usr_at_host,len,"%s%s",
            puser.c_str(),
            at);
          }
        else
          {
          usr_at_host = (char *)calloc(len, sizeof(char));

          snprintf(usr_at_host,len,"%s",
            puser.c_str());
          }

        free(pjob->ji_wattr[JOB_ATR_job_owner].at_val.at_str);
        pjob->ji_wattr[JOB_ATR_job_owner].at_val.at_str = usr_at_host;
        }
      else if (geteusernam(pjob, pattr,puser) == false)
        {
        if (EMsg != NULL)
          snprintf(EMsg, 1024, "cannot locate user name in job");

        return(PBSE_BADUSER);
        }

      sprintf(tmpLine, "%s", puser.c_str());

      /* end of change to use userlist instead of owner 10/17/2007 */
      }
    else
      {
      strcpy(tmpLine, "???");
      }
    }  /* END if (CheckID == false) */
  else
    {
    int perm;

    if ((attrry + JOB_ATR_userlst)->at_flags & ATR_VFLAG_SET)
      pattr = attrry + JOB_ATR_userlst;
    else
      pattr = &pjob->ji_wattr[JOB_ATR_userlst];

    if (geteusernam(pjob, pattr,puser) == false)
      {
      if (EMsg != NULL)
        snprintf(EMsg, 1024, "cannot locate user name in job");

      return(PBSE_BADUSER);
      }

    pwent = getpwnam_ext(&buf, (char *)puser.c_str());

    perm = svr_get_privilege((char *)puser.c_str(),get_variable(pjob,(char *)"PBS_O_HOST"));

    if (pwent == NULL)
      {
      snprintf(log_buf,sizeof(log_buf),
        "User %s does not exist in server password file\n",
        puser.c_str());

      log_err(errno, __func__, log_buf);

      if (EMsg != NULL)
        snprintf(EMsg,1024,"%s",log_buf);

      return(PBSE_BADUSER);
      }

    if ((pwent->pw_uid == 0) ||
        (perm & ATR_DFLAG_MGWR))
      {
      struct array_strings *pas = NULL;
      get_svr_attr_arst(SRV_ATR_AclRoot, &pas);

      /* add check here for virtual user */
      if (pjob->ji_wattr[JOB_ATR_proxy_user].at_flags & ATR_VFLAG_SET)
        {
        puser = pjob->ji_wattr[JOB_ATR_proxy_user].at_val.at_str;

        free_pwnam(pwent, buf);
        pwent = getpwnam_ext(&buf, (char *)puser.c_str());

        if (pwent == NULL)
          {
          snprintf(log_buf,sizeof(log_buf),
            "User %s does not exist in server password file\n",
            puser.c_str());

          log_err(errno, __func__, log_buf);

          if (EMsg != NULL)
            snprintf(EMsg,1024,"%s",log_buf);

          return(PBSE_BADUSER);
          }

        /* set the job's owner as the new user */
        at = strchr(pjob->ji_wattr[JOB_ATR_job_owner].at_val.at_str,'@');
        len = puser.length() + 1;
        if (at != NULL)
          {
          len += strlen(at);
          usr_at_host = (char *)calloc(len, sizeof(char));
          snprintf(usr_at_host,len,"%s%s",
            puser.c_str(),
            at);
          }
        else
          {
          usr_at_host = (char *)calloc(len, sizeof(char));

          snprintf(usr_at_host,len,"%s",
            puser.c_str());
          }

        free(pjob->ji_wattr[JOB_ATR_job_owner].at_val.at_str);
        pjob->ji_wattr[JOB_ATR_job_owner].at_val.at_str = usr_at_host;
        }
      else if (get_svr_attr_arst(SRV_ATR_AclRoot, &pas) == PBSE_NONE)
        {
        if (acl_check_my_array_string(pas, pjob->ji_wattr[JOB_ATR_job_owner].at_val.at_str, ACL_User) == 0)
          {
          if (EMsg != NULL)
            snprintf(EMsg, 1024, "root user %s fails ACL check",
                     puser.c_str());

          free_pwnam(pwent, buf);
          return(PBSE_BADUSER); /* root not allowed */
          }
        }
      else if (pwent->pw_uid == 0)
        {
        if (EMsg != NULL)
          snprintf(EMsg, 1024, "root user %s not allowed",
                   puser.c_str());
          
        free_pwnam(pwent, buf);
        return(PBSE_BADUSER); /* root not allowed */
        }
      }    /* END if (pwent->pw_uid == 0) */
    else if (pjob->ji_wattr[JOB_ATR_proxy_user].at_flags & ATR_VFLAG_SET)
      {
      /* cannot submit a proxy job if not root or a manager */
      if (EMsg != NULL)
        {
        snprintf(EMsg, 1024,
          "User '%s' is attempting to submit a proxy job for user '%s' but is not a manager",
          puser.c_str(),
          pjob->ji_wattr[JOB_ATR_proxy_user].at_val.at_str);
        }

      snprintf(log_buf, 1024,
        "User '%s' is attempting to submit a proxy job for user '%s' but is not a manager",
        puser.c_str(),
        pjob->ji_wattr[JOB_ATR_proxy_user].at_val.at_str);
      log_err(PBSE_BADUSER, __func__, log_buf);

      free_pwnam(pwent, buf);
      return(PBSE_BADUSER);
      }

    if (is_user_allowed_to_submit_jobs(pjob, puser.c_str(), EMsg, LOGLEVEL) == false)
      {
      free_pwnam(pwent, buf);
      return(PBSE_BADUSER);
      }

    snprintf(tmpLine, sizeof(tmpLine), "%s", puser.c_str());
    }  /* END else (CheckID == false) */

  pattr = attrry + JOB_ATR_euser;

  job_attr_def[JOB_ATR_euser].at_free(pattr);

  job_attr_def[JOB_ATR_euser].at_decode(pattr, NULL, NULL, tmpLine, 0);

#ifdef _CRAY

  /* on cray check UDB (user data base) for permission to batch it */

  if ((pwent != NULL) && (puser.length() != 0))
    {
    pudb = getudbuid(pwent->pw_uid);

    endudb();

    if (pudb == UDB_NULL)
      {
      if (EMsg != NULL)
        snprintf(EMsg, 1024, "user %s not located in user data base",
                 puser.c_str());

      free_pwnam(pwent, buf);
      return(PBSE_BADUSER);
      }

    if (pudb->ue_permbits & (PERMBITS_NOBATCH | PERMBITS_RESTRICTED))
      {
      free_pwnam(pwent, buf);
      return(PBSE_QACESS);
      }

    /* if account (qsub -A) not specified, set default from UDB */

    pattr = attrry + JOB_ATR_account;

    if ((pattr->at_flags & ATR_VFLAG_SET) == 0)
      {
      job_attr_def[JOB_ATR_account].at_decode(
        pattr,
        NULL,
        NULL,
        (char *)acid2nam(pudb->ue_acids[0]));
      }
    }    /* END if ((pwent != NULL) && (puser != NULL)) */

#endif /* _CRAY */

  /*
   * now figure out the group name under which the job should execute
   * PBS requires that each group have an entry in the group file,
   * see the admin guide for the reason why...
   *
   * use the passed group_list if set, may be a newly modified one
   * if not set, fall back to the job's actual group_list, may be same
   */

  if ((attrry + JOB_ATR_grouplst)->at_flags & ATR_VFLAG_SET)
    pattr = attrry + JOB_ATR_grouplst;
  else
    pattr = &pjob->ji_wattr[JOB_ATR_grouplst];

  /* extract user-specified egroup if it exists */

  if (!getegroup(pjob, pattr,pgrpn))
    {
    free_pwnam(pwent, buf);
    pwent = NULL;
    if ((pwent != NULL) || ((pwent = getpwnam_ext(&buf, (char *)puser.c_str())) != NULL))
      {
      /* egroup not specified - use user login group */

      gpent = getgrgid_ext(&grp_buf, pwent->pw_gid);

      if (gpent != NULL)
        {
        pgrpn = gpent->gr_name;           /* use group name */
        free(grp_buf);
        free(gpent);
        }
      else
        {
        sprintf(gname, "%ld",
                (long)pwent->pw_gid);

        pgrpn = gname;            /* turn gid into string */
        }
      }
    else if (CheckID == false)
      {
      strcpy(gname, "???");

      pgrpn = gname;
      }
    else
      {
      log_err(errno, __func__, "getpwnam failed");

      if (EMsg != NULL)
        snprintf(EMsg, 1024, "user does not exist in server password file");

      free_pwnam(pwent, buf);
      return(PBSE_BADUSER);
      }

    /*
     * setting the DEFAULT flag is a "kludgy" way to keep MOM from
     * having to do an unneeded look up of the group file.
     * We needed to have JOB_ATR_egroup set for the server but
     * MOM only wants it if it is not the login group, so there!
     */

    addflags = ATR_VFLAG_DEFLT;
    }  /* END if ((pgrpn = getegroup(pjob,pattr))) */
  else if (CheckID == false)
    {
    /* egroup specified - do not validate group within server */

    /* NO-OP */
    }
  else
    {
    /* user specified a group, group must exist and either */
    /* must be user's primary group or the user must be in it */

    gpent = getgrnam_ext(&grp_buf, (char *)pgrpn.c_str());

    if (gpent == NULL)
      {
      if (EMsg != NULL)
        snprintf(EMsg, 1024, "cannot locate group %s in server group file",
          pgrpn.c_str());

      free_pwnam(pwent, buf);
      return(PBSE_BADGRP);  /* no such group */
      }

    if (gpent->gr_gid != pwent->pw_gid)
      {
      /* not primary group */

      pmem = gpent->gr_mem;

      while (*pmem != NULL)
        {
        if (!strcmp(puser.c_str(), *pmem))
          break;

        ++pmem;
        }

      if (*pmem == NULL)
        {
        /* requested group not allowed */
        snprintf(log_buf,sizeof(log_buf),
          "user %s is not a member of group %s in server password file",
          puser.c_str(),
          pgrpn.c_str());

        log_err(-1, __func__, log_buf);

        if (EMsg != NULL)
          snprintf(EMsg, 1024, "%s",log_buf);

        free_pwnam(pwent, buf);
        free_grname(gpent, grp_buf);
        return(PBSE_BADGRP); /* user not in group */
        }
      }
    free_grname(gpent, grp_buf);
    }    /* END if ((pgrpn = getegroup(pjob,pattr))) */

  /* set new group */

  pattr = attrry + JOB_ATR_egroup;

  job_attr_def[JOB_ATR_egroup].at_free(pattr);

  job_attr_def[JOB_ATR_egroup].at_decode(pattr, NULL, NULL, pgrpn.c_str(), 0);

  pattr->at_flags |= addflags;

  /* SUCCESS */
  free_pwnam(pwent, buf);
  return(PBSE_NONE);

  }  /* END set_jobexid() */



/*
 * node_exception_check()
 *
 */

int node_exception_check(

  pbs_attribute *pattr,
  void          *pobject,
  int            actmode)

  {
  struct array_strings *pstr;

  if (actmode == ATR_ACTION_FREE)
    {
    return(PBSE_NONE); /* no checking on free */
    }

  pstr = pattr->at_val.at_arst;

  for (int i = 0; pstr != NULL && i < pstr->as_usedptr; i++)
    {
    if (node_exists(pstr->as_string[i]) == false)
      {
      return(PBSE_UNKNODE);
      }
    }

  return(PBSE_NONE);
  } // END node_exception_check()



/* END geteusernam.c */

