Пример #1
0
int
is_root( void ) 
{
	int root = 0;
#if 1
    PSID psid = my_user_Sid();
	if( ! psid ) {
		dprintf( D_ALWAYS, 
				 "ERROR in is_root(): my_user_Sid() returned NULL\n" );
		return 0;
	}
    root = EqualSid(psid, const_cast<SID*>(&sids.LocalSystem));
    free (psid);
#else
	char* user = my_username( 0 );
	if( ! user ) {
		dprintf( D_ALWAYS, 
				 "ERROR in is_root(): my_username() returned NULL\n" );
		return 0;
	}
	if( !strcasecmp(user, "SYSTEM") ) {
		root = 1;
	}
	free( user );
#endif
	return root;
}
Пример #2
0
void
main_pre_dc_init( int argc, char* argv[] )
{
	// handle -o, so that we can switch euid to the user before
	// daemoncore does most of its initialization work.
	int i = 1;
	while ( i < argc ) {
		if ( !strcmp( argv[i], "-o" ) ) {
			// Say what user we're running jobs on behave of.
			// If the schedd starts us as root, we need to switch to
			// this uid for most of our life.
			if ( argc <= i + 1 ) {
				usage( argv[0] );
			}
			myUserName = strdup( argv[i + 1] );
			break;
		}
		i++;
	}

	if ( myUserName ) {
		char *owner = strdup( myUserName );
		char *domain = strchr( owner, '@' );
		if ( domain ) {
			*domain = '\0';
			domain = domain + 1;
		}
		if ( !init_user_ids(owner, domain)) {
			dprintf(D_ALWAYS, "init_user_ids() failed!\n");
			// uids.C will EXCEPT when we set_user_priv() now
			// so there's not much we can do at this point
		}
		set_user_priv();
		// We can't call daemonCore->Register_Priv_State() here because
		// there's no daemonCore object yet. We'll call it in main_init().

		free( myUserName );
		myUserName = owner;
	} else if ( is_root() ) {
		dprintf( D_ALWAYS, "Don't know what user to run as!\n" );
		DC_Exit( 1 );
	} else {
		myUserName = my_username();
	}
}
Пример #3
0
void 
initialize_uids(void)
{
#if defined(WIN32)
#include "my_username.h"

	char *name = NULL;
	char *domain = NULL;

	name = my_username();
	domain = my_domainname();

	caller_name = name;
	job_user_name = name;

	if ( !init_user_ids(name, domain ) ) {
		// shouldn't happen - we always can get our own token
		vmprintf(D_ALWAYS, "Could not initialize user_priv with our own token!\n");
	}

	vmprintf(D_ALWAYS, "Initialize Uids: caller=%s@%s, job user=%s@%s\n", 
			caller_name.Value(), domain, job_user_name.Value(), domain);

	if( name ) {
		free(name);
	}
	if( domain ) {
		free(domain);
	}
	return;
#else
	// init_user_ids was called in main_pre_dc_init()
	vmprintf(D_ALWAYS, "Initial UID/GUID=%d/%d, EUID/EGUID=%d/%d, "
			"Condor UID/GID=%d,%d\n", (int)getuid(), (int)getuid(), 
			(int)geteuid(), (int)getegid(), 
			(int)get_condor_uid(), (int)get_condor_gid());

	vmprintf(D_ALWAYS, "Initialize Uids: caller=%s, job user=%s\n", 
			caller_name.Value(), job_user_name.Value());
	
	return;
#endif
}
/* Changed to int from void by JN in order to return evid. */
long save_event(Dbptr dbi, long is, long ie, long orid, Dbptr dbo)

{
	/* these are variables in dbi copied to dbo */
	long evid;
	char evname[16];
	
	/*altered in output by this program */
	long prefor;
	char auth[20];
	double lddate;

	/* intentionally ignored:  commid */

	dbo = dblookup(dbo,0,"event",0,0);
	dbi.record = is;
	if( dbgetv(dbi,0,
		"event.evid",&evid,
		"event.evname",evname,	
				NULL) == dbINVALID)
	{
		elog_die(1,"save_event: dbgetv error reading event fields of input view at record %ld\n",
				is);
	}
	prefor = orid;
	my_username(auth);
	lddate = std_now();
	if(dbaddv(dbo,0,
                "evid",evid,
		"evname",evname,
		"prefor",prefor,
                "auth",auth,
                "lddate",lddate,
			NULL ) == dbINVALID)
	{
		elog_die(1,"save_event: dbaddv error writing event record for orid %ld\n",
				orid);
	}
        /* Added by JN */
	return(evid);
}
Пример #5
0
int main(int argc, char **argv)
{
	char ** ptr;
	const char * myName;

	// find our name
	myName = strrchr( argv[0], DIR_DELIM_CHAR );
	if( !myName ) {
		myName = argv[0];
	} else {
		myName++;
	}

	int cred_type = 0;
	char * cred_name = NULL;
	char * cred_file_name = NULL;
	char * myproxy_user = NULL;

	char * myproxy_host = NULL;
	int myproxy_port = 0;

	char * myproxy_dn = NULL;

	char * server_address= NULL;

	// read config file
	myDistro->Init (argc, argv);
	config();

	for (ptr=argv+1,argc--; argc > 0; argc--,ptr++) {
		if ( ptr[0][0] == '-' ) {
			switch ( ptr[0][1] ) {
			case 'h':
				usage(myName);
				exit(0);
				break;
			case 'd':

					// dprintf to console
				Termlog = 1;
				dprintf_config ("TOOL", get_param_functions());

				break;
			case 'S':

					// dprintf to console
				Termlog = 1;
				Read_Myproxy_pw_terminal = false;

				break;
			case 'n':
				if( !(--argc) || !(*(++ptr)) ) {
					fprintf( stderr, "%s: -n requires another argument\n",
							 myName );
					exit(1);
				}
	
				server_address = strdup (*ptr);

				break;
			case 't':
				if( !(--argc) || !(*(++ptr)) ) {
					fprintf( stderr, "%s: -t requires another argument\n",
							 myName );
					exit(1);
				}

				if (strcmp (*ptr, "x509") == 0) {
					cred_type = X509_CREDENTIAL_TYPE;
				} else {
					fprintf( stderr, "Invalid credential type %s\n",
							 *ptr );
					exit(1);
				}
				break;
			case 'f':
				if( !(--argc) || !(*(++ptr)) ) {
					fprintf( stderr, "%s: -f requires another argument\n",
							 myName );
					exit(1);
				}
				cred_file_name = strdup (*ptr);
				break;
			case 'N':
				if( !(--argc) || !(*(++ptr)) ) {
					fprintf( stderr, "%s: -N requires another argument\n",
							 myName );
					exit(1);
				}
				cred_name = strdup (*ptr);
				break;

			case 'm':
				if( !(--argc) || !(*(++ptr)) ) {
					fprintf( stderr, "%s: -m requires another argument\n",
							 myName );
					exit(1);
				}
	
				parseMyProxyArgument (*ptr, myproxy_user, myproxy_host, myproxy_port);
				break;
			case 'D':
				if( !(--argc) || !(*(++ptr)) ) {
					fprintf( stderr, "%s: -D requires another argument\n",
							 myName );
					exit(1);
				}
				myproxy_dn = strdup (*ptr);
				break;

			case 'v':
				version();	// this function calls exit(0)
				break;

			default:
				fprintf( stderr, "%s: Unknown option %s\n",
						 myName, *ptr);
				usage(myName);
				exit(1);
			}
		} //fi
	} //rof

	if (( cred_file_name == NULL ) || (cred_type == 0)) {
		fprintf ( stderr, "Credential filename or type not specified\n");
		exit (1);

	}

    Credential * cred = NULL;
	if (cred_type == X509_CREDENTIAL_TYPE) {
		cred = new X509Credential();
	} else {
		fprintf ( stderr, "Invalid credential type\n");
		exit (1);
	}

    
	char * data = NULL;
	int data_size;
	if (!read_file (cred_file_name, data, data_size)) {
		fprintf (stderr, "Can't open %s\n", cred_file_name);
		exit (1);
	}

	cred->SetData (data, data_size);

	if (cred_name !=NULL) {
		cred->SetName(cred_name);
	} else {
		cred->SetName(DEFAULT_CREDENTIAL_NAME);
	}

	char * username = my_username(0);
	cred->SetOwner (username);
  
	if (cred_type == X509_CREDENTIAL_TYPE && myproxy_host != NULL) {
		X509Credential * x509cred = (X509Credential*)cred;

		MyString str_host_port = myproxy_host;
		if (myproxy_port != 0) {
			str_host_port += ":";
			str_host_port += myproxy_port;
		}
		x509cred->SetMyProxyServerHost (str_host_port.Value());

		if (myproxy_user != NULL) {
			x509cred->SetMyProxyUser (myproxy_user);
		} else {
			x509cred->SetMyProxyUser (username);
		}

		if (myproxy_dn != NULL) {
			x509cred->SetMyProxyServerDN (myproxy_dn);
		}

		char * myproxy_password;
		if ( Read_Myproxy_pw_terminal ) {
			myproxy_password = 
				prompt_password(
					"Please enter the MyProxy password:"******"Please enter the MyProxy password from the standard input\n");
		}
		if (myproxy_password) {
			x509cred->SetRefreshPassword ( myproxy_password );
		}

		x509cred->display( D_FULLDEBUG );
	}

	CondorError errstack;
	DCCredd dc_credd (server_address);

	// resolve server address
	if ( ! dc_credd.locate() ) {
		fprintf (stderr, "%s\n", dc_credd.error() );
		return 1;
	}

	if (dc_credd.storeCredential(cred, errstack)) {
		printf ("Credential submitted successfully\n");
	} else {
		fprintf (stderr, "Unable to submit credential\n%s\n",
				 errstack.getFullText(true));
		return 1;
	}

	return 0;
}
long save_origin(Dbptr dbi, long is, long ie, int depth_fixed,
	Hypocenter h, Dbptr dbo)
{
	long orid;

	/* These are parameters copied from input db -- names = css names */
	long evid;
	long jdate;
	long grn;
	long srn;
	char etype[8];
	double mb;
	long mbid;
	double ms;
	long msid;
	double ml;
	long mlid;
	/* These obtained from this solution */

	long nass;
	long ndef;
	char dtype[2];
	char algorithm[16]="genloc-nlls";
	char auth[20];
	double lddate;
	

	/* these are intentionally left null: ndp,depdp,commid*/


	/* set but obtained directly from hypo structure 
	lat, lon, depth, time */

	dbo = dblookup(dbo,0,"origin",0,0);
	
	/* Grab what we need from the input db for copying.  Note
	that because the joins used here, each of the input db
	records have the same origin entries.  Thus, we just fetch
	stuff from row is.  */
	dbi.record = is;
	if( dbgetv(dbi,0,
		"origin.evid", &evid,
		"origin.jdate", &jdate,
		"origin.grn", &grn,
		"origin.srn", &srn,
		"origin.etype", etype,
		"origin.mb", &mb,
		"origin.mbid", &mbid,
		"origin.ms", &ms,
		"origin.msid", &msid,
		"origin.ml", &ml,
		"origin.mlid", &mlid,
				NULL) == dbINVALID)
	{
		elog_die(1,"save_origin: dbgetv error reading origin fields of input view at record %ld\n",
				is);
	}
	nass = ie - is;
	/* ndef is potentially wrong by this calculation.  We set ndef 
	from the number of degrees of freedom in the solution + npar
	where npar is 3 when depth is fixed and 4 otherwise.  This does
	not match the real definition of ndef, especially when array 
	data are used because each arrival then then has 3 data points
	used to constrain the solution.  These is either an error in 
	my (glp) understanding of the css3.0 schema or a flaw in its 
	design.*/
	if(depth_fixed)
	{
		ndef = h.degrees_of_freedom + 3;
		strcpy(dtype,"r");
	}
	else
	{
		ndef = h.degrees_of_freedom + 4;
		strcpy(dtype,"f");
	}
	my_username(auth);
	lddate = std_now();
	orid = dbnextid(dbo,"orid");
	if(dbaddv(dbo,0,
                "lat",h.lat,
                "lon",h.lon,
                "depth",h.z,
                "time",h.time,
                "orid",orid,
                "evid",evid,
                "jdate",jdate,
                "nass",nass,
                "ndef",ndef,
                "grn",grn,
                "srn",srn,
                "etype",etype,
                "dtype",dtype,
                "mb",mb,
                "mbid",mbid,
                "ms",ms,
                "msid",msid,
                "ml",ml,
                "mlid",mlid,
                "algorithm",algorithm,
                "auth",auth,
                "lddate",lddate,
			NULL) == dbINVALID)
	{
		elog_die(1,"save_origin: dbaddv error writing orid %ld\n",
				orid);
	}
	return(orid);
}
Пример #7
0
Qmgr_connection *
ConnectQ(const char *qmgr_location, int timeout, bool read_only, CondorError* errstack, const char *effective_owner, const char* schedd_version_str )
{
	int		rval, ok;
	int cmd = read_only ? QMGMT_READ_CMD : QMGMT_WRITE_CMD;

		// do we already have a connection active?
	if( qmgmt_sock ) {
			// yes; reject new connection (we can only handle one at a time)
		return( NULL );
	}

	// set up the error handling so it will clean up automatically on
	// return.  also allow them to specify their own stack.
	CondorError  our_errstack;
	CondorError* errstack_select = &our_errstack;
	if (errstack) {
		errstack_select = errstack;
	}

    // no connection active as of now; create a new one
	Daemon d( DT_SCHEDD, qmgr_location );
	if( ! d.locate() ) {
		ok = FALSE;
		if( qmgr_location ) {
			dprintf( D_ALWAYS, "Can't find address of queue manager %s\n", 
					 qmgr_location );
		} else {
			dprintf( D_ALWAYS, "Can't find address of local queue manager\n" );
		}
	} else { 
			// QMGMT_WRITE_CMD didn't exist before 7.5.0, so use QMGMT_READ_CMD
			// when talking to older schedds
		if( cmd == QMGMT_WRITE_CMD ) {
			if( !schedd_version_str ) schedd_version_str = d.version();
			if( !schedd_version_str ) {
					// Some day when we don't care about compatibility with
					// things from before 7.5.0, we could stop defaulting
					// to QMGMT_READ_CMD here.
				cmd = QMGMT_READ_CMD;
			}
			else {
				CondorVersionInfo ver_info(schedd_version_str);
				if( !ver_info.built_since_version(7,5,0) ) {
					cmd = QMGMT_READ_CMD;
				}
			}
		}

		qmgmt_sock = (ReliSock*) d.startCommand( cmd,
												 Stream::reli_sock,
												 timeout,
												 errstack_select);
		ok = qmgmt_sock != NULL;
		if( !ok && !errstack) {
			dprintf(D_ALWAYS, "Can't connect to queue manager: %s\n",
					errstack_select->getFullText().c_str() );
		}
	}

	if( !ok ) {
		if( qmgmt_sock ) delete qmgmt_sock;
		qmgmt_sock = NULL;
		return 0;
	}

		// If security negotiation is turned off and we are using WRITE_CMD,
		// then we must force authentication now, before trying to initialize
		// the connection, because this command is registered with
		// force_authentication=true on the server side.
	if( cmd == QMGMT_WRITE_CMD && !qmgmt_sock->triedAuthentication()) {
		if( !SecMan::authenticate_sock(qmgmt_sock, CLIENT_PERM, errstack_select ) )
		{
			delete qmgmt_sock;
			qmgmt_sock = NULL;
			if (!errstack) {
				dprintf( D_ALWAYS, "Authentication Error: %s\n",
						 errstack_select->getFullText().c_str() );
			}
			return 0;
		}
	}

    // This could be a problem
	char *username = my_username();
	char *domain = my_domainname();

	if ( !username ) {
		dprintf(D_FULLDEBUG,"Failure getting my_username()\n");
		delete qmgmt_sock;
		qmgmt_sock = NULL;
		if (domain) free(domain);
		return( 0 );
	}

	/* Get the schedd to handle Q ops. */

    /* Get rid of all the code below */

    if (read_only || !qmgmt_sock->triedAuthentication()) {
        if ( read_only ) {
            rval = InitializeReadOnlyConnection( username );
        } else {
            rval = InitializeConnection( username, domain );
        }

		if (username) {
			free(username);
			username = NULL;
		}
		if (domain) {
			free(domain);
			domain = NULL;
		}

        if (rval < 0) {
            delete qmgmt_sock;
            qmgmt_sock = NULL;
            return 0;
        }

        if ( !read_only ) {
            if (!SecMan::authenticate_sock(qmgmt_sock, CLIENT_PERM, errstack_select)) {
                delete qmgmt_sock;
                qmgmt_sock = NULL;
				if (!errstack) {
					dprintf( D_ALWAYS, "Authentication Error: %s\n",
							 errstack_select->getFullText().c_str() );
				}
                return 0;
            }
        }
    }

	if (username) free(username);
	if (domain) free(domain);

	if( effective_owner && *effective_owner ) {
		if( QmgmtSetEffectiveOwner( effective_owner ) != 0 ) {
			if( errstack ) {
				errstack->pushf(
					"Qmgmt",SCHEDD_ERR_SET_EFFECTIVE_OWNER_FAILED,
					"SetEffectiveOwner(%s) failed with errno=%d: %s.",
					effective_owner, errno, strerror(errno) );
			}
			else {
				dprintf( D_ALWAYS,
						 "SetEffectiveOwner(%s) failed with errno=%d: %s.\n",
						 effective_owner, errno, strerror(errno) );
			}
			delete qmgmt_sock;
			qmgmt_sock = NULL;
			return 0;
		}
	}

	return &connection;
}
Пример #8
0
int RefreshProxyThruMyProxy(Proxy * proxy)
{
	char * proxy_filename = proxy->proxy_filename;
	MyProxyEntry * myProxyEntry = NULL;
	MyString args_string;
	int pid;

	// Starting from the most recent myproxy entry
	// Find an entry with a password
	int found = FALSE;
	proxy->myproxy_entries.Rewind();
	while (proxy->myproxy_entries.Next (myProxyEntry)) {
		if (myProxyEntry->myproxy_password ||
			GetMyProxyPasswordFromSchedD (myProxyEntry->cluster_id,
										  myProxyEntry->proc_id,
										  &(myProxyEntry->myproxy_password))) {
			found=TRUE;

			//. Now move it to the front of the list
			proxy->myproxy_entries.DeleteCurrent();
			proxy->myproxy_entries.Prepend(myProxyEntry);
			break;
		}
	}

	if (!found) {
		// We're screwed - can't get MyProxy passwords for any entry
		return FALSE;
	}

	// Make sure we're not called more often than necessary and if
	time_t now=time(NULL);
	if ((myProxyEntry->get_delegation_pid != FALSE) ||
		(now - myProxyEntry->last_invoked_time < 30)) {

		dprintf (D_ALWAYS,
			 "proxy %s too soon or myproxy-get-delegation already started\n",
				 proxy_filename);
		return FALSE;
	}
	myProxyEntry->last_invoked_time=now;


	// If you don't have a myproxy password, ask SchedD for it
	if (!myProxyEntry->myproxy_password) {
		// Will there ever be a case when there is no MyProxy password needed at all?
		return FALSE;
	}

	// Initialize reaper, if needed
	if (myproxyGetDelegationReaperId == 0 ) {
		myproxyGetDelegationReaperId = daemonCore->Register_Reaper(
					   "GetDelegationReaper",
					   (ReaperHandler) &MyProxyGetDelegationReaper,
					   "GetDelegation Reaper");
 	}

	// Set up environnment for myproxy-get-delegation
	Env myEnv;
	std::string buff;

	if (myProxyEntry->myproxy_server_dn) {
		formatstr( buff, "MYPROXY_SERVER_DN=%s",
				 myProxyEntry->myproxy_server_dn);
		myEnv.SetEnv(buff.c_str());
		dprintf (D_FULLDEBUG, "%s\n", buff.c_str());
	}


	formatstr(buff, "X509_USER_PROXY=%s", proxy_filename);
	myEnv.SetEnv (buff.c_str());
	dprintf (D_FULLDEBUG, "%s\n", buff.c_str());


	// Print password (this will end up in stdin for myproxy-get-delegation)
	if (pipe (myProxyEntry->get_delegation_password_pipe)) {
		dprintf(D_ALWAYS,
				"Failed to pipe(2) in RefreshProxyThruMyProxy "
				"for writing password, aborting\n");
		return FALSE;
	}
	int written = write (myProxyEntry->get_delegation_password_pipe[1],
		   myProxyEntry->myproxy_password,
		   strlen (myProxyEntry->myproxy_password));
	if (written < (int) strlen (myProxyEntry->myproxy_password)) {
		dprintf(D_ALWAYS, "Failed to write to pipe in RefreshProxyThruMyProxy %d\n", errno);
		return FALSE;
    }
	written = write (myProxyEntry->get_delegation_password_pipe[1], "\n", 1);
	if (written < 1) {
		dprintf(D_ALWAYS, "Failed to write to pipe in RefreshProxyThruMyProxy %d\n", errno);
		return FALSE;
	}


	// Figure out user name;
	char * username = my_username(0);	


	// Figure out myproxy host and port
	char * myproxy_host = getHostFromAddr (myProxyEntry->myproxy_host);
	int myproxy_port = getPortFromAddr (myProxyEntry->myproxy_host);

	// args
	ArgList args;
	args.AppendArg(proxy_filename);
	args.AppendArg("-v");
	args.AppendArg("-o");
	args.AppendArg(proxy_filename);
	args.AppendArg("-s");
	args.AppendArg(myproxy_host);
	args.AppendArg("-d");
	args.AppendArg("-t");
	args.AppendArg(myProxyEntry->new_proxy_lifetime);
	args.AppendArg("-S");
	args.AppendArg("-l");
	args.AppendArg(username);


	// Optional port argument
	if (myproxy_port) {
		args.AppendArg("-p");
		args.AppendArg(myproxy_port);
	}

	// Optional credential name argument
	if (myProxyEntry->myproxy_credential_name) {
		args.AppendArg("-k");
		args.AppendArg(myProxyEntry->myproxy_credential_name);
	}

	free (username);
	free (myproxy_host);

	// Create temporary file to store myproxy-get-delegation's stderr
	myProxyEntry->get_delegation_err_filename = create_temp_file();
	if(!myProxyEntry->get_delegation_err_filename) {
		dprintf( D_ALWAYS, "Failed to create temp file");
	} else {
		MSC_SUPPRESS_WARNING_FIXME(6031) // warning: return value of 'chmod' ignored.
		chmod (myProxyEntry->get_delegation_err_filename, 0600);
		myProxyEntry->get_delegation_err_fd = safe_open_wrapper_follow(myProxyEntry->get_delegation_err_filename,O_RDWR);
		if (myProxyEntry->get_delegation_err_fd == -1) {
			dprintf (D_ALWAYS, "Error opening file %s\n",
					 myProxyEntry->get_delegation_err_filename);
		}
	}


	int arrIO[3];
	arrIO[0]=myProxyEntry->get_delegation_password_pipe[0]; //stdin
	arrIO[1]=myProxyEntry->get_delegation_err_fd;
	arrIO[2]=myProxyEntry->get_delegation_err_fd; // stderr

	char * myproxy_get_delegation_pgm = param ("MYPROXY_GET_DELEGATION");
	if (!myproxy_get_delegation_pgm) {
		dprintf (D_ALWAYS, "MYPROXY_GET_DELEGATION not defined in config file\n");
		goto error_exit;
	}


	args.GetArgsStringForDisplay(&args_string);
	dprintf (D_ALWAYS, "Calling %s %s\n", myproxy_get_delegation_pgm, args_string.Value());

	pid = daemonCore->Create_Process (
					myproxy_get_delegation_pgm,
					args,
					PRIV_USER_FINAL,
					myproxyGetDelegationReaperId,
					FALSE,
					&myEnv,
					NULL,	// cwd
					NULL,  // process family info
					NULL,  // socket inherit
					arrIO); // in/out/err streams

	free (myproxy_get_delegation_pgm);

	if (pid == FALSE) {
		dprintf (D_ALWAYS, "Failed to run myproxy-get-delegation\n");
		goto error_exit;
	}

	myProxyEntry->get_delegation_pid = pid;

	return TRUE;

 error_exit:
	myProxyEntry->get_delegation_pid=FALSE;

	if (myProxyEntry->get_delegation_err_fd >= 0) {
		close (myProxyEntry->get_delegation_err_fd);
		myProxyEntry->get_delegation_err_fd=-1;
	}

	if (myProxyEntry->get_delegation_err_filename) {
		MSC_SUPPRESS_WARNING_FIXME(6031) // warning: return value of 'unlink' ignored.
		unlink (myProxyEntry->get_delegation_err_filename);// Remove the tempora
		free (myProxyEntry->get_delegation_err_filename);
		myProxyEntry->get_delegation_err_filename=NULL;
	}

	if (myProxyEntry->get_delegation_password_pipe[0] >= 0) {
		close (myProxyEntry->get_delegation_password_pipe[0]);
		myProxyEntry->get_delegation_password_pipe[0]=-1;
	}
	if (myProxyEntry->get_delegation_password_pipe[1] >= 0 ) {
		close (myProxyEntry->get_delegation_password_pipe[1]);
		myProxyEntry->get_delegation_password_pipe[1]=-1;
	}

	return FALSE;
}
Пример #9
0
int Condor_Auth_Claim :: authenticate(const char * /* remoteHost */, CondorError* /* errstack */, bool /*non_blocking*/)
{

	const char * pszFunction = "Condor_Auth_Claim :: authenticate";

	int retval = 0;
	int fail = 0;

	if ( mySock_->isClient() ) {

		MyString myUser;
		bool error_getting_name = false;

		// get our user name in condor priv
		// (which is what we want to use for daemons. for
		//  tools and daemons not started as root, this will
		//  just give us the username that we were invoked
		//  as, which is also what we want)
		priv_state priv = set_condor_priv();
		char* tmpOwner = NULL; 
		char* tmpSwitchUser = param("SEC_CLAIMTOBE_USER");
		if(tmpSwitchUser) {
			tmpOwner = tmpSwitchUser;
			dprintf(D_ALWAYS, "SEC_CLAIMTOBE_USER to %s!\n", tmpSwitchUser);
		} else {
			tmpOwner = my_username();
		}
		// remove temptation to use this variable to see if we were
		// specifying the claim to be user
		tmpSwitchUser = NULL;
		set_priv(priv);
		if ( !tmpOwner ) {
			//send 0
			if (!mySock_->code( retval )) { 
				dprintf(D_SECURITY, "Protocol failure at %s, %d!\n", 
					pszFunction, __LINE__);
				return fail; 
			}
			error_getting_name = true;
		}
		else {
			myUser = tmpOwner;
			free(tmpOwner);

			// check SEC_CLAIMTOBE_INCLUDE_DOMAIN. this knob exists (and defaults
			// to false) to provide backwards compatibility. it will be removed
			// completely in the development (6.9) series
			if (param_boolean("SEC_CLAIMTOBE_INCLUDE_DOMAIN", false)) {
				char* tmpDomain = param("UID_DOMAIN");
				if ( !tmpDomain ) {
					//send 0
					if (!mySock_->code( retval )) { 
						dprintf(D_SECURITY, "Protocol failure at %s, %d!\n", 
							pszFunction, __LINE__);
						return fail; 
					}
					error_getting_name = true;
				}
				else {
					myUser += "@";
					myUser += tmpDomain;
					free(tmpDomain);
				}
			}
		}

		if (!error_getting_name) {

			//send 1 and then our username
			mySock_->encode();
			retval = 1;
			char* tmpUser = strdup(myUser.Value());
			ASSERT(tmpUser);
			if (!mySock_->code( retval ) || 
			    !mySock_->code( tmpUser ))
			{
				free(tmpUser);
				dprintf(D_SECURITY, "Protocol failure at %s, %d!\n", 
					pszFunction, __LINE__);
				return fail; 
			}
			//setRemoteUser(tmpUser); // <-- IS THIS NEEDED????
			free(tmpUser);
			if (!mySock_->end_of_message()) { 
				dprintf(D_SECURITY, "Protocol failure at %s, %d!\n", 
					pszFunction, __LINE__);
				return fail;
			}
			mySock_->decode();
			if (!mySock_->code( retval )) {
				dprintf(D_SECURITY, "Protocol failure at %s, %d!\n", 
					pszFunction, __LINE__);
				return fail; 
			}
		}

	} else { //server side

		mySock_->decode();
		if (!mySock_->code( retval )) { 
			dprintf(D_SECURITY, "Protocol failure at %s, %d!\n", 
				pszFunction, __LINE__);
			return fail; 
		}

		//if 1, receive user and send back ok
		if( retval == 1 ) {

			char* tmpUser = NULL;
			if (!mySock_->code( tmpUser ) ||
			    !mySock_->end_of_message())
			{
				dprintf(D_SECURITY, "Protocol failure at %s, %d!\n", 
					pszFunction, __LINE__);
				if (tmpUser != NULL)
				{
					free(tmpUser);
				}
				return fail;
			}

			if( tmpUser ) {

				MyString myUser = tmpUser;

				// check SEC_CLAIMTOBE_INCLUDE_DOMAIN. this knob exists (and defaults
				// to false) to provide backwards compatibility. it will be removed
				// completely in the development (6.9) series
				if (param_boolean("SEC_CLAIMTOBE_INCLUDE_DOMAIN", false)) {
					// look for an '@' char in the name we received.
					// if present (newer clients), set the domain using
					// the given component. if not present (older clients),
					// use UID_DOMAIN from our config
					char* tmpDomain = NULL;
					char* at = strchr(tmpUser, '@');
					if ( at ) {
						*at = '\0';
						if (*(at + 1) != '\0') {
							tmpDomain = strdup(at + 1);
						}
					}
					if (!tmpDomain) {
						tmpDomain = param("UID_DOMAIN");
					}
					ASSERT(tmpDomain);
					setRemoteDomain(tmpDomain);
					myUser.formatstr("%s@%s", tmpUser, tmpDomain);
					free(tmpDomain);
				}
				setRemoteUser(tmpUser);
				setAuthenticatedName(myUser.Value());
				free(tmpUser);
				retval = 1;
			} else {
				// tmpUser is NULL; failure
				retval = 0;
			}

			mySock_->encode();
			if (!mySock_->code( retval )) { 
				dprintf(D_SECURITY, "Protocol failure at %s, %d!\n", 
					pszFunction, __LINE__);
				return fail;
			}
		}
	}
    
	if (!mySock_->end_of_message()) { 
		dprintf(D_SECURITY, "Protocol failure at %s, %d!\n", 
			pszFunction, __LINE__);
		return fail; 
	}

	return retval;
}
Пример #10
0
bool
JobInfoCommunicator::initUserPrivWindows( void )
{
    // Win32
    // taken origionally from OsProc::StartJob.  Here we create the
    // user and initialize user_priv.

    // By default, assume execute login may be shared by other processes.
    setExecuteAccountIsDedicated( NULL );

    // we support running the job as other users if the user
    // is specifed in the config file, and the account's password
    // is properly stored in our credential stash.

    char *name = NULL;
    char *domain = NULL;
    bool init_priv_succeeded = true;
    bool run_as_owner = allowRunAsOwner( false, false );

    // TODO..
    // Currently vmgahp for VMware VM universe can't run as user on Windows.
    // It seems like a bug of VMware. VMware command line tool such as "vmrun"
    // requires Administrator privilege.
    // So here we set name and domain with my_username and my_domainname
    // -jaeyoung 06/15/07
    if( job_universe == CONDOR_UNIVERSE_VM ) {
#if 0
        // If "VM_UNIV_NOBODY_USER" is defined in Condor configuration file,
        // wee will use it.
        char *vm_jobs_as = param("VM_UNIV_NOBODY_USER");
        if (vm_jobs_as) {
            getDomainAndName(vm_jobs_as, domain, name);
            /*
             * name and domain are now just pointers into vm_jobs_as
             * buffer.  copy these values into their own buffer so we
             * deallocate below.
             */
            if ( name ) {
                name = strdup(name);
            }
            if ( domain ) {
                domain = strdup(domain);
            }
            free(vm_jobs_as);
        }
#endif
        MyString vm_type;
        job_ad->LookupString(ATTR_JOB_VM_TYPE, vm_type);

        if( strcasecmp(vm_type.Value(), CONDOR_VM_UNIVERSE_VMWARE) == MATCH ) {
            name = my_username();
            domain = my_domainname();
        }
    }

    if( !name ) {
        if ( run_as_owner ) {
            job_ad->LookupString(ATTR_OWNER,&name);
            job_ad->LookupString(ATTR_NT_DOMAIN,&domain);
        }
    }

    if ( !name ) {
        char slot_user[255];
        MyString slotName = "";
        slotName = Starter->getMySlotName();

        slotName.upper_case();
        sprintf(slot_user, "%s_USER", slotName);
        char *run_jobs_as = param(slot_user);
        if (run_jobs_as) {
            getDomainAndName(run_jobs_as, domain, name);
            /*
             * name and domain are now just pointers into run_jobs_as
             * buffer.  copy these values into their own buffer so we
             * deallocate below.
             */
            if ( name ) {
                name = strdup(name);
            }
            if ( domain ) {
                domain = strdup(domain);
            }
            free(run_jobs_as);
        }
    }

    if ( name ) {

        if (!init_user_ids(name, domain)) {

            dprintf(D_ALWAYS, "Could not initialize user_priv as \"%s\\%s\".\n"
                    "\tMake sure this account's password is securely stored "
                    "with condor_store_cred.\n", domain, name );
            init_priv_succeeded = false;
        }
        else {
            MyString login_name;
            joinDomainAndName(name, domain, login_name);
            if( checkDedicatedExecuteAccounts( login_name.Value() ) ) {
                setExecuteAccountIsDedicated( login_name.Value() );
            }
        }

    } else if ( !can_switch_ids() ) {
        char *u = my_username();
        char *d = my_domainname();

        if ( !init_user_ids(u, d) ) {
            // shouldn't happen - we always can get our own token
            dprintf(D_ALWAYS, "Could not initialize user_priv with our own token!\n");
            init_priv_succeeded = false;
        }
        free(u);
        free(d);
    } else if( init_user_ids("nobody", ".") ) {
        // just init a new nobody user; dynuser handles the rest.
        // the "." means Local Machine to LogonUser

        setExecuteAccountIsDedicated( get_user_loginname() );
    }
    else {

        dprintf( D_ALWAYS, "ERROR: Could not initialize user_priv "
                 "as \"nobody\"\n" );
        init_priv_succeeded = false;

    }

    if ( name ) free(name);
    if ( domain ) free(domain);

    user_priv_is_initialized = init_priv_succeeded;
    return init_priv_succeeded;
}
Пример #11
0
int
init_user_ids(const char username[], const char domain[]) 
{
	int retval = 0;

	if (!username || !domain) {
		dprintf(D_ALWAYS, "WARNING: init_user_ids() called with"
			   " NULL arguments!\n");
	   	return 0;
   	}

	// we have to be very careful calling dprintf in this function, because dprintf
	// will try and _set_priv to root and then back to what it was.  so we need to
	// make sure that our global variables are always in a state where that doesn't
	// except.

	// TJ:2010: Can't do this here, UserIdsInited must never be true 
	// while CurrUserHandle is NULL or dprintf will EXCEPT.
	// UserIdsInited = true;
	
	// see if we already have a user handle for the requested user.
	// if so, just return 1. 
	// TODO: cache multiple user handles to save time.

	dprintf(D_FULLDEBUG, "init_user_ids: want user '%s@%s', "
			"current is '%s@%s'\n",
		username, domain, UserLoginName, UserDomainName);
	
	if ( CurrUserHandle = cached_tokens.getToken(username, domain)) {
		UserIdsInited = true; // do this before we call dprintf
		// when we uninit_user_ids we can end up CurrUserHandle in the cache
		// but UserLoginName and UserDomainName not set, if that happens
		// we need to set them here.
		if ( ! UserLoginName) UserLoginName = strdup(username);
		if ( ! UserDomainName) UserDomainName = strdup(domain);
		dprintf(D_FULLDEBUG, "init_user_ids: Already have handle for %s@%s,"
			" so returning.\n", username, domain);
		return 1;
	} else {
		char* myusr = my_username();
		char* mydom = my_domainname();

		// we cleared CurrUserHandle, so we aren't inited.
		UserIdsInited = false;

		// see if our calling thread matches the user and domain
		// we want a token for. This happens if we're submit for example.
		if ( strcmp( myusr, username ) == 0 &&
			 strcasecmp( mydom, domain ) == 0 ) { // domain is case insensitive

			dprintf(D_FULLDEBUG, "init_user_ids: Calling thread has token "
					"we want, so returning.\n");
			CurrUserHandle = my_usertoken();
			if (CurrUserHandle) {
				UserIdsInited = true;
			} else {
				dprintf(D_FULLDEBUG, "init_user_ids: handle is null!\n");
			}
			
			if (UserLoginName) {
				free(UserLoginName);
				UserLoginName = NULL;
			}
			if (UserDomainName) {
				free(UserDomainName);
				UserDomainName = NULL;
			}
			
			// these are strdup'ed, so we can just stash their pointers
			UserLoginName = myusr;
			UserDomainName = mydom;

			// don't forget to drop it in the cache too
			cached_tokens.storeToken(UserLoginName, UserDomainName,
				   		CurrUserHandle);
			return 1;
		}
	}

	// at this point UserIdsInited should be false.
	ASSERT( ! UserIdsInited);

	// anything beyond this requires user switching
	if (!can_switch_ids()) {
		dprintf(D_ALWAYS, "init_user_ids: failed because user switching is disabled\n");
		return 0;
	}

	if ( strcmp(username,"nobody") != 0 ) {
		// here we call routines to deal with passwords. Hopefully we're
		// running as LocalSystem here, otherwise we can't get at the 
		// password stash.
		lsa_mgr lsaMan;
		char pw[255];
		char user[255];
		char dom[255];
		wchar_t w_fullname[255];
		wchar_t *w_pw;
		bool got_password = false;
		bool got_password_from_credd = false;

		// these should probably be snprintfs
		swprintf(w_fullname, L"%S@%S", username, domain);
		sprintf(user, "%s", username);
		sprintf(dom, "%s", domain);
		
		// make sure we're SYSTEM when we do this
		w_pw = lsaMan.query(w_fullname);
		if ( w_pw ) {
			// copy password into a char buffer
			sprintf(pw, "%S", w_pw);			
			// we don't need the wide char pw anymore, so clean it up
			SecureZeroMemory(w_pw, wcslen(w_pw)*sizeof(wchar_t));
			delete[](w_pw);
			w_pw = NULL;

			// now that we got a password, see if it is good.
			retval = LogonUser(
				user,						// user name
				dom,						// domain or server - local for now
				pw,							// password
				LOGON32_LOGON_INTERACTIVE,	// type of logon operation. 
											// LOGON_BATCH doesn't seem to work right here.
				LOGON32_PROVIDER_DEFAULT,	// logon provider
				&CurrUserHandle				// receive tokens handle
			);
			
			if ( !retval ) {
				dprintf(D_FULLDEBUG,"Locally stored credential for %s@%s is stale\n",
					user,dom);
				// Set handle to NULL to make certain we recall LogonUser again below
				CurrUserHandle = NULL;	
			} else {
				got_password = true;	// so we don't bother going to a credd
			}
		}

		// if we don't have the password from our local stash, try to fetch
		// it from a credd. this tiny function is in a separate file so
        // that we don't pull in all of daemon core when we link to the utils library.

		char *credd_host = param("CREDD_HOST");
		if (credd_host && got_password==false) {
#if 1
           got_password = get_password_from_credd(
              credd_host,
              username,
              domain,
              pw,
              sizeof(pw));
           got_password_from_credd = got_password;
#else
			dprintf(D_FULLDEBUG, "trying to fetch password from credd: %s\n", credd_host);
			Daemon credd(DT_CREDD);
			Sock * credd_sock = credd.startCommand(CREDD_GET_PASSWD,Stream::reli_sock,10);
			if ( credd_sock ) {
				credd_sock->put((char*)username);	// send user
				credd_sock->put((char*)domain);		// send domain
				credd_sock->end_of_message();
				credd_sock->decode();
				pw[0] = '\0';
				int my_stupid_sizeof_int_for_damn_cedar = sizeof(pw);
				char *my_buffer = pw;
				if ( credd_sock->code(my_buffer,my_stupid_sizeof_int_for_damn_cedar) && pw[0] ) {
					got_password = true;
					got_password_from_credd = true;
				} else {
					dprintf(D_FULLDEBUG,
							"credd (%s) did not have info for %s@%s\n",
							credd_host, username,domain);
				}
				delete credd_sock;
				credd_sock = NULL;
			} else {
				dprintf(D_FULLDEBUG,"Failed to contact credd %s: %s\n",
					credd_host,credd.error() ? credd.error() : "");
			}
#endif
		}
		if (credd_host) free(credd_host);

		if ( ! got_password ) {
			dprintf(D_ALWAYS, "ERROR: Could not locate valid credential for user "
				"'%s@%s'\n", username, domain);
			return 0;
		} else {
			dprintf(D_FULLDEBUG, "Found credential for user '%s'\n", username);

			// If we have not yet called LogonUser, then CurrUserHandle is NULL,
			// and we need to call it here.
			if ( CurrUserHandle == NULL ) {
				retval = LogonUser(
					user,						// user name
					dom,						// domain or server - local for now
					pw,							// password
					LOGON32_LOGON_INTERACTIVE,	// type of logon operation. 
												// LOGON_BATCH doesn't seem to work right here.
					LOGON32_PROVIDER_DEFAULT,	// logon provider
					&CurrUserHandle				// receive tokens handle
				);
			} else {
				// we already have a good user handle from calling LogonUser to check to
				// see if our stashed credential was stale or not, so set retval to success
				retval = 1;	// LogonUser returns nonzero value on success
			}

			dprintf(D_FULLDEBUG, "LogonUser completed.\n");

			if (UserLoginName) {
				free(UserLoginName);
				UserDomainName = NULL;
			}
			if (UserDomainName) {
				free(UserDomainName);
				UserDomainName = NULL;
			}
			UserLoginName = strdup(username);
			UserDomainName = strdup(domain);

			if ( !retval ) {
				dprintf(D_ALWAYS, "init_user_ids: LogonUser failed with NT Status %ld\n", 
					GetLastError());
				retval =  0;	// return of 0 means FAILURE
			} else {
				// stash the new token in our cache
				cached_tokens.storeToken(UserLoginName, UserDomainName,
					   	CurrUserHandle);
				UserIdsInited = true;

				// if we got the password from the credd, and the admin wants passwords stashed
				// locally on this machine, then do it.
				if ( got_password_from_credd &&
                     param_boolean("CREDD_CACHE_LOCALLY",false) ) {
                    cache_credd_locally(username, domain, pw);
                }
				
				retval = 1;	// return of 1 means SUCCESS
			}

			// clear pw from memory
			SecureZeroMemory(pw, 255);

			return retval;
		}
		
	} else {
		///
		// Here's where we use a nobody account
		//
		
		dprintf(D_FULLDEBUG, "Using dynamic user account.\n");

		myDynuser->reset();
		// at this point, we know we want a user nobody, so
		// generate a dynamic user and stash the handle

				
		if ( !myDynuser->init_user() ) {
			// This is indicative of a serious problem.
			EXCEPT("Failed to create a user nobody");
		}
		
		if (UserLoginName) {
			free(UserLoginName);
			UserDomainName = NULL;
		}
		if (UserDomainName) {
			free(UserDomainName);
			UserDomainName = NULL;
		}

		UserLoginName = strdup( myDynuser->get_accountname() );
		UserDomainName = strdup( "." );

		// we created a new user, now just stash the token
		CurrUserHandle = myDynuser->get_token();

		// drop the handle in our cache too
		cached_tokens.storeToken(UserLoginName, UserDomainName,
			   		CurrUserHandle);
		UserIdsInited = true;
		return 1;
	}
}
Пример #12
0
int
main(int argc, char **argv)
{
	int             verbose = 0;


	char           *dbname = malloc(STRSZ);
	char           *datafilename = malloc(STRSZ);
	char           *name = malloc(STRSZ);
	char           *line = malloc(STRSZ);
	char            str1[20], str2[20], *str3 = malloc(1024);
	int             level = 0;
	int             closed = 0, close = 0;
	int             maxpoints = 5000;
	Point          *poly = malloc(maxpoints * sizeof(double));
	double          lat, lon;

	long             npoints;
	char           *auth = malloc(STRSZ);
	char            ptype[STRSZ];
	char           *dir = malloc(STRSZ), *dfile = malloc(STRSZ), *tname = malloc(STRSZ),
	                numstr[10];
	int             ftype = polyFLOAT;
	Dbptr           db;
	FILE           *fh;
	int             putit;
	int             polycounter = 0;

	elog_init(argc, argv);


	my_username(auth);
	strcat(auth, ":gmt");
	strcpy(name, "-");
	strcpy(dir, "-");
	strcpy(dfile, "gmt.bin");
	strcpy(ptype, "-");
	for (argc--, argv++; argc > 0; argc--, argv++) {
		if (!strcmp(*argv, "-auth")) {
			argc--;
			argv++;
			if (argc < 3) {
				elog_complain(0, "Need -auth argument.\n");
				usage();
				exit(1);
			}
			auth = *argv;
		} else if (!strcmp(*argv, "-dir")) {
			argc--;
			argv++;
			if (argc < 3) {
				elog_complain(0, "Need -dir argument.\n");
				usage();
				exit(1);
			}
			dir = *argv;
		} else if (!strcmp(*argv, "-dfile")) {
			argc--;
			argv++;
			if (argc < 3) {
				elog_complain(0, "Need -dfile argument.\n");
				usage();
				exit(1);
			}
			dfile = *argv;
		} else if (!strcmp(*argv, "-pname")) {
			argc--;
			argv++;
			if (argc < 3) {
				elog_complain(0, "Need -pname argument.\n");
				usage();
				exit(1);
			}
			name = *argv;
		} else if (!strcmp(*argv, "-ptype")) {
			argc--;
			argv++;
			if (argc < 3) {
				elog_complain(0, "Need -ptype argument.\n");
				usage();
				exit(1);
			}
			strncpy(ptype, *argv, 2);
		} else if (!strcmp(*argv, "-level")) {
			argc--;
			argv++;
			if (argc < 3) {
				elog_complain(0, "Need -level argument.\n");
				usage();
				exit(1);
			}
			level = atoi(*argv);
		} else if (!strcmp(*argv, "-close_polygons")) {
			close = 1;
		} else if (!strcmp(*argv, "-v")) {
			verbose++;
		} else if (**argv != '-') {
			break;
		} else {
			elog_complain(0, "unrecognized argument '%s'\n", *argv);
			usage();
			exit(1);
		}
	}
	if (argc < 2) {
		elog_complain(0, "Need datfile and db arguments.\n");
		usage();
		exit(1);
	}
	datafilename = *argv;
	argc--;
	argv++;
	dbname = *argv;
	if (access(datafilename, 4)) {
		elog_die(0, "datafile %s should be READABLE!\n", datafilename);
	}
	if (dbcreate(dbname, "polygon1.2", 0, 0, 0)) {
		elog_die(1, "can't create database %s\n", dbname);
	}
	if (!strcmp(name, "-")) {
		strcpy(name, datafilename);
	}
	dbopen(dbname, "r+", &db);
	db = dblookup(db, 0, "polygon", 0, 0);
	fh = fopen(datafilename, "r");
	putit = 0;
	npoints = 0;
	polycounter = 0;
	while (fgets(line, 80, fh) != 0) {
		if (line[0] == '>') {
			if (putit) {
				strcpy(tname, name);
				if (polycounter > 0) {
					sprintf(numstr, ".%d", polycounter);
					tname = strcat(tname, numstr);
				}
				if (verbose) {
					elog_notify(0, "%s: (%ld points n file %s/%s)\n", tname, npoints, dir, dfile);
				}
				if (npoints > 2 && (close || (
				 (poly[0].lat == poly[npoints - 1].lat) &&
				(poly[0].lon == poly[npoints - 1].lon)))) {
					closed = 1;
				}
				writePolygonData(db, poly, npoints, tname, closed, level, ptype, auth, dir, dfile, ftype);
				closed = 0;
				polycounter++;
			}
			strtrim(line);
			npoints = 0;
			putit = 1;
		} else {
			sscanf(line, "%s %s %s", str1, str2, str3);
			lon = atof(str1);
			lat = atof(str2);
			if (npoints > maxpoints - 2) {
				maxpoints += 5000;
				poly = realloc(poly, maxpoints);
			}
			poly[npoints].lat = lat;
			poly[npoints].lon = lon;
			npoints++;
		}
	}
	if (npoints > 0) {
		strcpy(tname, name);
		if (polycounter > 0) {
			sprintf(numstr, ".%d", polycounter);
			strcat(tname, numstr);
		}
		if (verbose) {
			elog_notify(0, "%s: (%ld points n file %s/%s)\n", tname, npoints, dir, dfile);
		}
		if (npoints > 2 && (close || (
				 (poly[0].lat == poly[npoints - 1].lat) &&
			       (poly[0].lon == poly[npoints - 1].lon)))) {
			closed = 1;
		}
		writePolygonData(db, poly, npoints, tname, closed, level, ptype, auth, dir, dfile, ftype);
		closed = 0;
	}
	fclose(fh);
	elog_print(0, 0);
	return 0;
}
Пример #13
0
/*
 * numbered_command: does (hopefully) the right thing with the numbered
 * responses from the server.  I wasn't real careful to be sure I got them
 * all, but the default case should handle any I missed (sorry) 
 */
void
numbered_command(u_char *from, int comm, u_char **ArgList)
{
	u_char	*user;
	u_char	none_of_these = 0;
	u_char	blah[BIG_BUFFER_SIZE];
	int	flag,
		lastlog_level;
	const	int	from_server = parsing_server();
#if 0
	int	user_cnt,
		inv_cnt,
		server_cnt;
#endif /* 0 */

	if (!from || !*from)
		return;
	if (!*ArgList[0])
		user = NULL;
	else
		user = ArgList[0];
	if (!ArgList[1])
		return;
	lastlog_level = set_lastlog_msg_level(LOG_CRAP);
	save_message_from();
	message_from(NULL, LOG_CRAP);
	ArgList++;
	current_numeric_local = -comm;	/* must be negative of numeric! */
	switch (comm)
	{
	case 001:	/* #define RPL_WELCOME          001 */
		PasteArgs(ArgList, 0);
		if (my_strcmp(user, server_get_nickname(from_server)) != 0)
		{
			yell("=== Setting this servers nickname to \"%s\" from \"%s\"", user, server_get_nickname(from_server));
			server_set_nickname(from_server, user);
		}
		if (do_hook(current_numeric(), "%s %s", from, *ArgList)) 
			display_msg(from, ArgList);
		clean_whois_queue();
		break;
	case 002:	/* #define RPL_YOURHOST         002 */
		PasteArgs(ArgList, 0);
		snprintf(CP(blah), sizeof blah, "*** %s", ArgList[0]);
		got_initial_version(blah);
		if (do_hook(current_numeric(), "%s %s", from, *ArgList))
			display_msg(from, ArgList);
		break;

/* should do something with this some day, 2.8 had channel/user mode switches */
	case 004:	/* #define RPL_MYINFO           004 */
		PasteArgs(ArgList, 0);
		if (do_hook(current_numeric(), "%s %s", from, *ArgList))
			display_msg(from, ArgList);
		break;

/*
 * this part of ircii has been broken for most of ircd 2.7, so someday I'll
 * make it work for ircd 2.8 ...  phone..
 */
#if 0
	case 251:		/* #define RPL_LUSERCLIENT      251 */
		display_msg(from, ArgList);
		if (is_server_connected(from_server))
			break;
		if (from_server == get_primary_server() && ((sscanf(ArgList[1],
		    "There are %d users and %d invisible on %d servers",
		    &user_cnt, &inv_cnt, &server_cnt) == 3)||(sscanf(ArgList[1],
		    "There are %d users and %d invisible on %d servers",
		    &user_cnt, &inv_cnt, &server_cnt) == 3)))
		{
			user_cnt =+ inv_cnt;
			if ((server_cnt < get_int_var(MINIMUM_SERVERS_VAR)) ||
			    (user_cnt < get_int_var(MINIMUM_USERS_VAR)))
			{
				say("Trying better populated server...");
				get_connected(from_server + 1);
			}
		}
		break;
#endif /* 0 */
	case 301:		/* #define RPL_AWAY             301 */
		user_is_away(from, ArgList);
		break;

	case 302:		/* #define RPL_USERHOST         302 */
		userhost_returned(from, ArgList);
		break;

	case 303:		/* #define RPL_ISON             303 */
		ison_returned(from, ArgList);
		break;

	case 311:		/* #define RPL_WHOISUSER        311 */
		whois_name(from, ArgList);
		break;

	case 312:		/* #define RPL_WHOISSERVER      312 */
		whois_server(from, ArgList);
		break;

	case 313:		/* #define RPL_WHOISOPERATOR    313 */
		whois_oper(from, ArgList);
		break;

	case 314:		/* #define RPL_WHOWASUSER       314 */
		whowas_name(from, ArgList);
		break;

	case 316:		/* #define RPL_WHOISCHANOP      316 */
		whois_chop(from, ArgList);
		break;

	case 317:		/* #define RPL_WHOISIDLE        317 */
		whois_lastcom(from, ArgList);
		break;

	case 318:		/* #define RPL_ENDOFWHOIS       318 */
		end_of_whois(from, ArgList);
		break;

	case 319:		/* #define RPL_WHOISCHANNELS    319 */
		whois_channels(from, ArgList);
		break;

	case 321:		/* #define RPL_LISTSTART        321 */
		ArgList[0] = UP("Channel\0Users\0Topic");
		ArgList[1] = ArgList[0] + 8;
		ArgList[2] = ArgList[1] + 6;
		ArgList[3] = NULL;
		funny_list(from, ArgList);
		break;

	case 322:		/* #define RPL_LIST             322 */
		funny_list(from, ArgList);
		break;

	case 324:		/* #define RPL_CHANNELMODEIS    324 */
		funny_mode(from, ArgList);
		break;

	case 341:		/* #define RPL_INVITING         341 */
		invite(from, ArgList);
		break;

	case 352:		/* #define RPL_WHOREPLY         352 */
		whoreply(NULL, ArgList);
		break;

	case 353:		/* #define RPL_NAMREPLY         353 */
		funny_namreply(from, ArgList);
		break;

	case 366:		/* #define RPL_ENDOFNAMES       366 */
		{
			u_char	*tmp = NULL,
				*chan;

			PasteArgs(ArgList, 0);
			malloc_strcpy(&tmp, ArgList[0]);
			chan = next_arg(tmp, 0);
			flag = do_hook(current_numeric(), "%s %s", from, ArgList[0]);
			
			if (flag &&
			    channel_mode_lookup(chan, CHAN_NAMES | CHAN_MODE, 0) &&
			    get_int_var(SHOW_END_OF_MSGS_VAR) && flag)
				display_msg(from, ArgList);

			new_free(&tmp);
		}
		break;

	case 381: 		/* #define RPL_YOUREOPER        381 */
		PasteArgs(ArgList, 0);
		if (do_hook(current_numeric(), "%s %s", from, *ArgList))
			display_msg(from, ArgList);
		server_set_operator(parsing_server(), 1);
		update_all_status();	/* fix the status line */
		break;

	case 401:		/* #define ERR_NOSUCHNICK       401 */
		no_such_nickname(from, ArgList);
		break;

	case 405:		/* #define ERR_TOOMANYCHANNELS  405 */
		remove_channel(ArgList[0], parsing_server());
		break;
		
	case 421:		/* #define ERR_UNKNOWNCOMMAND   421 */
		if (check_screen_redirect(ArgList[0]))
			break;
		if (check_wait_command(ArgList[0]))
			break;
		PasteArgs(ArgList, 0);
		flag = do_hook(current_numeric(), "%s %s", from, *ArgList);
		if (!my_strncmp("ISON", *ArgList, 4) || !my_strncmp("USERHOST",
		    *ArgList, 8))
		{
			server_set_2_6_2(parsing_server(), 0);
			convert_to_whois();
		}
		else if (flag)
			display_msg(from, ArgList);
		break;

	case 432:		/* #define ERR_ERRONEUSNICKNAME 432 */
	case 433:		/* #define ERR_NICKNAMEINUSE    433 */ 
		PasteArgs(ArgList, 0);
		if (do_hook(current_numeric(), "%s %s", from, *ArgList))
			display_msg(from, ArgList);
		reset_nickname(from);
		break;

	case 437:		/* #define ERR_UNAVAILRESOURCE  437 */
		PasteArgs(ArgList, 0);
		if (do_hook(current_numeric(), "%s %s", from, *ArgList))
			display_msg(from, ArgList);
		if (!is_channel(*ArgList))
			reset_nickname(from);
		break;

	case 463:		/* #define ERR_NOPERMFORHOST    463 */
		display_msg(from, ArgList);
		close_server(parsing_server(), empty_string());
		window_check_servers();
		if (!connected_to_server())
			get_connected(parsing_server() + 1);
		break;

	case 464:		/* #define ERR_PASSWDMISMATCH   464 */
		PasteArgs(ArgList, 0);
		flag = do_hook(current_numeric(), "%s %s", from, ArgList[0]);
		if (server_get_oper_command())
		{
			if (flag)
				display_msg(from, ArgList);
		}
		else
			get_password();
		break;

	case 465:		/* #define ERR_YOUREBANNEDCREEP 465 */
		{
			int	klined_server = parsing_server();

			PasteArgs(ArgList, 0);
			if (do_hook(current_numeric(), "%s %s", from, ArgList[0]))
				display_msg(from, ArgList);
			close_server(parsing_server(), empty_string());
			window_check_servers();
			if (number_of_servers() > 1)
				remove_from_server_list(klined_server);
			if (!connected_to_server())
				say("You are not connected to a server. Use /SERVER to connect.");
			break;
		}

	case 471:		/* #define ERR_CHANNELISFULL    471 */
	case 473:		/* #define ERR_INVITEONLYCHAN   473 */
	case 474:		/* #define ERR_BANNEDFROMCHAN   474 */
	case 475: 		/* #define ERR_BADCHANNELKEY    475 */
	case 476:		/* #define ERR_BADCHANMASK      476 */
		cannot_join_channel(from, ArgList);
		break;

	case 484:		/* #define ERR_RESTRICTED       484 */
		if (do_hook(current_numeric(), "%s %s", from, *ArgList))
			display_msg(from, ArgList);
		server_set_flag(parsing_server(), USER_MODE_R, 1);
		break;

		/*
		 * The following accumulates the remaining arguments
		 * in ArgSpace for hook detection.  We can't use
		 * PasteArgs here because we still need the arguments
		 * separated for use elsewhere.
		 */
	default:
		{
			u_char	*ArgSpace = NULL;
			int	i,
				do_message_from = 0;
			size_t	len;

			for (i = len = 0; ArgList[i]; len += my_strlen(ArgList[i++]))
				;
			len += (i - 1);
			ArgSpace = new_malloc(len + 1);
			ArgSpace[0] = '\0';
			/* this is cheating */
			if (ArgList[0] && is_channel(ArgList[0]))
				do_message_from = 1;
			for (i = 0; ArgList[i]; i++)
			{
				if (i)
					my_strcat(ArgSpace, " ");
				my_strcat(ArgSpace, ArgList[i]);
			}
			if (do_message_from)
				message_from(ArgList[0], LOG_CRAP);
			i = do_hook(current_numeric(), "%s %s", from, ArgSpace);
			new_free(&ArgSpace);
			if (do_message_from)
				restore_message_from();
			if (i == 0)
				goto done;
			none_of_these = 1;
		}
	}
	/* the following do not hurt the ircII if intercepted by a hook */
	if (none_of_these)
	{
		switch (comm)
		{
		case 221: 		/* #define RPL_UMODEIS          221 */
			put_it("%s Your user mode is \"%s\"", numeric_banner(),
				ArgList[0]);
			break;

		case 242:		/* #define RPL_STATSUPTIME      242 */
			PasteArgs(ArgList, 0);
			if (from && !my_strnicmp(server_get_itsname(parsing_server()),
			    from, my_strlen(server_get_itsname(parsing_server()))))
				from = NULL;
			if (from)
				put_it("%s %s from (%s)", numeric_banner(),
					*ArgList, from);
			else
				put_it("%s %s", numeric_banner(), *ArgList);
			break;

		case 332:		/* #define RPL_TOPIC            332 */
			channel_topic(from, ArgList);
			break;

		case 351:		/* #define RPL_VERSION          351 */
			version(from, ArgList);
			break;

		case 364:		/* #define RPL_LINKS            364 */
			if (ArgList[2])
			{
				PasteArgs(ArgList, 2);
				put_it("%s %-20s %-20s %s", numeric_banner(),
					ArgList[0], ArgList[1], ArgList[2]);
			}
			else
			{
				PasteArgs(ArgList, 1);
				put_it("%s %-20s %s", numeric_banner(),
					ArgList[0], ArgList[1]);
			}
			break;

		case 372:		/* #define RPL_MOTD             372 */
			if (!get_int_var(SUPPRESS_SERVER_MOTD_VAR) ||
			    !server_get_motd(parsing_server()))
			{
				PasteArgs(ArgList, 0);
				put_it("%s %s", numeric_banner(), ArgList[0]);
			}
			break;

		case 375:		/* #define RPL_MOTDSTART        375 */
			if (!get_int_var(SUPPRESS_SERVER_MOTD_VAR) ||
			    !server_get_motd(parsing_server()))
			{
				PasteArgs(ArgList, 0);
				put_it("%s %s", numeric_banner(), ArgList[0]);
			}
			break;

		case 376:		/* #define RPL_ENDOFMOTD        376 */
			if (server_get_attempting_to_connect(parsing_server()))
				got_initial_version(UP("*** Your host is broken and not running any version"));
			if (get_int_var(SHOW_END_OF_MSGS_VAR) &&
			    (!get_int_var(SUPPRESS_SERVER_MOTD_VAR) ||
			    !server_get_motd(parsing_server())))
			{
				PasteArgs(ArgList, 0);
				put_it("%s %s", numeric_banner(), ArgList[0]);
			}
			server_set_motd(parsing_server(), 0);
			break;

		case 384:		/* #define RPL_MYPORTIS         384 */
			PasteArgs(ArgList, 0);
			put_it("%s %s %s", numeric_banner(), ArgList[0], user);
			break;

		case 385:		/* #define RPL_NOTOPERANYMORE   385 */
			server_set_operator(parsing_server(), 0);
			display_msg(from, ArgList);
			update_all_status();
			break;

		case 403:		/* #define ERR_NOSUCHCHANNEL    403 */
			not_valid_channel(from, ArgList);
			break;

		case 451:		/* #define ERR_NOTREGISTERED    451 */
	/*
	 * Sometimes the server doesn't catch the USER line, so
	 * here we send a simplified version again  -lynx 
	 */
			send_to_server("USER %s %s . :%s", my_username(),
				irc_umode(), my_realname());
			send_to_server("NICK %s",
				server_get_nickname(parsing_server()));
			break;

		case 462:		/* #define ERR_ALREADYREGISTRED 462 */
			display_msg(from, ArgList);
			break;

#define RPL_CLOSEEND         363
#define RPL_SERVLISTEND      235
		case 315:		/* #define RPL_ENDOFWHO         315 */
		case 323:               /* #define RPL_LISTEND          323 */
			funny_print_widelist();

		case 219:		/* #define RPL_ENDOFSTATS       219 */
		case 232:		/* #define RPL_ENDOFSERVICES    232 */
		case 365:		/* #define RPL_ENDOFLINKS       365 */
		case 368:		/* #define RPL_ENDOFBANLIST     368 */
		case 369:		/* #define RPL_ENDOFWHOWAS      369 */
		case 374:		/* #define RPL_ENDOFINFO        374 */
#if 0	/* this case needs special handing - see above */
		case 376:		/* #define RPL_ENDOFMOTD        376 */
#endif /* 0 */
		case 394:		/* #define RPL_ENDOFUSERS       394 */
			if (!get_int_var(SHOW_END_OF_MSGS_VAR))
				break;
		default:
			display_msg(from, ArgList);
		}
	}
	set_lastlog_msg_level(lastlog_level);
done:
	restore_message_from();
}
Пример #14
0
int
CondorQ::fetchQueueFromHostAndProcessV2(const char *host,
					const char *constraint,
					StringList &attrs,
					int fetch_opts,
					int match_limit,
					condor_q_process_func process_func,
					void * process_func_data,
					int connect_timeout,
					int useFastPath,
					CondorError *errstack,
					ClassAd ** psummary_ad)
{
	classad::ClassAdParser parser;
	classad::ExprTree *expr = NULL;
	parser.ParseExpression(constraint, expr);
	if (!expr) return Q_INVALID_REQUIREMENTS;

	classad::ClassAd request_ad;  // query ad to send to schedd
	ClassAd *ad = NULL;	// job ad result

	request_ad.Insert(ATTR_REQUIREMENTS, expr);

	char *projection = attrs.print_to_delimed_string("\n");
	if (projection) {
		request_ad.InsertAttr(ATTR_PROJECTION, projection);
		free(projection);
	}

	bool want_authentication = false;
	if (fetch_opts == fetch_DefaultAutoCluster) {
		request_ad.InsertAttr("QueryDefaultAutocluster", true);
		request_ad.InsertAttr("MaxReturnedJobIds", 2); // TODO: make this settable by caller of this function.
	} else if (fetch_opts == fetch_GroupBy) {
		request_ad.InsertAttr("ProjectionIsGroupBy", true);
		request_ad.InsertAttr("MaxReturnedJobIds", 2); // TODO: make this settable by caller of this function.
	} else {
		if (fetch_opts & fetch_MyJobs) {
			const char * owner = my_username();
			if (owner) { request_ad.InsertAttr("Me", owner); }
			request_ad.InsertAttr("MyJobs", owner ? "(Owner == Me)" : "true");
			want_authentication = true;
		}
		if (fetch_opts & fetch_SummaryOnly) {
			request_ad.InsertAttr("SummaryOnly", true);
		}
		if (fetch_opts & fetch_IncludeClusterAd) {
			request_ad.InsertAttr("IncludeClusterAd", true);
		}
	}

	if (match_limit >= 0) {
		request_ad.InsertAttr(ATTR_LIMIT_RESULTS, match_limit);
	}

	// determine if authentication can/will happen.  three reasons why it might not:
	// 1) security negotiation is disabled (NEVER or OPTIONAL for outgoing connections)
	// 2) Authentication is disabled (NEVER) by the client
	// 3) Authentication is disabled (NEVER) by the server.  this is actually impossible to
	//    get correct without actually querying the server but we make an educated guess by
	//    paraming the READ auth level.
	bool can_auth = true;
	char *paramer = NULL;

	paramer = SecMan::getSecSetting ("SEC_%s_NEGOTIATION", CLIENT_PERM);
	if (paramer != NULL) {
		char p = toupper(paramer[0]);
		free(paramer);
		if (p == 'N' || p == 'O') {
			// authentication will not happen since no security negotiation will occur
			can_auth = false;
		}
	}

	paramer = SecMan::getSecSetting ("SEC_%s_AUTHENTICATION", CLIENT_PERM);
	if (paramer != NULL) {
		char p = toupper(paramer[0]);
		free(paramer);
		if (p == 'N') {
			// authentication will not happen since client doesn't allow it.
			can_auth = false;
		}
	}

	// authentication will not happen since server probably doesn't allow it.
	// on the off chance that someone's config manages to trick us, leave an
	// undocumented knob as a last resort to disable our inference.
	if (param_boolean("CONDOR_Q_INFER_SCHEDD_AUTHENTICATION", true)) {
		paramer = SecMan::getSecSetting ("SEC_%s_AUTHENTICATION", READ);
		if (paramer != NULL) {
			char p = toupper(paramer[0]);
			free(paramer);
			if (p == 'N') {
				can_auth = false;
			}
		}

		paramer = SecMan::getSecSetting ("SCHEDD.SEC_%s_AUTHENTICATION", READ);
		if (paramer != NULL) {
			char p = toupper(paramer[0]);
			free(paramer);
			if (p == 'N') {
				can_auth = false;
			}
		}
	}

	if (!can_auth) {
		dprintf (D_ALWAYS, "detected that authentication will not happen.  falling back to QUERY_JOB_ADS without authentication.\n");
	}

	DCSchedd schedd(host);
	int cmd = QUERY_JOB_ADS;
	if (want_authentication && can_auth && (useFastPath > 2)) {
		cmd = QUERY_JOB_ADS_WITH_AUTH;
	}
	Sock* sock;
	if (!(sock = schedd.startCommand(cmd, Stream::reli_sock, connect_timeout, errstack))) return Q_SCHEDD_COMMUNICATION_ERROR;

	classad_shared_ptr<Sock> sock_sentry(sock);

	if (!putClassAd(sock, request_ad) || !sock->end_of_message()) return Q_SCHEDD_COMMUNICATION_ERROR;
	dprintf(D_FULLDEBUG, "Sent classad to schedd\n");

	int rval = 0;
	do {
		ad = new ClassAd();
		if ( ! getClassAd(sock, *ad) || ! sock->end_of_message()) {
			rval = Q_SCHEDD_COMMUNICATION_ERROR;
			break;
		}
		dprintf(D_FULLDEBUG, "Got classad from schedd.\n");
		long long intVal;
		if (ad->EvaluateAttrInt(ATTR_OWNER, intVal) && (intVal == 0))
		{ // Last ad.
			sock->close();
			dprintf(D_FULLDEBUG, "Ad was last one from schedd.\n");
			std::string errorMsg;
			if (ad->EvaluateAttrInt(ATTR_ERROR_CODE, intVal) && intVal && ad->EvaluateAttrString(ATTR_ERROR_STRING, errorMsg))
			{
				if (errstack) errstack->push("TOOL", intVal, errorMsg.c_str());
				rval = Q_REMOTE_ERROR;
			}
			if (psummary_ad && rval == 0) {
				std::string val;
				if (ad->LookupString(ATTR_MY_TYPE, val) && val == "Summary") {
					ad->Delete(ATTR_OWNER); // remove the bogus owner attribute
					*psummary_ad = ad; // return the final ad, because it has summary information
					ad = NULL; // so we don't delete it below.
				}
			}
			break;
		}
		// Note: According to condor_q.h, process_func() will return false if taking
		// ownership of ad, so only delete if it returns true, else set to NULL
		// so we don't delete it here.  Either way, next set ad to NULL since either
		// it has been deleted or will be deleted later by process_func().
		if (process_func(process_func_data, ad)) {
			delete ad;
		}
		ad = NULL;
	} while (true);

	// Make sure ad is not leaked no matter how we break out of the above loop.
	delete ad;

	return rval;
}
Пример #15
0
int main(int argc, char *argv[]) {

    MyString my_full_name;
    const char *full_name;
    char* pw = NULL;
    struct StoreCredOptions options;
    int result = FAILURE_ABORTED;
    bool pool_password_arg = false;
    bool pool_password_delete = false;
    Daemon *daemon = NULL;
    char *credd_host;

    MyName = condor_basename(argv[0]);

    // load up configuration file
    myDistro->Init( argc, argv );
    config();

    if (!parseCommandLine(&options, argc, argv)) {
        goto cleanup;
    }

    // if -h was given, just print usage
    if (options.help || (options.mode == 0)) {
        usage();
        goto cleanup;
    }

#if !defined(WIN32)
    // if the -f argument was given, we just want to prompt for a password
    // and write it to a file (in our weirdo XORed format)
    //
    if (options.password_file != NULL) {
        if (options.pw[0] == '\0') {
            pw = get_password();
            printf("\n");
        }
        else {
            pw = strnewp(options.pw);
            SecureZeroMemory(options.pw, MAX_PASSWORD_LENGTH + 1);
        }
        result = write_password_file(options.password_file, pw);
        SecureZeroMemory(pw, strlen(pw));
        if (result != SUCCESS) {
            fprintf(stderr,
                    "error writing password file: %s\n",
                    options.password_file);
        }
        goto cleanup;
    }
#endif

    // determine the username to use
    if ( strcmp(options.username, "") == 0 ) {
        // default to current user and domain
        char* my_name = my_username();
        char* my_domain = my_domainname();

        my_full_name.formatstr("%s@%s", my_name, my_domain);
        if ( my_name) {
            free(my_name);
        }
        if ( my_domain) {
            free(my_domain);
        }
        my_name = my_domain = NULL;
    } else if (strcmp(options.username, POOL_PASSWORD_USERNAME) == 0) {
#if !defined(WIN32)
        // we don't support querying the pool password on UNIX
        // (since it is not possible to do so through the
        //  STORE_POOL_CRED command)
        if (options.mode == QUERY_MODE) {
            fprintf(stderr, "Querying the pool password is not supported.\n");
            goto cleanup;
        }
#endif
        // append the correct domain name if we're using the pool pass
        // we first try POOL_PASSWORD_DOMAIN, then UID_DOMAIN
        pool_password_arg = true;
        char *domain;
        if ((domain = param("SEC_PASSWORD_DOMAIN")) == NULL) {
            if ((domain = param("UID_DOMAIN")) == NULL) {
                fprintf(stderr, "ERROR: could not domain for pool password\n");
                goto cleanup;
            }
        }
        my_full_name.formatstr(POOL_PASSWORD_USERNAME "@%s", domain);
        free(domain);
    } else {
        // username was specified on the command line
        my_full_name += options.username;
    }
    full_name = my_full_name.Value();
    printf("Account: %s\n\n", full_name);

    // determine where to direct our command
    daemon = NULL;
    credd_host = NULL;
    if (options.daemonname != NULL) {
        if (pool_password_arg && (options.mode != QUERY_MODE)) {
            // daemon named on command line; go to master for pool password
            //printf("sending command to master: %s\n", options.daemonname);
            daemon = new Daemon(DT_MASTER, options.daemonname);
        }
        else {
            // daemon named on command line; go to schedd for user password
            //printf("sending command to schedd: %s\n", options.daemonname);
            daemon = new Daemon(DT_SCHEDD, options.daemonname);
        }
    }
    else if (!pool_password_arg && ((credd_host = param("CREDD_HOST")) != NULL)) {
        // no daemon given, use credd for user passwords if CREDD_HOST is defined
        // (otherwise, we use the local schedd)
        //printf("sending command to CREDD: %s\n", credd_host);
        daemon = new Daemon(DT_CREDD);
    }
    else {
        //printf("sending command to local daemon\n");
    }

    // flag the case where we're deleting the pool password
    if (pool_password_arg && (options.mode == DELETE_MODE)) {
        pool_password_delete = true;
    }

    switch (options.mode) {
    case ADD_MODE:
    case DELETE_MODE:
        if (!pool_password_delete) {
            if ( strcmp(options.pw, "") == 0 ) {
                // get password from the user.
                pw = get_password();
                printf("\n\n");
            } else {
                // got the passwd from the command line.
                pw = strnewp(options.pw);
                SecureZeroMemory(options.pw, MAX_PASSWORD_LENGTH);
            }
        }
        if ( pw || pool_password_delete) {
            result = store_cred(full_name, pw, options.mode, daemon);
            if ((result == FAILURE_NOT_SECURE) && goAheadAnyways()) {
                // if user is ok with it, send the password in the clear
                result = store_cred(full_name, pw, options.mode, daemon, true);
            }
            if (pw) {
                SecureZeroMemory(pw, strlen(pw));
                delete[] pw;
            }
        }
        break;
    case QUERY_MODE:
        result = queryCredential(full_name, daemon);
        break;
#if defined(WIN32)
    case CONFIG_MODE:
        return interactive();
        break;
#endif
    default:
        fprintf(stderr, "Internal error\n");
        goto cleanup;
    }

    // output result of operation
    switch (result) {
    case SUCCESS:
        if (options.mode == QUERY_MODE) {
            printf("A credential is stored and is valid.\n");
        }
        else {
            printf("Operation succeeded.\n");
        }
        break;

    case FAILURE:
        printf("Operation failed.\n");
        if (pool_password_arg && (options.mode != QUERY_MODE)) {
            printf("    Make sure you have CONFIG access to the target Master.\n");
        }
        else {
            printf("    Make sure your ALLOW_WRITE setting includes this host.\n");
        }
        break;

    case FAILURE_BAD_PASSWORD:
        if (options.mode == QUERY_MODE) {
            printf("A credential is stored, but it is invalid. "
                   "Run 'condor_store_cred add' again.\n");
        }
        else {
            printf("Operation failed: bad password.\n");
        }
        break;

    case FAILURE_NOT_FOUND:
        if (options.mode == QUERY_MODE) {
            printf("No credential is stored.\n");
        }
        else {
            printf("Operation failed: username not found.\n");
        }
        break;

    case FAILURE_NOT_SECURE:
    case FAILURE_ABORTED:
        printf("Operation aborted.\n");
        break;

    case FAILURE_NOT_SUPPORTED:
        printf("Operation failed.\n"
               "    The target daemon is not running as SYSTEM.\n");
        break;

    default:
        fprintf(stderr, "Operation failed: unknown error code\n");
    }

cleanup:
    if (options.daemonname) {
        delete[] options.daemonname;
    }
    if (daemon) {
        delete daemon;
    }

    if ( result == SUCCESS ) {
        return 0;
    } else {
        return 1;
    }
}
Пример #16
0
//---------------------------------------------------------------------------
void main_init (int argc, char ** const argv) {

	printf ("Executing condor dagman ... \n");

		// flag used if DAGMan is invoked with -WaitForDebug so we
		// wait for a developer to attach with a debugger...
	volatile int wait_for_debug = 0;

		// process any config vars -- this happens before we process
		// argv[], since arguments should override config settings
	dagman.Config();

	// The DCpermission (last parm) should probably be PARENT, if it existed
    daemonCore->Register_Signal( SIGUSR1, "SIGUSR1",
                                 (SignalHandler) main_shutdown_remove,
                                 "main_shutdown_remove", NULL);

/****** FOR TESTING *******
    daemonCore->Register_Signal( SIGUSR2, "SIGUSR2",
                                 (SignalHandler) main_testing_stub,
                                 "main_testing_stub", NULL);
****** FOR TESTING ********/
    debug_progname = condor_basename(argv[0]);

		// condor_submit_dag version from .condor.sub
	bool allowVerMismatch = false;
	const char *csdVersion = "undefined";

	int i;
    for (i = 0 ; i < argc ; i++) {
        debug_printf( DEBUG_NORMAL, "argv[%d] == \"%s\"\n", i, argv[i] );
    }

    if (argc < 2) Usage();  //  Make sure an input file was specified

		// get dagman job id from environment, if it's there
		// (otherwise it will be set to "-1.-1.-1")
	dagman.DAGManJobId.SetFromString( getenv( EnvGetName( ENV_ID ) ) );

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		// Minimum legal version for a .condor.sub file to be compatible
		// with this condor_dagman binary.

		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		// Be sure to change this if the arguments or environment
		// passed to condor_dagman change in an incompatible way!!
		// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

	struct DagVersionData {
		int majorVer;
		int minorVer;
		int subMinorVer;
	};
	const DagVersionData MIN_SUBMIT_FILE_VERSION = { 7, 1, 2 };

		// Construct a string of the minimum submit file version.
	MyString minSubmitVersionStr;
	minSubmitVersionStr.formatstr( "%d.%d.%d",
				MIN_SUBMIT_FILE_VERSION.majorVer,
				MIN_SUBMIT_FILE_VERSION.minorVer,
				MIN_SUBMIT_FILE_VERSION.subMinorVer );
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    //
    // Process command-line arguments
    //
    for (i = 1; i < argc; i++) {
        if( !strcasecmp( "-Debug", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT, "No debug level specified\n" );
                Usage();
            }
            debug_level = (debug_level_t) atoi (argv[i]);
        } else if( !strcasecmp( "-Lockfile", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT, "No DagMan lockfile specified\n" );
                Usage();
            }
            lockFileName = argv[i];
        } else if( !strcasecmp( "-Help", argv[i] ) ) {
            Usage();
        } else if (!strcasecmp( "-Dag", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT, "No DAG specified\n" );
                Usage();
            }
			dagman.dagFiles.append( argv[i] );
        } else if( !strcasecmp( "-MaxIdle", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT,
							  "Integer missing after -MaxIdle\n" );
                Usage();
            }
            dagman.maxIdle = atoi( argv[i] );
        } else if( !strcasecmp( "-MaxJobs", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT,
							  "Integer missing after -MaxJobs\n" );
                Usage();
            }
            dagman.maxJobs = atoi( argv[i] );
        } else if( !strcasecmp( "-MaxScripts", argv[i] ) ) {
			debug_printf( DEBUG_SILENT, "-MaxScripts has been replaced with "
						   "-MaxPre and -MaxPost arguments\n" );
			Usage();
        } else if( !strcasecmp( "-MaxPre", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT,
							  "Integer missing after -MaxPre\n" );
                Usage();
            }
            dagman.maxPreScripts = atoi( argv[i] );
        } else if( !strcasecmp( "-MaxPost", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT,
							  "Integer missing after -MaxPost\n" );
                Usage();
            }
            dagman.maxPostScripts = atoi( argv[i] );
        } else if( !strcasecmp( "-NoEventChecks", argv[i] ) ) {
			debug_printf( DEBUG_QUIET, "Warning: -NoEventChecks is "
						"ignored; please use the DAGMAN_ALLOW_EVENTS "
						"config parameter instead\n");
			check_warning_strictness( DAG_STRICT_1 );

        } else if( !strcasecmp( "-AllowLogError", argv[i] ) ) {
			dagman.allowLogError = true;

        } else if( !strcasecmp( "-DontAlwaysRunPost",argv[i] ) ) {
			dagman._runPost = false;

        } else if( !strcasecmp( "-WaitForDebug", argv[i] ) ) {
			wait_for_debug = 1;

        } else if( !strcasecmp( "-UseDagDir", argv[i] ) ) {
			dagman.useDagDir = true;

        } else if( !strcasecmp( "-AutoRescue", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT, "No AutoRescue value specified\n" );
                Usage();
            }
            dagman.autoRescue = (atoi( argv[i] ) != 0);

        } else if( !strcasecmp( "-DoRescueFrom", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT, "No rescue DAG number specified\n" );
                Usage();
            }
            dagman.doRescueFrom = atoi (argv[i]);

        } else if( !strcasecmp( "-CsdVersion", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT, "No CsdVersion value specified\n" );
                Usage();
            }
			csdVersion = argv[i];

        } else if( !strcasecmp( "-AllowVersionMismatch", argv[i] ) ) {
			allowVerMismatch = true;

        } else if( !strcasecmp( "-DumpRescue", argv[i] ) ) {
			dagman.dumpRescueDag = true;

        } else if( !strcasecmp( "-verbose", argv[i] ) ) {
			dagman._submitDagDeepOpts.bVerbose = true;

        } else if( !strcasecmp( "-force", argv[i] ) ) {
			dagman._submitDagDeepOpts.bForce = true;
		
        } else if( !strcasecmp( "-notification", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT, "No notification value specified\n" );
                Usage();
            }
			dagman._submitDagDeepOpts.strNotification = argv[i];

        } else if( !strcasecmp( "-dagman", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT, "No dagman value specified\n" );
                Usage();
            }
			dagman._submitDagDeepOpts.strDagmanPath = argv[i];

        } else if( !strcasecmp( "-outfile_dir", argv[i] ) ) {
            i++;
            if( argc <= i || strcmp( argv[i], "" ) == 0 ) {
                debug_printf( DEBUG_SILENT, "No outfile_dir value specified\n" );
                Usage();
            }
			dagman._submitDagDeepOpts.strOutfileDir = argv[i];

        } else if( !strcasecmp( "-update_submit", argv[i] ) ) {
			dagman._submitDagDeepOpts.updateSubmit = true;

        } else if( !strcasecmp( "-import_env", argv[i] ) ) {
			dagman._submitDagDeepOpts.importEnv = true;

        } else if( !strcasecmp( "-priority", argv[i] ) ) {
		++i;
		if( i >= argc || strcmp( argv[i], "" ) == 0 ) {
			debug_printf( DEBUG_NORMAL, "No priority value specified\n");
			Usage();
		}
		dagman._submitDagDeepOpts.priority = atoi(argv[i]);
		} else if( !strcasecmp( "-dont_use_default_node_log", argv[i] ) ) {
			dagman._submitDagDeepOpts.always_use_node_log = false;
        } else {
    		debug_printf( DEBUG_SILENT, "\nUnrecognized argument: %s\n",
						argv[i] );
			Usage();
		}
    }

	dagman.dagFiles.rewind();
	dagman.primaryDagFile = dagman.dagFiles.next();
	dagman.multiDags = (dagman.dagFiles.number() > 1);

	MyString tmpDefaultLog;
	if ( dagman._defaultNodeLog != NULL ) {
		tmpDefaultLog = dagman._defaultNodeLog;
		free( dagman._defaultNodeLog );
	} else {
		tmpDefaultLog = dagman.primaryDagFile + ".nodes.log";
	}

		// Force default log file path to be absolute so it works
		// with -usedagdir and DIR nodes.
	CondorError errstack;
	if ( !MultiLogFiles::makePathAbsolute( tmpDefaultLog, errstack) ) {
       	debug_printf( DEBUG_QUIET, "Unable to convert default log "
					"file name to absolute path: %s\n",
					errstack.getFullText().c_str() );
		dagman.dag->GetJobstateLog().WriteDagmanFinished( EXIT_ERROR );
		DC_Exit( EXIT_ERROR );
	}
	dagman._defaultNodeLog = strdup( tmpDefaultLog.Value() );
	debug_printf( DEBUG_NORMAL, "Default node log file is: <%s>\n",
				dagman._defaultNodeLog);

    //
    // Check the arguments
    //

	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// Checking for version compatibility between the .condor.sub
	// file and this condor_dagman binary...

	// Note: if we're in recovery mode and the submit file version
	// causes us to quit, we leave any existing node jobs still
	// running -- may want to change that eventually.  wenger 2009-10-13.

		// Version of the condor_submit_dag that created our submit file.
	CondorVersionInfo submitFileVersion( csdVersion );

		// Version of this condor_dagman binary.
	CondorVersionInfo dagmanVersion;

		// Just generate this message fragment in one place.
	MyString versionMsg;
	versionMsg.formatstr("the version (%s) of this DAG's Condor submit "
				"file (created by condor_submit_dag)", csdVersion );

		// Make sure version in submit file is valid.
	if( !submitFileVersion.is_valid() ) {
		if ( !allowVerMismatch ) {
        	debug_printf( DEBUG_QUIET, "Error: %s is invalid!\n",
						versionMsg.Value() );
			DC_Exit( EXIT_ERROR );
		} else {
        	debug_printf( DEBUG_NORMAL, "Warning: %s is invalid; "
						"continuing because of -AllowVersionMismatch flag\n",
						versionMsg.Value() );
		}

		// Make sure .condor.sub file is recent enough.
	} else if ( submitFileVersion.compare_versions(
				CondorVersion() ) != 0 ) {

		if( !submitFileVersion.built_since_version(
					MIN_SUBMIT_FILE_VERSION.majorVer,
					MIN_SUBMIT_FILE_VERSION.minorVer,
					MIN_SUBMIT_FILE_VERSION.subMinorVer ) ) {
			if ( !allowVerMismatch ) {
        		debug_printf( DEBUG_QUIET, "Error: %s is older than "
							"oldest permissible version (%s)\n",
							versionMsg.Value(), minSubmitVersionStr.Value() );
				DC_Exit( EXIT_ERROR );
			} else {
        		debug_printf( DEBUG_NORMAL, "Warning: %s is older than "
							"oldest permissible version (%s); continuing "
							"because of -AllowVersionMismatch flag\n",
							versionMsg.Value(), minSubmitVersionStr.Value() );
			}

			// Warn if .condor.sub file is a newer version than this binary.
		} else if (dagmanVersion.compare_versions( csdVersion ) > 0 ) {
        	debug_printf( DEBUG_NORMAL, "Warning: %s is newer than "
						"condor_dagman version (%s)\n", versionMsg.Value(),
						CondorVersion() );
			check_warning_strictness( DAG_STRICT_3 );
		} else {
        	debug_printf( DEBUG_NORMAL, "Note: %s differs from "
						"condor_dagman version (%s), but the "
						"difference is permissible\n", 
						versionMsg.Value(), CondorVersion() );
		}
	}
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    if( dagman.primaryDagFile == "" ) {
        debug_printf( DEBUG_SILENT, "No DAG file was specified\n" );
        Usage();
    }
    if (lockFileName == NULL) {
        debug_printf( DEBUG_SILENT, "No DAG lock file was specified\n" );
        Usage();
    }
    if( dagman.maxJobs < 0 ) {
        debug_printf( DEBUG_SILENT, "-MaxJobs must be non-negative\n");
        Usage();
    }
    if( dagman.maxPreScripts < 0 ) {
        debug_printf( DEBUG_SILENT, "-MaxPre must be non-negative\n" );
        Usage();
    }
    if( dagman.maxPostScripts < 0 ) {
        debug_printf( DEBUG_SILENT, "-MaxPost must be non-negative\n" );
        Usage();
    }
    if( dagman.doRescueFrom < 0 ) {
        debug_printf( DEBUG_SILENT, "-DoRescueFrom must be non-negative\n" );
        Usage();
    }

    debug_printf( DEBUG_VERBOSE, "DAG Lockfile will be written to %s\n",
                   lockFileName );
	if ( dagman.dagFiles.number() == 1 ) {
    	debug_printf( DEBUG_VERBOSE, "DAG Input file is %s\n",
				  	dagman.primaryDagFile.Value() );
	} else {
		MyString msg = "DAG Input files are ";
		dagman.dagFiles.rewind();
		const char *dagFile;
		while ( (dagFile = dagman.dagFiles.next()) != NULL ) {
			msg += dagFile;
			msg += " ";
		}
		msg += "\n";
    	debug_printf( DEBUG_VERBOSE, "%s", msg.Value() );
	}

		// if requested, wait for someone to attach with a debugger...
	while( wait_for_debug ) { }

    {
		MyString cwd;
		if( !condor_getcwd(cwd) ) {
			cwd = "<null>";
		}
        debug_printf( DEBUG_DEBUG_1, "Current path is %s\n",cwd.Value());

		char *temp = my_username();
		debug_printf( DEBUG_DEBUG_1, "Current user is %s\n",
					   temp ? temp : "<null>" );
		if( temp ) {
			free( temp );
		}
    }

		//
		// Figure out the rescue DAG to run, if any (this is with "new-
		// style" rescue DAGs).
		//
	int rescueDagNum = 0;
	MyString rescueDagMsg;

	if ( dagman.doRescueFrom != 0 ) {
		rescueDagNum = dagman.doRescueFrom;
		rescueDagMsg.formatstr( "Rescue DAG number %d specified", rescueDagNum );
		RenameRescueDagsAfter( dagman.primaryDagFile.Value(),
					dagman.multiDags, rescueDagNum, dagman.maxRescueDagNum );

	} else if ( dagman.autoRescue ) {
		rescueDagNum = FindLastRescueDagNum(
					dagman.primaryDagFile.Value(),
					dagman.multiDags, dagman.maxRescueDagNum );
		rescueDagMsg.formatstr( "Found rescue DAG number %d", rescueDagNum );
	}

		//
		// Fill in values in the deep submit options that we haven't
		// already set.
		//
	dagman._submitDagDeepOpts.bAllowLogError = dagman.allowLogError;
	dagman._submitDagDeepOpts.useDagDir = dagman.useDagDir;
	dagman._submitDagDeepOpts.autoRescue = dagman.autoRescue;
	dagman._submitDagDeepOpts.doRescueFrom = dagman.doRescueFrom;
	dagman._submitDagDeepOpts.allowVerMismatch = allowVerMismatch;
	dagman._submitDagDeepOpts.recurse = false;

    //
    // Create the DAG
    //

	// Note: a bunch of the parameters we pass here duplicate things
	// in submitDagOpts, but I'm keeping them separate so we don't have to
	// bother to construct a new SubmitDagOtions object for splices.
	// wenger 2010-03-25
    dagman.dag = new Dag( dagman.dagFiles, dagman.maxJobs,
						  dagman.maxPreScripts, dagman.maxPostScripts,
						  dagman.allowLogError, dagman.useDagDir,
						  dagman.maxIdle, dagman.retrySubmitFirst,
						  dagman.retryNodeFirst, dagman.condorRmExe,
						  dagman.storkRmExe, &dagman.DAGManJobId,
						  dagman.prohibitMultiJobs, dagman.submitDepthFirst,
						  dagman._defaultNodeLog,
						  dagman._generateSubdagSubmits,
						  &dagman._submitDagDeepOpts,
						  false ); /* toplevel dag! */

    if( dagman.dag == NULL ) {
        EXCEPT( "ERROR: out of memory!\n");
    }

	dagman.dag->SetAbortOnScarySubmit( dagman.abortOnScarySubmit );
	dagman.dag->SetAllowEvents( dagman.allow_events );
	dagman.dag->SetConfigFile( dagman._dagmanConfigFile );
	dagman.dag->SetMaxJobHolds( dagman._maxJobHolds );
	dagman.dag->SetPostRun(dagman._runPost);
	if( dagman._submitDagDeepOpts.priority != 0 ) { // From command line
		dagman.dag->SetDefaultPriority(dagman._submitDagDeepOpts.priority);
	} else if( dagman._defaultPriority != 0 ) { // From config file
		dagman.dag->SetDefaultPriority(dagman._defaultPriority);
		dagman._submitDagDeepOpts.priority = dagman._defaultPriority;
	}

    //
    // Parse the input files.  The parse() routine
    // takes care of adding jobs and dependencies to the DagMan
    //
	dagman.mungeNodeNames = (dagman.dagFiles.number() > 1);
	parseSetDoNameMunge( dagman.mungeNodeNames );
   	debug_printf( DEBUG_VERBOSE, "Parsing %d dagfiles\n", 
		dagman.dagFiles.number() );
	dagman.dagFiles.rewind();
	char *dagFile;

	// Here we make a copy of the dagFiles for iteration purposes. Deep inside
	// of the parsing, copies of the dagman.dagFile string list happen which
	// mess up the iteration of this list.
	StringList sl( dagman.dagFiles );
	sl.rewind();
	while ( (dagFile = sl.next()) != NULL ) {
    	debug_printf( DEBUG_VERBOSE, "Parsing %s ...\n", dagFile );

    	if( !parse( dagman.dag, dagFile, dagman.useDagDir ) ) {
			if ( dagman.dumpRescueDag ) {
					// Dump the rescue DAG so we can see what we got
					// in the failed parse attempt.
    			debug_printf( DEBUG_QUIET, "Dumping rescue DAG "
							"because of -DumpRescue flag\n" );
				dagman.dag->Rescue( dagman.primaryDagFile.Value(),
							dagman.multiDags, dagman.maxRescueDagNum,
							false, true, false );
			}
			
			dagman.dag->RemoveRunningJobs(dagman, true);
			MSC_SUPPRESS_WARNING_FIXME(6031) // return falue of unlink ignored.
			unlink( lockFileName );
			dagman.CleanUp();
			
				// Note: debug_error calls DC_Exit().
        	debug_error( 1, DEBUG_QUIET, "Failed to parse %s\n",
					 	dagFile );
    	}
	}
	if( dagman.dag->GetDefaultPriority() != 0 ) {
		dagman.dag->SetDefaultPriorities(); // Applies to the nodes of the dag
	}
	dagman.dag->GetJobstateLog().WriteDagmanStarted( dagman.DAGManJobId );
	if ( rescueDagNum > 0 ) {
			// Get our Pegasus sequence numbers set correctly.
		dagman.dag->GetJobstateLog().InitializeRescue();
	}

	// lift the final set of splices into the main dag.
	dagman.dag->LiftSplices(SELF);

		//
		// Actually parse the "new-new" style (partial DAG info only)
		// rescue DAG here.  Note: this *must* be done after splices
		// are lifted!
		//
	if ( rescueDagNum > 0 ) {
		dagman.rescueFileToRun = RescueDagName(
					dagman.primaryDagFile.Value(),
					dagman.multiDags, rescueDagNum );
		debug_printf ( DEBUG_QUIET, "%s; running %s in combination with "
					"normal DAG file%s\n", rescueDagMsg.Value(),
					dagman.rescueFileToRun.Value(),
					dagman.multiDags ? "s" : "");
		debug_printf ( DEBUG_QUIET,
					"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");

		debug_printf ( DEBUG_QUIET, "USING RESCUE DAG %s\n",
					dagman.rescueFileToRun.Value() );

			// Turn off node name munging for the rescue DAG, because
			// it will already have munged node names.
		parseSetDoNameMunge( false );

    	if( !parse( dagman.dag, dagman.rescueFileToRun.Value(),
					dagman.useDagDir ) ) {
			if ( dagman.dumpRescueDag ) {
					// Dump the rescue DAG so we can see what we got
					// in the failed parse attempt.
    			debug_printf( DEBUG_QUIET, "Dumping rescue DAG "
							"because of -DumpRescue flag\n" );
				dagman.dag->Rescue( dagman.primaryDagFile.Value(),
							dagman.multiDags, dagman.maxRescueDagNum,
							true, false );
			}
			
			dagman.dag->RemoveRunningJobs(dagman, true);
			MSC_SUPPRESS_WARNING_FIXME(6031) // return falue of unlink ignored.
			unlink( lockFileName );
			dagman.CleanUp();
			
				// Note: debug_error calls DC_Exit().
        	debug_error( 1, DEBUG_QUIET, "Failed to parse %s\n",
					 	dagFile );
    	}
	}

	dagman.dag->CheckThrottleCats();

	// fix up any use of $(JOB) in the vars values for any node
	dagman.dag->ResolveVarsInterpolations();

/*	debug_printf(DEBUG_QUIET, "COMPLETED DAG!\n");*/
/*	dagman.dag->PrintJobList();*/

#ifndef NOT_DETECT_CYCLE
	if( dagman.startup_cycle_detect && dagman.dag->isCycle() )
	{
		// Note: maybe we should run the final node here, if there is one.
		// wenger 2011-12-19.
		debug_error (1, DEBUG_QUIET, "ERROR: a cycle exists in the dag, please check input\n");
	}
#endif
    debug_printf( DEBUG_VERBOSE, "Dag contains %d total jobs\n",
				  dagman.dag->NumNodes( true ) );

	MyString firstLocation;
	if ( dagman.dag->GetReject( firstLocation ) ) {
    	debug_printf( DEBUG_QUIET, "Exiting because of REJECT "
					"specification in %s.  This most likely means "
					"that the DAG file was produced with the -DumpRescue "
					"flag when parsing the original DAG failed.\n",
					firstLocation.Value() );
		DC_Exit( EXIT_ERROR );
		return;
	}

	dagman.dag->DumpDotFile();

	if ( dagman.dumpRescueDag ) {
    	debug_printf( DEBUG_QUIET, "Dumping rescue DAG and exiting "
					"because of -DumpRescue flag\n" );
		dagman.dag->Rescue( dagman.primaryDagFile.Value(),
					dagman.multiDags, dagman.maxRescueDagNum, false,
					false, false );
		ExitSuccess();
		return;
	}

    //------------------------------------------------------------------------
    // Bootstrap and Recovery
    //
    // If the Lockfile exists, this indicates a premature termination
    // of a previous run of Dagman. If condor log is also present,
    // we run in recovery mode
  
    // If the Daglog is not present, then we do not run in recovery
    // mode
  
    {
      bool recovery = access(lockFileName,  F_OK) == 0;
      
        if (recovery) {
            debug_printf( DEBUG_VERBOSE, "Lock file %s detected, \n",
                           lockFileName);
			if (dagman.abortDuplicates) {
				if (util_check_lock_file(lockFileName) == 1) {
        			debug_printf( DEBUG_QUIET, "Aborting because it "
							"looks like another instance of DAGMan is "
							"currently running on this DAG; if that is "
							"not the case, delete the lock file (%s) "
							"and re-submit the DAG.\n", lockFileName );
					dagman.dag->GetJobstateLog().
								WriteDagmanFinished( EXIT_RESTART );
    				dagman.CleanUp();
					DC_Exit( EXIT_ERROR );
					// We should never get to here!
				}
			}
        }

			//
			// If this DAGMan continues, it should overwrite the lock
			// file if it exists.
			//
		util_create_lock_file(lockFileName, dagman.abortDuplicates);

        debug_printf( DEBUG_VERBOSE, "Bootstrapping...\n");
        if( !dagman.dag->Bootstrap( recovery ) ) {
            dagman.dag->PrintReadyQ( DEBUG_DEBUG_1 );
            debug_error( 1, DEBUG_QUIET, "ERROR while bootstrapping\n");
        }
    }

    debug_printf( DEBUG_VERBOSE, "Registering condor_event_timer...\n" );
    daemonCore->Register_Timer( 1, dagman.m_user_log_scan_interval, 
				condor_event_timer, "condor_event_timer" );

	dagman.dag->SetPendingNodeReportInterval(
				dagman.pendingReportInterval );
}