Exemple #1
0
static int
rmJobBufFilesPid(struct jobCard *jp)
{
    static char fname[] = "rmJobBufFilesPid()";
    int pid;

    if ((pid = fork()) < 0) {
	ls_syslog(LOG_ERR, I18N_JOB_FAIL_S_M, fname,
	    lsb_jobid2str(jp->jobSpecs.jobId), "fork");
	return (pid);
    }

    if (pid)
	return (pid);



    closeBatchSocket();
    putEnv(LS_EXEC_T, "END");

    if (postJobSetup(jp) < 0) {
	ls_syslog(LOG_ERR, I18N_JOB_FAIL_S,
	    fname,
	    lsb_jobid2str(jp->jobSpecs.jobId),
	    "postSetupUser");
	exit(-1);
    }

    rmJobBufFiles(jp);
    exit(0);
}
Exemple #2
0
static int
cleanupMigJob(struct jobCard *jp)
{
    static char fname[] = "cleanupMigJob()";
    int pid;


    unlockHosts (jp, jp->jobSpecs.numToHosts);

    if (!jp->jobSpecs.postCmd || jp->jobSpecs.postCmd[0] == '\0')
        return 0;


    if ((pid = fork()) < 0) {
	ls_syslog(LOG_ERR, I18N_JOB_FAIL_S_M, fname,
	    lsb_jobid2str(jp->jobSpecs.jobId), "fork");
        lsb_merr2(_i18n_msg_get(ls_catd , NL_SETN, 700,
	    "Unable to fork a child to run the queue's post-exec command for job <%s>.  Please run <%s> manually if necessary.\n"), /* catgets 700 */
	    lsb_jobid2str(jp->jobSpecs.jobId),
	    jp->jobSpecs.postCmd);
	return (pid);
    }

    if (pid)
	return (pid);



    closeBatchSocket();
    putEnv(LS_EXEC_T, "END");

    if (postJobSetup(jp) == -1) {
	ls_syslog(LOG_ERR, I18N_JOB_FAIL_S, fname,
	    lsb_jobid2str(jp->jobSpecs.jobId), "postJobSetup");
	lsb_merr2(_i18n_msg_get(ls_catd , NL_SETN, 701,
	    "Unable to setup the environment for job <%s> to run the queue's post exec.  Please run <%s> manually if necessary.\n"), /* catgets 701 */
	    lsb_jobid2str(jp->jobSpecs.jobId),
	    jp->jobSpecs.postCmd);
	exit(-1);
    }

    runQPost(jp);
    exit(0);
}
Exemple #3
0
int
main(int argc, char **argv)
{
    static char fname[] = "res/main";
    int nready;
    int maxfd;
    int i;
    char *sp;
    char *pathname = NULL;
    int didSomething = 0;
    char exbuf;

    time_t thisPeriodic, lastPeriodic = 0, timeDiff;


    fd_set rm, wm, em;

    int sbdPty = FALSE;
    char *sbdClHost = NULL;
    ushort sbdClPort = 0;
    char **sbdArgv = NULL;
    int selectError = 0;


    _i18n_init(I18N_CAT_RES);

    saveDaemonDir_(argv[0]);



    for (i=1; i<argc; i++) {
      if (strcmp(argv[i], "-d") == 0 && argv[i+1] != NULL) {
         pathname = argv[i+1];
         putEnv("LSF_ENVDIR",pathname);
         break;
      }
    }

    if (pathname == NULL) {
	if ((pathname = getenv("LSF_ENVDIR")) == NULL)
	    pathname = LSETCDIR;
    }


    if (argc > 1) {
        if (!strcmp(argv[1],"-V")) {
            fputs(_LS_VERSION_, stderr);
            exit(0);
        }
    }



    if ((ls_readconfenv(resConfParams, NULL) < 0) ||
        (initenv_(resParams, pathname) < 0) ) {
        if ((sp = getenv("LSF_LOGDIR")) != NULL)
            resParams[LSF_LOGDIR].paramValue = sp;
        ls_openlog("res", resParams[LSF_LOGDIR].paramValue, (debug > 1),
                   resParams[LSF_LOG_MASK].paramValue);
        ls_syslog(LOG_ERR, I18N_FUNC_S_FAIL_MM, fname, "initenv_",
            pathname);
        ls_syslog(LOG_ERR, I18N_Exiting);
        exit(-1);
    }



    restart_argc = argc;
    restart_argv = argv;
    for (i=1; i<argc; i++) {
	if (strcmp(argv[i], "-d") == 0 && argv[i+1] != NULL) {
	    pathname = argv[i+1];
	    i++;
	    continue;
	}

	if (strcmp(argv[i], "-1") == 0) {
	    debug = 1;
	    continue;
	}

	if (strcmp(argv[i], "-2") == 0) {
	    debug = 2;
	    continue;
	}


	if (strcmp(argv[i], "-PTY_FIX") == 0) {
	    printf("PTY_FIX");
	    exit(0);
	}


	if ( (strcmp(argv[i], "-j") == 0) && (argv[i+1] != NULL) ) {
	    lsbJobStarter = argv[++i];
	    continue;
	}

	if (strcmp(argv[i], "-P") == 0) {
	    sbdPty = TRUE;
	    continue;
	}

	if (strcmp(argv[i], "-i") == 0) {
	    sbdFlags |= SBD_FLAG_STDIN;
	    continue;
	}

	if (strcmp(argv[i], "-o") == 0) {
	    sbdFlags |= SBD_FLAG_STDOUT;
	    continue;
	}

	if (strcmp(argv[i], "-e") == 0) {
	    sbdFlags |= SBD_FLAG_STDERR;
	    continue;
	}

	if (strcmp(argv[i], "-m") == 0 && argv[i+1] != NULL) {
	    sbdClHost = argv[i+1];
	    i++;
	    sbdMode = TRUE;
	    continue;
	}

	if (strcmp(argv[i], "-p") == 0 && argv[i+1] != NULL) {
	    sbdClPort = atoi(argv[i+1]);
	    i++;
	    sbdMode = TRUE;
	    continue;
	}


	if (argv[i][0] != '-') {
	    sbdMode = TRUE;
	    sbdArgv = argv + i;
	    break;
	}

        usage(argv[0]);
    }

    if (sbdMode) {

	if (sbdClHost == NULL || sbdArgv == NULL) {
	    usage(argv[0]);
	    exit(-1);
	}
	if (sbdClPort) {
	    sbdFlags |= SBD_FLAG_TERM;
	} else {

	    sbdFlags |= SBD_FLAG_STDIN | SBD_FLAG_STDOUT | SBD_FLAG_STDERR;
	}
    } else {


	if (debug < 2)
	    for (i = sysconf(_SC_OPEN_MAX) ; i >= 0 ; i--)
		close(i);
    }


    if (resParams[LSF_SERVERDIR].paramValue == NULL) {
	ls_openlog("res", resParams[LSF_LOGDIR].paramValue, (debug > 1),
				   resParams[LSF_LOG_MASK].paramValue);
	ls_syslog(LOG_ERR, _i18n_msg_get(ls_catd , NL_SETN, 5001,
	    "LSF_SERVERDIR not defined in %s/lsf.conf: %M; res exiting"), /* catgets 5001 */
	    pathname);
	resExit_(-1);
    }


    if (! debug && resParams[LSF_RES_DEBUG].paramValue != NULL) {
	debug = atoi(resParams[LSF_RES_DEBUG].paramValue);
	if (debug <= 0)
	    debug = 1;
    }


    getLogClass_(resParams[LSF_DEBUG_RES].paramValue,
                 resParams[LSF_TIME_RES].paramValue);


    if (getuid() == 0 && debug) {
        if (sbdMode)  {
	   debug = 0;
	} else {
          ls_openlog("res", resParams[LSF_LOGDIR].paramValue, FALSE,
		   resParams[LSF_LOG_MASK].paramValue);
          ls_syslog(LOG_ERR, I18N(5005,"Root cannot run RES in debug mode ... exiting."));/*catgets 5005 */
	   exit(-1);
	}
    }

    if (debug > 1)
	ls_openlog("res", resParams[LSF_LOGDIR].paramValue, TRUE, "LOG_DEBUG");
    else {
 	ls_openlog("res", resParams[LSF_LOGDIR].paramValue, FALSE,
		   resParams[LSF_LOG_MASK].paramValue);
    }
    if (logclass & (LC_TRACE | LC_HANG))
        ls_syslog(LOG_DEBUG, "%s: logclass=%x", fname, logclass);

    ls_syslog(LOG_DEBUG, "%s: LSF_SERVERDIR=%s", fname, resParams[LSF_SERVERDIR].paramValue);



    init_res();
    initSignals();

    periodic(0);



    if (sbdMode) {
	lsbJobStart(sbdArgv, sbdClPort, sbdClHost, sbdPty);
    }

    maxfd = FD_SETSIZE;


    for (;;) {
        struct timeval *timep;
        struct timeval timeout;
loop:
        didSomething = 0;

        for (i = 0; i < child_cnt; i++) {
            if (children[i]->backClnPtr == NULL
                 && !FD_IS_VALID(conn2NIOS.sock.fd)
                 && children[i]->running == 0) {
                delete_child (children[i]);
            }
        }

	if (logclass & LC_TRACE) {
	    ls_syslog(LOG_DEBUG,"\
%s: %s Res child_res=<%d> child_go=<%d> child_cnt=<%d> client_cnt=<%d>",
		      fname, ((child_res) ? "Application" : "Root") ,
		      child_res, child_go, child_cnt, client_cnt);
            if (child_cnt == 1 && children != NULL && children[0] != NULL) {
                dumpChild(children[0], 1, "in main()");
            }
	}

        if (child_res && child_go && child_cnt == 0 && client_cnt == 0)  {


            if (debug > 1)
		printf (" \n Child <%d> Retired! \n", (int)getpid());

	    if (logclass & LC_TRACE) {
		ls_syslog(LOG_DEBUG,"\
%s: Application Res is exiting.....", fname);
	    }


	    millisleep_(5000);


	    if (sbdMode) {

		close(1);
		close(2);
		exit(lastChildExitStatus);
            }
	    resExit_(EXIT_NO_ERROR);
        }
void GRASS_EXPORT QgsGrass::init( void )
{
  // Warning!!!
  // G_set_error_routine() once called from plugin
  // is not valid in provider -> call it always

  // Set error function
  G_set_error_routine( &error_routine );

  if ( initialized )
    return;

  QSettings settings;

  // Is it active mode ?
  if ( getenv( "GISRC" ) )
  {
    active = true;
    // Store default values
    defaultGisdbase = G_gisdbase();
    defaultLocation = G_location();
    defaultMapset = G_mapset();
  }
  else
  {
    active = false;
  }

  // Don't use GISRC file and read/write GRASS variables (from location G_VAR_GISRC) to memory only.
  G_set_gisrc_mode( G_GISRC_MODE_MEMORY );

  // Init GRASS libraries (required)
  G_no_gisinit();  // Doesn't check write permissions for mapset compare to G_gisinit("libgrass++");

  // I think that mask should not be used in QGIS as it can only confuses people,
  // anyway, I don't think anybody is using MASK
  G_suppress_masking();

  // Set program name
  G_set_program_name( "QGIS" );

  // Require GISBASE to be set. This should point to the location of
  // the GRASS installation. The GRASS libraries use it to know
  // where to look for things.

  // Look first to see if GISBASE env var is already set.
  // This is set when QGIS is run from within GRASS
  // or when set explicitly by the user.
  // This value should always take precedence.
#if WIN32
  QString gisBase = getenv( "WINGISBASE" ) ? getenv( "WINGISBASE" ) : getenv( "GISBASE" );
  gisBase = shortPath( gisBase );
#else
  QString gisBase = getenv( "GISBASE" );
#endif
  QgsDebugMsg( QString( "GRASS gisBase from GISBASE env var is: %1" ).arg( gisBase ) );
  if ( !isValidGrassBaseDir( gisBase ) )
  {
    // Look for gisbase in QSettings
    gisBase = settings.value( "/GRASS/gisbase", "" ).toString();
    QgsDebugMsg( QString( "GRASS gisBase from QSettings is: %1" ).arg( gisBase ) );
  }

  if ( !isValidGrassBaseDir( gisBase ) )
  {
    // Erase gisbase from settings because it does not exists
    settings.setValue( "/GRASS/gisbase", "" );

#ifdef WIN32
    // Use the applicationDirPath()/grass
    gisBase = shortPath( QCoreApplication::applicationDirPath() + "/grass" );
    QgsDebugMsg( QString( "GRASS gisBase = %1" ).arg( gisBase ) );
#else
    // Use the location specified --with-grass during configure
    gisBase = GRASS_BASE;
    QgsDebugMsg( QString( "GRASS gisBase from configure is: %1" ).arg( gisBase ) );
#endif
  }

  bool userGisbase = false;
  bool valid = false;
  while ( !( valid = isValidGrassBaseDir( gisBase ) ) )
  {

    // ask user if he wants to specify GISBASE
    QMessageBox::StandardButton res = QMessageBox::warning( 0, QObject::tr( "GRASS plugin" ),
                                      QObject::tr( "QGIS couldn't find your GRASS installation.\n"
                                                   "Would you like to specify path (GISBASE) to your GRASS installation?" ),
                                      QMessageBox::Ok | QMessageBox::Cancel );

    if ( res != QMessageBox::Ok )
    {
      userGisbase = false;
      break;
    }

    // XXX Need to subclass this and add explantory message above to left side
    userGisbase = true;
    // For Mac, GISBASE folder may be inside GRASS bundle. Use Qt file dialog
    // since Mac native dialog doesn't allow user to browse inside bundles.
    gisBase = QFileDialog::getExistingDirectory(
                0, QObject::tr( "Choose GRASS installation path (GISBASE)" ), gisBase,
                QFileDialog::DontUseNativeDialog );
    if ( gisBase == QString::null )
    {
      // User pressed cancel. No GRASS for you!
      userGisbase = false;
      break;
    }
#if defined(WIN32)
    gisBase = shortPath( gisBase );
#endif
  }

  if ( !valid )
  {
    // warn user
    QMessageBox::information( 0, QObject::tr( "GRASS plugin" ),
                              QObject::tr( "GRASS data won't be available if GISBASE is not specified." ) );
  }

  if ( userGisbase )
  {
    settings.setValue( "/GRASS/gisbase", gisBase );
  }

  QgsDebugMsg( QString( "Valid GRASS gisBase is: %1" ).arg( gisBase ) );
  putEnv( "GISBASE", gisBase );

  // Add path to GRASS modules
#ifdef WIN32
  QString sep = ";";
#else
  QString sep = ":";
#endif
  QString path = gisBase + "/bin";
  path.append( sep + gisBase + "/scripts" );
  path.append( sep +  QgsApplication::pkgDataPath() + "/grass/scripts/" );

  // On windows the GRASS libraries are in
  // QgsApplication::prefixPath(), we have to add them
  // to PATH to enable running of GRASS modules
  // and database drivers
#ifdef WIN32
  // It seems that QgsApplication::prefixPath()
  // is not initialized at this point
  path.append( sep + shortPath( QCoreApplication::applicationDirPath() ) );

  // Add path to MSYS bin
  // Warning: MSYS sh.exe will translate this path to '/bin'
  if ( QFileInfo( QCoreApplication::applicationDirPath() + "/msys/bin/" ).isDir() )
    path.append( sep + shortPath( QCoreApplication::applicationDirPath() + "/msys/bin/" ) );
#endif

  QString p = getenv( "PATH" );
  path.append( sep + p );

  QgsDebugMsg( QString( "set PATH: %1" ).arg( path ) );
  putEnv( "PATH", path );

  // Set PYTHONPATH
  QString pythonpath = gisBase + "/etc/python";
  QString pp = getenv( "PYTHONPATH" );
  pythonpath.append( sep + pp );
  QgsDebugMsg( QString( "set PYTHONPATH: %1" ).arg( pythonpath ) );
  putEnv( "PYTHONPATH", pythonpath );

  // Set GRASS_PAGER if not set, it is necessary for some
  // modules printing to terminal, e.g. g.list
  // We use 'cat' because 'more' is not present in MSYS (Win)
  // and it doesn't work well in built in shell (Unix/Mac)
  // and 'less' is not user friendly (for example user must press
  // 'q' to quit which is definitely difficult for normal user)
  // Also scroling can be don in scrollable window in both
  // MSYS terminal and built in shell.
  if ( !getenv( "GRASS_PAGER" ) )
  {
    QString pager;
    QStringList pagers;
    //pagers << "more" << "less" << "cat"; // se notes above
    pagers << "cat";

    for ( int i = 0; i < pagers.size(); i++ )
    {
      int state;

      QProcess p;
      p.start( pagers.at( i ) );
      p.waitForStarted();
      state = p.state();
      p.write( "\004" ); // Ctrl-D
      p.closeWriteChannel();
      p.waitForFinished( 1000 );
      p.kill();

      if ( state == QProcess::Running )
      {
        pager = pagers.at( i );
        break;
      }
    }

    if ( pager.length() > 0 )
    {
      putEnv( "GRASS_PAGER", pager );
    }
  }

  initialized = 1;
}
QString GRASS_EXPORT QgsGrass::openMapset( QString gisdbase, QString location, QString mapset )
{
  QgsDebugMsg( QString( "gisdbase = %1" ).arg( gisdbase.toUtf8().constData() ) );
  QgsDebugMsg( QString( "location = %1" ).arg( location.toUtf8().constData() ) );
  QgsDebugMsg( QString( "mapset = %1" ).arg( mapset.toUtf8().constData() ) );

  QString mapsetPath = gisdbase + "/" + location + "/" + mapset;

  // Check if the mapset is in use
  QString gisBase = getenv( "GISBASE" );
  if ( gisBase.isEmpty() ) return QObject::tr( "GISBASE is not set." );

  QFileInfo fi( mapsetPath + "/WIND" );
  if ( !fi.exists() )
  {
    return QObject::tr( "%1 is not a GRASS mapset." ).arg( mapsetPath );
  }
  QString lock = mapsetPath + "/.gislock";

#ifndef _MSC_VER
  int pid = getpid();
#else
  int pid = GetCurrentProcessId();
#endif

  QgsDebugMsg( QString( "pid = %1" ).arg( pid ) );

#ifndef Q_OS_WIN
  QFile lockFile( lock );
  QProcess *process = new QProcess();
  QString lockProgram( gisBase + "/etc/lock" );

  QgsDebugMsg( QString( "pid = %1" ).arg( pid ) );

  process->start( lockProgram, QStringList() << lock << QString::number( pid ) );
  if ( !process->waitForStarted() )
  {
    delete process;
    return QObject::tr( "Cannot start %1/etc/lock" ).arg( gisBase );
  }

  process->waitForFinished( -1 );

  int status = process->exitStatus();
  QgsDebugMsg( QString( "status = %1" ).arg( status ) );
  delete process;

  if ( status > 0 )
    return QObject::tr( "Mapset is already in use." );
#endif // !WIN32

  // Create temporary directory
  QFileInfo info( mapsetPath );
  QString user = info.owner();

  mTmp = QDir::tempPath() + "/grass6-" + user + "-" + QString::number( pid );
  QDir dir( mTmp );
  if ( dir.exists() )
  {
    QFileInfo dirInfo( mTmp );
    if ( !dirInfo.isWritable() )
    {
#ifndef Q_OS_WIN
      lockFile.remove();
#endif
      return QObject::tr( "Temporary directory %1 exists but is not writable" ).arg( mTmp );
    }
  }
  else if ( !dir.mkdir( mTmp ) )
  {
#ifndef Q_OS_WIN
    lockFile.remove();
#endif
    return QObject::tr( "Cannot create temporary directory %1" ).arg( mTmp );
  }

  // Create GISRC file
  QString globalGisrc =  QDir::home().path() + "/.grassrc6";
  mGisrc = mTmp + "/gisrc";

  QgsDebugMsg( QString( "globalGisrc = %1" ).arg( globalGisrc ) );
  QgsDebugMsg( QString( "mGisrc = %1" ).arg( mGisrc ) );

  QFile out( mGisrc );
  if ( !out.open( QIODevice::WriteOnly ) )
  {
#ifndef Q_OS_WIN
    lockFile.remove();
#endif
    return QObject::tr( "Cannot create %1" ).arg( mGisrc );
  }
  QTextStream stream( &out );

  QFile in( globalGisrc );
  QString line;
  bool guiSet = false;
  char buf[1000];
  if ( in.open( QIODevice::ReadOnly ) )
  {
    while ( in.readLine( buf, 1000 ) != -1 )
    {
      line = buf;
      if ( line.contains( "GISDBASE:" ) ||
           line.contains( "LOCATION_NAME:" ) ||
           line.contains( "MAPSET:" ) )
      {
        continue;
      }
      if ( line.contains( "GRASS_GUI:" ) ) guiSet = true;
      stream << line;
    }
    in.close();
  }
  line = "GISDBASE: " + gisdbase + "\n";
  stream << line;
  line = "LOCATION_NAME: " + location + "\n";
  stream << line;
  line = "MAPSET: " + mapset + "\n";
  stream << line;
  if ( !guiSet )
  {
    stream << "GRASS_GUI: wxpython\n";
  }

  out.close();

  // Set GISRC environment variable

  /* _Correct_ putenv() implementation is not making copy! */
  putEnv( "GISRC", mGisrc );

  // Reinitialize GRASS
  G__setenv( "GISRC", mGisrc.toUtf8().data() );
#if defined(WIN32)
  G__setenv( "GISDBASE", shortPath( gisdbase ).toLocal8Bit().data() );
#else
  G__setenv( "GISDBASE", gisdbase.toUtf8().data() );
#endif
  G__setenv( "LOCATION_NAME", location.toLocal8Bit().data() );
  G__setenv( "MAPSET", mapset.toLocal8Bit().data() );
  defaultGisdbase = gisdbase;
  defaultLocation = location;
  defaultMapset = mapset;

  active = true;

#ifndef Q_OS_WIN
  // Close old mapset
  if ( mMapsetLock.length() > 0 )
  {
    QFile file( mMapsetLock );
    file.remove();
  }
#endif

  mMapsetLock = lock;

  return NULL;
}
Exemple #6
0
static Bool
StartClient (
    struct verify_info	*verify,
    struct display	*d,
    int			*pidp,
    char		*name,
    char		*passwd)
{
    char	**f, *home;
    char	*failsafeArgv[2];
    int	pid;
#ifdef HAS_SETUSERCONTEXT
    struct passwd* pwd;
#endif
#ifdef USE_PAM 
    pam_handle_t *pamh = thepamh();
#endif

    if (verify->argv) {
	Debug ("StartSession %s: ", verify->argv[0]);
	for (f = verify->argv; *f; f++)
		Debug ("%s ", *f);
	Debug ("; ");
    }
    if (verify->userEnviron) {
	for (f = verify->userEnviron; *f; f++)
		Debug ("%s ", *f);
	Debug ("\n");
    }
#ifdef USE_PAM
    if (pamh) pam_open_session(pamh, 0);
#endif    
    switch (pid = fork ()) {
    case 0:
	CleanUpChild ();
#ifdef XDMCP
	/* The chooser socket is not closed by CleanUpChild() */
	DestroyWellKnownSockets();
#endif

	/* Do system-dependent login setup here */

#ifdef USE_PAM
	/* pass in environment variables set by libpam and modules it called */
	if (pamh) {
	    long i;
	    char **pam_env = pam_getenvlist(pamh);
	    for(i = 0; pam_env && pam_env[i]; i++) {
		verify->userEnviron = putEnv(pam_env[i], verify->userEnviron);
	    }
	}
#endif


#ifndef AIXV3
#ifndef HAS_SETUSERCONTEXT
	if (setgid(verify->gid) < 0)
	{
	    LogError("setgid %d (user \"%s\") failed, errno=%d\n",
		     verify->gid, name, errno);
	    return (0);
	}
#if defined(BSD) && (BSD >= 199103)
	if (setlogin(name) < 0)
	{
	    LogError("setlogin for \"%s\" failed, errno=%d", name, errno);
	    return(0);
	}
#endif
#ifndef QNX4
	if (initgroups(name, verify->gid) < 0)
	{
	    LogError("initgroups for \"%s\" failed, errno=%d\n", name, errno);
	    return (0);
	}
#endif   /* QNX4 doesn't support multi-groups, no initgroups() */
#ifdef USE_PAM
	if (thepamh()) {
	    pam_setcred(thepamh(), PAM_ESTABLISH_CRED);
	}
#endif
	if (setuid(verify->uid) < 0)
	{
	    LogError("setuid %d (user \"%s\") failed, errno=%d\n",
		     verify->uid, name, errno);
	    return (0);
	}
#else /* HAS_SETUSERCONTEXT */
	/*
	 * Set the user's credentials: uid, gid, groups,
	 * environment variables, resource limits, and umask.
	 */
	pwd = getpwnam(name);
	if (pwd)
	{
	    if (setusercontext(NULL, pwd, pwd->pw_uid, LOGIN_SETALL) < 0)
	    {
		LogError("setusercontext for \"%s\" failed, errno=%d\n", name,
		    errno);
		return (0);
	    }
	    endpwent();
	}
	else
	{
	    LogError("getpwnam for \"%s\" failed, errno=%d\n", name, errno);
	    return (0);
	}
#endif /* HAS_SETUSERCONTEXT */
#else /* AIXV3 */
	/*
	 * Set the user's credentials: uid, gid, groups,
	 * audit classes, user limits, and umask.
	 */
	if (setpcred(name, NULL) == -1)
	{
	    LogError("setpcred for \"%s\" failed, errno=%d\n", name, errno);
	    return (0);
	}
#endif /* AIXV3 */

	/*
	 * for user-based authorization schemes,
	 * use the password to get the user's credentials.
	 */
#ifdef SECURE_RPC
	/* do like "keylogin" program */
	{
	    char    netname[MAXNETNAMELEN+1], secretkey[HEXKEYBYTES+1];
	    int	    nameret, keyret;
	    int	    len;
	    int     key_set_ok = 0;

	    nameret = getnetname (netname);
	    Debug ("User netname: %s\n", netname);
	    len = strlen (passwd);
	    if (len > 8)
		bzero (passwd + 8, len - 8);
	    keyret = getsecretkey(netname,secretkey,passwd);
	    Debug ("getsecretkey returns %d, key length %d\n",
		    keyret, strlen (secretkey));
	    /* is there a key, and do we have the right password? */
	    if (keyret == 1)
	    {
		if (*secretkey)
		{
		    keyret = key_setsecret(secretkey);
		    Debug ("key_setsecret returns %d\n", keyret);
		    if (keyret == -1)
			LogError ("failed to set NIS secret key\n");
		    else
			key_set_ok = 1;
		}
		else
		{
		    /* found a key, but couldn't interpret it */
		    LogError ("password incorrect for NIS principal \"%s\"\n",
			      nameret ? netname : name);
		}
	    }
	    if (!key_set_ok)
	    {
		/* remove SUN-DES-1 from authorizations list */
		int i, j;
		for (i = 0; i < d->authNum; i++)
		{
		    if (d->authorizations[i]->name_length == 9 &&
			memcmp(d->authorizations[i]->name, "SUN-DES-1", 9) == 0)
		    {
			for (j = i+1; j < d->authNum; j++)
			    d->authorizations[j-1] = d->authorizations[j];
			d->authNum--;
			break;
		    }
		}
	    }
	    bzero(secretkey, strlen(secretkey));
	}
#endif
#ifdef K5AUTH
	/* do like "kinit" program */
	{
	    int i, j;
	    int result;
	    extern char *Krb5CCacheName();

	    result = Krb5Init(name, passwd, d);
	    if (result == 0) {
		/* point session clients at the Kerberos credentials cache */
		verify->userEnviron =
		    setEnv(verify->userEnviron,
			   "KRB5CCNAME", Krb5CCacheName(d->name));
	    } else {
		for (i = 0; i < d->authNum; i++)
		{
		    if (d->authorizations[i]->name_length == 14 &&
			memcmp(d->authorizations[i]->name, "MIT-KERBEROS-5", 14) == 0)
		    {
			/* remove Kerberos from authorizations list */
			for (j = i+1; j < d->authNum; j++)
			    d->authorizations[j-1] = d->authorizations[j];
			d->authNum--;
			break;
		    }
		}
	    }
	}
#endif /* K5AUTH */
	bzero(passwd, strlen(passwd));
	SetUserAuthorization (d, verify);
	home = getEnv (verify->userEnviron, "HOME");
	if (home)
	    if (chdir (home) == -1) {
		LogError ("user \"%s\": cannot chdir to home \"%s\" (err %d), using \"/\"\n",
			  getEnv (verify->userEnviron, "USER"), home, errno);
		chdir ("/");
		verify->userEnviron = setEnv(verify->userEnviron, "HOME", "/");
	    }
	if (verify->argv) {
		Debug ("executing session %s\n", verify->argv[0]);
		execute (verify->argv, verify->userEnviron);
		LogError ("Session \"%s\" execution failed (err %d)\n", verify->argv[0], errno);
	} else {
		LogError ("Session has no command/arguments\n");
	}
	failsafeArgv[0] = d->failsafeClient;
	failsafeArgv[1] = 0;
	execute (failsafeArgv, verify->userEnviron);
	exit (1);
    case -1:
	bzero(passwd, strlen(passwd));
	Debug ("StartSession, fork failed\n");
	LogError ("can't start session on \"%s\", fork failed, errno=%d\n",
		  d->name, errno);
	return 0;
    default:
	bzero(passwd, strlen(passwd));
	Debug ("StartSession, fork succeeded %d\n", pid);
	*pidp = pid;
	return 1;
    }
}
Exemple #7
0
int
ctrlSbdDebug(struct debugReq  *pdebug)
{
    static char   fname[]="ctrlSbdDebug()";
    int           opCode;
    int           level;
    int           newClass;
    int           options;
    char          logFileName[MAXLSFNAMELEN];
    char          lsfLogDir[MAXPATHLEN];
    char          *dir;
    char          dynDbgEnv[MAXPATHLEN];

    memset(logFileName, 0, sizeof(logFileName));
    memset(lsfLogDir, 0, sizeof(lsfLogDir));

    opCode = pdebug->opCode;
    level = pdebug->level;
    newClass = pdebug->logClass;
    options = pdebug->options;

    if (pdebug->logFileName[0] != '\0') {
        if (((dir = strrchr(pdebug->logFileName,'/')) != NULL) ||
            ((dir = strrchr(pdebug->logFileName,'\\')) != NULL)) {
            dir++;
            ls_strcat(logFileName, sizeof(logFileName), dir);
            *(--dir) = '\0';
            ls_strcat(lsfLogDir, sizeof(lsfLogDir), pdebug->logFileName);
        }
        else {
            ls_strcat(logFileName, sizeof(logFileName), pdebug->logFileName);
            if (daemonParams[LSF_LOGDIR].paramValue
                && *(daemonParams[LSF_LOGDIR].paramValue)) {
                ls_strcat(lsfLogDir, sizeof(lsfLogDir),
                          daemonParams[LSF_LOGDIR].paramValue);
            }
            else {
                lsfLogDir[0] = '\0';
            }
        }
        ls_strcat(logFileName, sizeof(logFileName), ".sbatchd");
    }
    else {
  	ls_strcat(logFileName, sizeof(logFileName), "sbatchd");
        if (daemonParams[LSF_LOGDIR].paramValue
            && *(daemonParams[LSF_LOGDIR].paramValue)) {
            ls_strcat(lsfLogDir, sizeof(lsfLogDir),
                      daemonParams[LSF_LOGDIR].paramValue);
        } else {
            lsfLogDir[0] = '\0';
        }
    }

    if (options==1) {
        struct config_param *plp;
        for (plp = daemonParams; plp->paramName != NULL; plp++) {
            if (plp->paramValue != NULL)
                FREEUP(plp->paramValue);
        }

        if (initenv_(daemonParams, env_dir) < 0){
            ls_openlog("sbatchd", daemonParams[LSF_LOGDIR].paramValue,
                       (debug > 1), daemonParams[LSF_LOG_MASK].paramValue);
  	    ls_syslog(LOG_ERR, I18N_FUNC_FAIL_MM, fname, "initenv_");
            die(SLAVE_FATAL);
            return -1;
        }

        getLogClass_(daemonParams[LSB_DEBUG_SBD].paramValue,
                     daemonParams[LSB_TIME_SBD].paramValue);
        closelog();
        if (debug > 1)
            ls_openlog("sbatchd", daemonParams[LSF_LOGDIR].paramValue, TRUE,
                       daemonParams[LSF_LOG_MASK].paramValue);
        else
            ls_openlog("sbatchd", daemonParams[LSF_LOGDIR].paramValue, FALSE,
                       daemonParams[LSF_LOG_MASK].paramValue);

        if (logclass & LC_TRACE)
            ls_syslog(LOG_DEBUG, "%s: logclass=%x", fname, logclass);

        cleanDynDbgEnv();

        return(LSBE_NO_ERROR);
    }

    if (opCode==SBD_DEBUG) {
        putMaskLevel(level, &(daemonParams[LSF_LOG_MASK].paramValue));

        if (newClass>=0) {
            logclass = newClass;

            sprintf(dynDbgEnv, "%d", logclass);
            putEnv("DYN_DBG_LOGCLASS", dynDbgEnv);
        }

        if ( pdebug->level>=0 ){
            closelog();
            if (debug > 1)
                ls_openlog(logFileName, lsfLogDir, TRUE,
                           daemonParams[LSF_LOG_MASK].paramValue);
            else
                ls_openlog(logFileName, lsfLogDir, FALSE,
                           daemonParams[LSF_LOG_MASK].paramValue);

            putEnv("DYN_DBG_LOGDIR", lsfLogDir);
            putEnv("DYN_DBG_LOGFILENAME", logFileName);
            sprintf(dynDbgEnv, "%d", pdebug->level);
            putEnv("DYN_DBG_LOGLEVEL", dynDbgEnv);
        }
    }
    else if (opCode == SBD_TIMING) {
        if (level>=0)
 	    timinglevel = level;
        if (pdebug->logFileName[0] != '\0') {
            if (debug > 1)
                ls_openlog(logFileName, lsfLogDir,
                           TRUE, daemonParams[LSF_LOG_MASK].paramValue);
            else
                ls_openlog(logFileName, lsfLogDir,
                           FALSE, daemonParams[LSF_LOG_MASK].paramValue);
        }
    }
    else {
        ls_perror("No this debug command!\n");
        return -1;
    }
    return (LSBE_NO_ERROR);
}
Exemple #8
0
int
startClient( volatile int *pid )
{
	const char *home, *sessargs, *desksess;
	char **env, *xma;
	char **argv, *fname, *str;
#ifdef USE_PAM
	char ** volatile pam_env;
# ifndef HAVE_PAM_GETENVLIST
	char **saved_env;
# endif
	int pretc;
#else
# ifdef _AIX
	char *msg;
	char **theenv;
	extern char **newenv; /* from libs.a, this is set up by setpenv */
# endif
#endif
#ifdef HAVE_SETUSERCONTEXT
	extern char **environ;
#endif
	char *failsafeArgv[2];
	char *buf, *buf2;
	int i;

	if (strCmp( dmrcuser, curuser )) {
		if (curdmrc) { free( curdmrc ); curdmrc = 0; }
		if (dmrcuser) { free( dmrcuser ); dmrcuser = 0; }
	}

#if defined(USE_PAM) || defined(_AIX)
	if (!(p = getpwnam( curuser ))) {
		logError( "getpwnam(%s) failed.\n", curuser );
	  pError:
		displayStr( V_MSG_ERR, 0 );
		return 0;
	}
#endif

#ifndef USE_PAM
# ifdef _AIX
	msg = NULL;
	loginsuccess( curuser, hostname, tty, &msg );
	if (msg) {
		debug( "loginsuccess() - %s\n", msg );
		free( (void *)msg );
	}
# else /* _AIX */
#  if defined(KERBEROS) && defined(AFS)
	if (krbtkfile[0] != '\0') {
		if (k_hasafs()) {
			int fail = 0;
			if (k_setpag() == -1) {
				logError( "setpag() for %s failed\n", curuser );
				fail = 1;
			}
			if ((ret = k_afsklog( NULL, NULL )) != KSUCCESS) {
				logError( "AFS Warning: %s\n", krb_get_err_text( ret ) );
				fail = 1;
			}
			if (fail)
				displayMsg( V_MSG_ERR,
				            "Warning: Problems during Kerberos4/AFS setup." );
		}
	}
#  endif /* KERBEROS && AFS */
# endif /* _AIX */
#endif	/* !PAM */

	curuid = p->pw_uid;
	curgid = p->pw_gid;

	env = baseEnv( curuser );
	xma = 0;
	strApp( &xma, "method=", curtype, (char *)0 );
	if (td_setup)
		strApp( &xma, ",auto", (char *)0 );
	if (xma) {
		env = setEnv( env, "XDM_MANAGED", xma );
		free( xma );
	}
	if (td->autoLock && cursource == PWSRC_AUTOLOGIN)
		env = setEnv( env, "DESKTOP_LOCKED", "true" );
	env = setEnv( env, "PATH", curuid ? td->userPath : td->systemPath );
	env = setEnv( env, "SHELL", p->pw_shell );
	env = setEnv( env, "HOME", p->pw_dir );
#if !defined(USE_PAM) && !defined(_AIX) && defined(KERBEROS)
	if (krbtkfile[0] != '\0')
		env = setEnv( env, "KRBTKFILE", krbtkfile );
#endif
	userEnviron = inheritEnv( env, envvars );
	env = systemEnv( curuser );
	systemEnviron = setEnv( env, "HOME", p->pw_dir );
	debug( "user environment:\n%[|''>'\n's"
	       "system environment:\n%[|''>'\n's"
	       "end of environments\n",
	       userEnviron,
	       systemEnviron );

	/*
	 * for user-based authorization schemes,
	 * add the user to the server's allowed "hosts" list.
	 */
	for (i = 0; i < td->authNum; i++) {
#ifdef SECURE_RPC
		if (td->authorizations[i]->name_length == 9 &&
		    !memcmp( td->authorizations[i]->name, "SUN-DES-1", 9 ))
		{
			XHostAddress addr;
			char netname[MAXNETNAMELEN+1];
			char domainname[MAXNETNAMELEN+1];

			getdomainname( domainname, sizeof(domainname) );
			user2netname( netname, curuid, domainname );
			addr.family = FamilyNetname;
			addr.length = strlen( netname );
			addr.address = netname;
			XAddHost( dpy, &addr );
		}
#endif
#ifdef K5AUTH
		if (td->authorizations[i]->name_length == 14 &&
		    !memcmp( td->authorizations[i]->name, "MIT-KERBEROS-5", 14 ))
		{
			/* Update server's auth file with user-specific info.
			 * Don't need to AddHost because X server will do that
			 * automatically when it reads the cache we are about
			 * to point it at.
			 */
			XauDisposeAuth( td->authorizations[i] );
			td->authorizations[i] =
				krb5GetAuthFor( 14, "MIT-KERBEROS-5", td->name );
			saveServerAuthorizations( td, td->authorizations, td->authNum );
		}
#endif
	}

	if (*dmrcDir)
		mergeSessionArgs( TRUE );

	debug( "now starting the session\n" );

#ifdef USE_PAM

# ifdef HAVE_SETUSERCONTEXT
	if (setusercontext( lc, p, p->pw_uid, LOGIN_SETGROUP )) {
		logError( "setusercontext(groups) for %s failed: %m\n",
		          curuser );
		goto pError;
	}
# else
	if (!setGid( curuser, curgid ))
		goto pError;
# endif

# ifndef HAVE_PAM_GETENVLIST
	if (!(pam_env = initStrArr( 0 ))) {
		resetGids();
		goto pError;
	}
	saved_env = environ;
	environ = pam_env;
# endif
	removeCreds = 1; /* set it first - i don't trust PAM's rollback */
	pretc = pam_setcred( pamh, 0 );
	reInitErrorLog();
# ifndef HAVE_PAM_GETENVLIST
	pam_env = environ;
	environ = saved_env;
# endif
# ifdef HAVE_INITGROUPS
	/* This seems to be a strange place for it, but do it:
	   - after the initial groups are set
	   - after pam_setcred might have set something, even in the error case
	   - before pam_setcred(DELETE_CRED) might need it
	 */
	if (!saveGids())
		goto pError;
# endif
	if (pretc != PAM_SUCCESS) {
		logError( "pam_setcred() for %s failed: %s\n",
		          curuser, pam_strerror( pamh, pretc ) );
		resetGids();
		return 0;
	}

	removeSession = 1; /* set it first - same as above */
	pretc = pam_open_session( pamh, 0 );
	reInitErrorLog();
	if (pretc != PAM_SUCCESS) {
		logError( "pam_open_session() for %s failed: %s\n",
		          curuser, pam_strerror( pamh, pretc ) );
		resetGids();
		return 0;
	}

	/* we don't want sessreg and the startup/reset scripts run with user
	   credentials. unfortunately, we can reset only the gids. */
	resetGids();

# define D_LOGIN_SETGROUP LOGIN_SETGROUP
#else /* USE_PAM */
# define D_LOGIN_SETGROUP 0
#endif /* USE_PAM */

	removeAuth = 1;
	chownCtrl( &td->ctrl, curuid );
	endpwent();
#if !defined(USE_PAM) && defined(USESHADOW) && !defined(_AIX)
	endspent();
#endif
	ctltalk.pipe = &ctlpipe;
	ASPrintf( &buf, "sub-daemon for display %s", td->name );
	ASPrintf( &buf2, "client for display %s", td->name );
	switch (gFork( &ctlpipe, buf, buf2, 0, 0, mstrtalk.pipe, pid )) {
	case 0:

		gCloseOnExec( ctltalk.pipe );
		if (Setjmp( ctltalk.errjmp ))
			exit( 1 );

		gCloseOnExec( mstrtalk.pipe );
		if (Setjmp( mstrtalk.errjmp ))
			goto cError;

#ifndef NOXDMTITLE
		setproctitle( "%s'", td->name );
#endif
		strApp( &prog, " '", (char *)0 );
		reInitErrorLog();

		setsid();

		sessreg( td, getpid(), curuser, curuid );

		/* We do this here, as we want to have the session as parent. */
		switch (source( systemEnviron, td->startup, td_setup )) {
		case 0:
			break;
		case wcCompose( 0, 0, 127 ):
			goto cError;
		default: /* Explicit failure => message already displayed. */
			logError( "Startup script returned non-zero exit code\n" );
			exit( 1 );
		}

	/* Memory leaks are ok here as we exec() soon. */

#if defined(USE_PAM) || !defined(_AIX)

# ifdef USE_PAM
		/* pass in environment variables set by libpam and modules it called */
#  ifdef HAVE_PAM_GETENVLIST
		pam_env = pam_getenvlist( pamh );
		reInitErrorLog();
#  endif
		if (pam_env)
			for (; *pam_env; pam_env++)
				userEnviron = putEnv( *pam_env, userEnviron );
# endif

# ifdef HAVE_SETLOGIN
		if (setlogin( curuser ) < 0) {
			logError( "setlogin for %s failed: %m\n", curuser );
			goto cError;
		}
#  define D_LOGIN_SETLOGIN LOGIN_SETLOGIN
# else
#  define D_LOGIN_SETLOGIN 0
# endif

# if defined(USE_PAM) && defined(HAVE_INITGROUPS)
		if (!restoreGids())
			goto cError;
# endif

# ifndef HAVE_SETUSERCONTEXT

#  ifdef USE_PAM
		if (!setUid( curuser, curuid ))
			goto cError;
#  else
		if (!setUser( curuser, curuid, curgid ))
			goto cError;
#  endif

# else /* !HAVE_SETUSERCONTEXT */

		/*
		 * Destroy environment.
		 * We need to do this before setusercontext() because that may
		 * set or reset some environment variables.
		 */
		if (!(environ = initStrArr( 0 )))
			goto cError;

		/*
		 * Set the user's credentials: uid, gid, groups,
		 * environment variables, resource limits, and umask.
		 */
		if (setusercontext( lc, p, p->pw_uid,
		        LOGIN_SETALL & ~(D_LOGIN_SETGROUP|D_LOGIN_SETLOGIN) ) < 0)
		{
			logError( "setusercontext for %s failed: %m\n", curuser );
			goto cError;
		}

		for (i = 0; environ[i]; i++)
			userEnviron = putEnv( environ[i], userEnviron );

# endif /* !HAVE_SETUSERCONTEXT */

#else /* PAM || !_AIX */
		/*
		 * Set the user's credentials: uid, gid, groups,
		 * audit classes, user limits, and umask.
		 */
		if (setpcred( curuser, NULL ) == -1) {
			logError( "setpcred for %s failed: %m\n", curuser );
			goto cError;
		}

		/*
		 * Set the users process environment. Store protected variables and
		 * obtain updated user environment list. This call will initialize
		 * global 'newenv'.
		 */
		if (setpenv( curuser, PENV_INIT | PENV_ARGV | PENV_NOEXEC,
		             userEnviron, NULL ) != 0)
		{
			logError( "Cannot set %s's process environment\n", curuser );
			goto cError;
		}
		userEnviron = newenv;

#endif /* _AIX */

		/*
		 * for user-based authorization schemes,
		 * use the password to get the user's credentials.
		 */
#ifdef SECURE_RPC
		/* do like "keylogin" program */
		if (!curpass[0])
			logInfo( "No password for NIS provided.\n" );
		else {
			char netname[MAXNETNAMELEN+1], secretkey[HEXKEYBYTES+1];
			int nameret, keyret;
			int len;
			int key_set_ok = 0;
			struct key_netstarg netst;

			nameret = getnetname( netname );
			debug( "user netname: %s\n", netname );
			len = strlen( curpass );
			if (len > 8)
				bzero( curpass + 8, len - 8 );
			keyret = getsecretkey( netname, secretkey, curpass );
			debug( "getsecretkey returns %d, key length %d\n",
			       keyret, strlen( secretkey ) );
			netst.st_netname = netname;
			memcpy( netst.st_priv_key, secretkey, HEXKEYBYTES );
			memset( netst.st_pub_key, 0, HEXKEYBYTES );
			if (key_setnet( &netst ) < 0)
				debug( "Could not set secret key.\n" );
			/* is there a key, and do we have the right password? */
			if (keyret == 1) {
				if (*secretkey) {
					keyret = key_setsecret( secretkey );
					debug( "key_setsecret returns %d\n", keyret );
					if (keyret == -1)
						logError( "Failed to set NIS secret key\n" );
					else
						key_set_ok = 1;
				} else {
					/* found a key, but couldn't interpret it */
					logError( "Password incorrect for NIS principal %s\n",
					          nameret ? netname : curuser );
				}
			}
			if (!key_set_ok)
				nukeAuth( 9, "SUN-DES-1" );
			bzero( secretkey, strlen( secretkey ) );
		}
#endif
#ifdef K5AUTH
		/* do like "kinit" program */
		if (!curpass[0])
			logInfo( "No password for Kerberos5 provided.\n" );
		else
			if ((str = krb5Init( curuser, curpass, td->name )))
				userEnviron = setEnv( userEnviron, "KRB5CCNAME", str );
			else
				nukeAuth( 14, "MIT-KERBEROS-5" );
#endif /* K5AUTH */
		if (td->autoReLogin) {
			gSet( &mstrtalk );
			gSendInt( D_ReLogin );
			gSendStr( curuser );
			gSendStr( curpass );
			gSendStr( newdmrc );
		}
		if (curpass)
			bzero( curpass, strlen( curpass ) );
		setUserAuthorization( td );
		home = getEnv( userEnviron, "HOME" );
		if (home && chdir( home ) < 0) {
			logError( "Cannot chdir to %s's home %s: %m\n", curuser, home );
			sendStr( V_MSG_ERR, "Cannot enter home directory. Using /.\n" );
			chdir( "/" );
			userEnviron = setEnv( userEnviron, "HOME", "/" );
			home = 0;
		}
		if (home || td->clientLogFile[0] == '/') {
			if (!createClientLog( td->clientLogFile )) {
				logWarn( "Session log file according to %s cannot be created: %m\n",
				         td->clientLogFile );
				goto tmperr;
			}
		} else {
		  tmperr:
			if (!createClientLog( td->clientLogFallback ))
				logError( "Fallback session log file according to %s cannot be created: %m\n",
				          td->clientLogFallback );
			/* Could inform the user, but I guess this is only confusing. */
		}
		if (!*dmrcDir)
			mergeSessionArgs( home != 0 );
		if (!(desksess = iniEntry( curdmrc, "Desktop", "Session", 0 )))
			desksess = "failsafe"; /* only due to OOM */
		gSet( &mstrtalk );
		gSendInt( D_User );
		gSendInt( curuid );
		gSendStr( curuser );
		gSendStr( desksess );
		close( mstrtalk.pipe->fd.w );
		userEnviron = setEnv( userEnviron, "DESKTOP_SESSION", desksess );
		for (i = 0; td->sessionsDirs[i]; i++) {
			fname = 0;
			if (strApp( &fname, td->sessionsDirs[i], "/", desksess, ".desktop", (char *)0 )) {
				if ((str = iniLoad( fname ))) {
					if (!strCmp( iniEntry( str, "Desktop Entry", "Hidden", 0 ), "true" ) ||
					    !(sessargs = iniEntry( str, "Desktop Entry", "Exec", 0 )))
						sessargs = "";
					free( str );
					free( fname );
					goto gotit;
				}
				free( fname );
			}
		}
		if (!strcmp( desksess, "failsafe" ) ||
		    !strcmp( desksess, "default" ) ||
		    !strcmp( desksess, "custom" ))
			sessargs = desksess;
		else
			sessargs = "";
	  gotit:
		if (!(argv = parseArgs( (char **)0, td->session )) ||
		    !(argv = addStrArr( argv, sessargs, -1 )))
			exit( 1 );
		if (argv[0] && *argv[0]) {
			debug( "executing session %\"[s\n", argv );
			execute( argv, userEnviron );
			logError( "Session %\"s execution failed: %m\n", argv[0] );
		} else
			logError( "Session has no command/arguments\n" );
		failsafeArgv[0] = td->failsafeClient;
		failsafeArgv[1] = 0;
		execute( failsafeArgv, userEnviron );
		logError( "Failsafe client %\"s execution failed: %m\n",
		          failsafeArgv[0] );
	  cError:
		sendStr( V_MSG_ERR, 0 );
		exit( 1 );
	case -1:
		free( buf );
		return 0;
	}
	debug( "StartSession, fork succeeded %d\n", *pid );
	free( buf );

	gSet( &ctltalk );
	if (!Setjmp( ctltalk.errjmp ))
		while (gRecvCmd( &i )) {
			buf = gRecvStr();
			displayStr( i, buf );
			free( buf );
			gSet( &ctltalk );
			gSendInt( 0 );
		}
	gClosen( ctltalk.pipe );
	finishGreet();

	return 1;
}
int
resParent (int s, struct passwd *pw, struct lsfAuth *auth,
	   struct resConnect *connReq, struct hostent *hostp)
{
  static char fname[] = "resParent";
  int cc;
  char *argv[7];
  char hndlbuf[64];
  struct resChildInfo childInfo;
  char buf[2 * MSGSIZE];
  XDR xdrs;
  int len;
  struct LSFHeader hdr;
  int hpipe[2];
  int wrapPipe[2];
  int pid;

  if (resParams[LSF_SERVERDIR].paramValue != NULL)
    {
      argv[0] = getDaemonPath_ ("/res", resParams[LSF_SERVERDIR].paramValue);
    }
  else
    {
      argv[0] = "res";
    }

  childInfo.resConnect = connReq;
  childInfo.lsfAuth = auth;
  childInfo.pw = pw;
  childInfo.host = hostp;
  childInfo.parentPort = ctrlAddr.sin_port;
  childInfo.currentRESSN = currentRESSN;


  if (resLogOn == 1)
    {
      char strLogCpuTime[32];

      sprintf (strLogCpuTime, "%d", resLogcpuTime);
      putEnv ("LSF_RES_LOGON", "1");
      putEnv ("LSF_RES_CPUTIME", strLogCpuTime);
      putEnv ("LSF_RES_ACCTPATH", resAcctFN);
    }
  else if (resLogOn == 0)
    {
      putEnv ("LSF_RES_LOGON", "0");
    }
  else if (resLogOn == -1)
    {
      putEnv ("LSF_RES_LOGON", "-1");
    }

  xdrmem_create (&xdrs, buf, 2 * MSGSIZE, XDR_ENCODE);
  memset ((void *) &hdr, 0, sizeof (struct LSFHeader));
  hdr.version = OPENLAVA_VERSION;
  if (!xdr_resChildInfo (&xdrs, &childInfo, &hdr))
    {
      ls_syslog (LOG_ERR, I18N_FUNC_FAIL, fname, "xdr_resChildInfo");
      return (-1);
    }
  len = XDR_GETPOS (&xdrs);

  if (socketpair (AF_UNIX, SOCK_STREAM, 0, hpipe) < 0)
    {
      ls_syslog (LOG_ERR, I18N_FUNC_FAIL_M, fname, "socketpair");
      return (-1);
    }
  if (socketpair (AF_UNIX, SOCK_STREAM, 0, wrapPipe) < 0)
    {
      ls_syslog (LOG_ERR, I18N_FUNC_FAIL_M, fname, "socketpair");
      return (-1);
    }
  sprintf (hndlbuf, "%d:%d", hpipe[1], s);

  cc = 1;
  argv[cc++] = "-d";
  argv[cc++] = env_dir;
  if (debug)
    {
      if (debug == 1)
	argv[cc++] = "-1";
      else
	argv[cc++] = "-2";
      argv[cc++] = "-s";
      argv[cc++] = hndlbuf;
      argv[cc++] = NULL;
    }
  else
    {
      argv[cc++] = "-s";
      argv[cc++] = hndlbuf;
      argv[cc++] = NULL;
    }


  if (getenv ("LSF_SETDCEPAG") == NULL)
    putEnv ("LSF_SETDCEPAG", "Y");

  pid = fork ();
  if (pid < 0)
    {
      ls_syslog (LOG_ERR, I18N_FUNC_FAIL_M, fname, "fork");
      close (hpipe[0]);
      close (hpipe[1]);
      close (wrapPipe[0]);
      close (wrapPipe[1]);
      return (-1);
    }

  if (pid == 0)
    {
      if (logclass & LC_TRACE)
	{
	  if (debug)
	    {
	      ls_syslog (LOG_DEBUG2, "%s: executing %s %s %s %s %s %s ",
			 fname, argv[0], argv[1], argv[2], argv[3], argv[4],
			 argv[5]);
	    }
	  else
	    {
	      ls_syslog (LOG_DEBUG2, "%s: executing %s %s %s %s %s ",
			 fname, argv[0], argv[1], argv[2], argv[3], argv[4]);
	    }
	}
      close (hpipe[0]);
      close (wrapPipe[0]);


      if (dup2 (wrapPipe[1], 0) == -1)
	{
	  ls_syslog (LOG_ERR, I18N_FUNC_FAIL_M, fname, "dup2");
	  exit (-1);
	}
      close (wrapPipe[1]);
      lsfExecv (argv[0], argv);
      ls_syslog (LOG_ERR, I18N_FUNC_FAIL_M, fname, "execv");
      exit (-1);
    }

  close (hpipe[1]);
  close (wrapPipe[1]);

  if (connReq->eexec.len > 0)
    {
      int cc1;
      if ((cc1 = b_write_fix (wrapPipe[0], connReq->eexec.data,
			      connReq->eexec.len)) != connReq->eexec.len)
	{
	  ls_syslog (LOG_ERR, _i18n_msg_get (ls_catd, NL_SETN, 5333, "%s: Falied in sending data to wrap for user <%s>, length = %d, cc=1%d: %m"), fname, pw->pw_name, connReq->eexec.len, cc1)	/* catgets 5333 */
	    ;
	  close (wrapPipe[0]);
	  close (hpipe[0]);
	  return (-1);
	}
    }
  close (wrapPipe[0]);

  if (write (hpipe[0], (char *) &len, sizeof (len)) != sizeof (len))
    {
      ls_syslog (LOG_ERR, I18N_FUNC_FAIL_M, fname, "write");
      xdr_destroy (&xdrs);
      close (hpipe[0]);
      return (-1);
    }

  if (write (hpipe[0], buf, len) != len)
    {
      ls_syslog (LOG_ERR, I18N_FUNC_FAIL_M, fname, "write");
      xdr_destroy (&xdrs);
      close (hpipe[0]);
      return (-1);
    }
  xdr_destroy (&xdrs);
  close (hpipe[0]);
  return (0);
}
Exemple #10
0
int
ls_connect(char *host)
{
    struct  hostent *hp;
    int     s, descriptor[2], size;
    char    official[MAXHOSTNAMELEN];
    struct resConnect connReq;
    char *reqBuf;
    struct lsfAuth auth;
    int resTimeout;



    if (genParams_[LSF_RES_TIMEOUT].paramValue)
	resTimeout = atoi(genParams_[LSF_RES_TIMEOUT].paramValue);
    else
	resTimeout = RES_TIMEOUT;

    if (_isconnected_(host, descriptor))
        return(descriptor[0]);

    if ((hp = Gethostbyname_(host)) == NULL) {
        lserrno = LSE_BAD_HOST;
        return -1;
    }

    strcpy(official, hp->h_name);
    memcpy((char *)&res_addr_.sin_addr,(char *)hp->h_addr,(int)hp->h_length);
    if ((rootuid_) && (genParams_[LSF_AUTH].paramValue == NULL)) {
        if (currentsocket_ > (FIRST_RES_SOCK + totsockets_ - 1)) {
            lserrno = LSE_NOMORE_SOCK;
            return -1;
        }
        s = currentsocket_;
        currentsocket_++;
    } else {
        if ((s = CreateSockEauth_(SOCK_STREAM)) < 0)
            return -1;
    }

    putEauthClientEnvVar("user");
    putEauthServerEnvVar("res");

#ifdef INTER_DAEMON_AUTH

    putEnv("LSF_EAUTH_AUX_PASS", "yes");
#endif


    if (getAuth_(&auth, official) == -1) {
	closesocket(s);
	return -1;
    }

    runEsub_(&connReq.eexec, NULL);

    size = sizeof(struct LSFHeader) + sizeof(connReq) +
	   sizeof(struct lsfAuth) +
	   ALIGNWORD_(connReq.eexec.len) +
	   sizeof(int) * 5 ;

    if ((reqBuf = malloc(size)) == NULL) {
	lserrno = LSE_MALLOC;
	goto Fail;
    }

    if (b_connect_(s, (struct sockaddr *)&res_addr_,
				 sizeof(res_addr_), resTimeout) < 0) {
	lserrno = LSE_CONN_SYS;
	goto Fail;
    }

    if (callRes_(s, RES_CONNECT, (char *) &connReq, reqBuf,
		 size, xdr_resConnect, 0, 0, &auth) == -1) {
	goto Fail;
    }

    if (connReq.eexec.len > 0)
	free(connReq.eexec.data);

    free(reqBuf);

    (void)connected_(official, s, -1, currentSN);

    return(s);

  Fail:
    CLOSESOCKET(s);

    if (connReq.eexec.len > 0)
	free(connReq.eexec.data);

    free(reqBuf);
    return -1;
}