Example #1
0
/*{
** Name: CS_map_sys_segment()	- Map the system control segment to this process
**
** Description:
**	Maps the system control block to this process.  This must happen before
**	any other action can be taken on shared memory (with the exception of
**	CS_create_sys_segment()).
**
**	Upon successful exectution of this routine CS may manipulate the system
**	control data structure CS_SMCNTRL (taking care to use proper semaphore
**	techniques which take into account that the data structure is shared
**	across processes).
**
**	This call is internal to CS is meant only to be called by CS, and may
**	only exist on unix systems supporting shared memory.
**
** Inputs:
**	none.
**
** Outputs:
**      cssm_segment			ptr to the CS_SMCNTRL data structure.
**      err_code			system dependent error information.
**
**	Returns:
**	    E_DB_OK
**
**	Exceptions:
**	    none
**
** Side Effects:
**	    none
**
** History:
**      08-Sep-88 (mmm)
**          First Version
**	12-jun-89 (rogerk)
**	    Added allocated_pages argument to MEget_pages calls.
**	    Changed shared memory key from a LOCATIONN pointer to a character
**	    string.
**      26-aug-89 (rexl)
**          Added calls to protect page allocator.
**	18-oct-1993 (bryanp)
**	    Issue trace messages in failure cases. Simply returning FAIL doesnt
**		help the diagnosis process very much, while the trace messages
**		can help (if the caller has done a TRset_file by this point).
**	14-Oct-1998 (jenjo02)
**	    CS_map_sys_segment(): Don't initialize css_spinlock. That was done 
**	    when the shared segment was created. Reinitializing it may 
**	    effectively destroy a holding process's lock!
**	21-May-2004 (wanfr01)
**	    INGSRV2835, Bug 112371
**	    As per the Jon Jensen's last update, removed the invalid initialize
**	    of css_spinlock.
**	5-Apr-2006 (kschendel)
**	    Use generated css version instead of constant.
** 12-aug-2008 (stephenb)
**		previous change is too strict if programs not shipped with Ingres
**		try to connect to the system segment because the checked version
**		goes right down to the build number. allow some latitude using
**		II_SYSSEG_VERS. If this is set to the current major Ingres 
**		version we will allow the connection. This is an interim 
**		solution to Golden Gate's issue.
*/
STATUS
CS_map_sys_segment(CL_ERR_DESC *err_code)
{
    STATUS	status = OK;
    PTR		address;
    SIZE_TYPE	alloc_pages;

    /* map segment into first available address and then initialize it */
    /* Use "sysseg.mem" as shared memory key. */
    address = 0;
    status = MEget_pages(ME_SSHARED_MASK, 0, "sysseg.mem", &address,
                         &alloc_pages, err_code);

    if (status)
    {
#ifdef xDEBUG
	TRdisplay("CS_map_sys_segment: unable to attach to sysseg.mem (%x)\n",
			status);
#endif
	/* Unable to attach allocated shared memory segment. */
	/* status = FAIL; This isn't a useful error return code! */
    }
    else
    {
    	char	*segvers;
    	i4		segint;
    	
    	Cs_sm_cb = (CS_SMCNTRL *) address;
    	/* 
    	** check if segment version has been provided, if so we'll
    	** deem it O.K. if it matches the current major version
    	*/
    	NMgtAt("II_SYSSEG_VERS", &segvers);
    	if (segvers != (char *)NULL && *segvers != EOS && 
    			CVal(segvers, &segint) == OK && segint == GV_MAJOR)
    		status = OK;
    	else
    	{
    		i4 id = make_css_version();
	
			if (Cs_sm_cb->css_version != id)
			{
			    TRdisplay(
		"CS_map_sys_segment: sysseg.mem is version %x (%d). We need version %x (%d)\n",
				Cs_sm_cb->css_version, Cs_sm_cb->css_version,
				id, id);
			    SETCLERR(err_code, 0, 0);
			    status = FAIL;
			}
    	}
    }

    return(status);
}
Example #2
0
bool check_uuid_mac()
{
	char *uuid_mac=NULL;
	NMgtAt("II_UUID_MAC", &uuid_mac);
	if ((uuid_mac != (char *)NULL && *uuid_mac != EOS) && 
        (STcompare(uuid_mac,"TRUE") == 0))
        {
		return TRUE;        
	}
	else
	{
		return FALSE;
	}
}
Example #3
0
/*{
** Name: get_value()	- get value 
**
** Description:
**	Return value of symbol input.  If symbol is not set in the environment
**	then return "default_value".
**
** Inputs:
**	symbol		The string representation of the symbol (ie. "II_SYM")
**	default_value	An integer default value to be returned if symbol not
**			found in the environment.
** Outputs:
**	none.
**
**
**	Returns:
**	      value of the symbol if set in environment, else returns
**	      whatever "default_value" was input.
**
** History:
**      06-apr-92 (mikem)
**         Created.
*/
static i4
get_value(char *symbol, i4 default_value)
{
    i4		value = default_value; 
    char	*string;
    i4	env_value;
    
    NMgtAt(symbol, &string);
    if (string                &&
	*string               &&
	(!CVal(string, &env_value)))
    {
	/* user override of default */
	value = env_value;
    }

    return(value);
}
Example #4
0
/*
** tcp6_set_trace - sets trace level for TCP.    
*/
static VOID
tcp6_set_trace()
{
	static bool init_trace=FALSE;
	char	*trace;

	if(init_trace)
	    return;

	init_trace=TRUE;

	NMgtAt( "II_TCP_TRACE",  &trace );

	if ( !( trace && *trace ) && PMget("!.tcp_trace_level", &trace) != OK )
	    tcp_trace = 0;
	else
	    tcp_trace =  atoi(trace);
}
Example #5
0
/*{
** Name:	aboslver	-  Initialize the OSL version.
**
** Description:
**	Initialize the OSL version.  On most OS this is a noop.	 On VMS
**	check to capability settings.  If either OSL/QUEL or OSL/SQL are
**	enabled, then it is new OSL.
**
** History:
**	19-jun-1987 (Joe)
**		Initial Version
*/
aboslver()
{
# ifdef VMS
	char	*cp;

	osNewVersion = 1;
	/*
	** Some VMS customers may have old version of OSL.
	** Want a way to test, so allow a logical name to set.
	*/
	NMgtAt(ERx("II_OSL_VERSION"), &cp);
	if (cp != NULL)
	{
		CVlower(cp);
		osNewVersion = !(*cp == 'o');
	}
# else
	osNewVersion = 1;
# endif /* VMS */
}
Example #6
0
bool
cer_istest(void)
{
	char	*nambuf;

	if (test_state == NOTSET)
	{   /* Check the II_MSG_TEST */
		NMgtAt("II_MSG_TEST", &nambuf);
		if (nambuf && *nambuf && 
		    ( STcasecmp(nambuf, "y" ) == 0
		   || STcasecmp(nambuf, "yes" ) == 0
		   || STcasecmp(nambuf, "t" ) == 0
		   || STcasecmp(nambuf, "true" ) == 0 ) )
		{	/* Value is Set */
			test_state = SETON;
		}
		else
		{
			test_state = SETOFF;
		}
	}

	return ((test_state == SETON) ? TRUE : FALSE);
}
Example #7
0
ADF_CB *
FEadfcb ()
{
    if (!done)
    {
	char		*cp;
	DB_STATUS	rval;
	PTR		srv_cb_ptr;
	SIZE_TYPE	srv_size;
	SIZE_TYPE	dbinfo_size;
	PTR		dbinfoptr;
        STATUS          tmtz_status;
        STATUS          date_status;
	char		date_type_alias[100];
        char            col[] = "udefault";
    	STATUS          status = OK;
    	CL_ERR_DESC     sys_err;
	ADUUCETAB	*ucode_ctbl; /* unicode collation information */
        PTR         	ucode_cvtbl;


	
    	done = TRUE;

	/* first, get the size of the ADF's server control block */
	srv_size = adg_srv_size();

	/* allocate enough memory for it */
	if ((srv_cb_ptr = MEreqmem(0, srv_size, FALSE, (STATUS *)NULL)) == NULL)
	{
    	    EXsignal(EXFEBUG, 1, ERx("FEadfcb(alloc)"));
	}

	/*
	**  Fix up code so that "now" works properly for frontends.
	**  Only allocating enough for one (1) dbmsinfo() request.
	*/
	dbinfo_size = sizeof(ADF_TAB_DBMSINFO);
	if ((dbinfoptr = MEreqmem(0, dbinfo_size, TRUE, (STATUS*)NULL)) == NULL)
	{
		IIUGbmaBadMemoryAllocation(ERx("FEadfcb"));
	}

	dbinfo = (ADF_TAB_DBMSINFO *) dbinfoptr;

	dbinfo->tdbi_next = NULL;
	dbinfo->tdbi_prev = NULL;
	dbinfo->tdbi_length = dbinfo_size;
	dbinfo->tdbi_type = ADTDBI_TYPE;
	dbinfo->tdbi_s_reserved = -1;
	dbinfo->tdbi_l_reserved = (PTR)-1;
	dbinfo->tdbi_owner = (PTR)-1;
	dbinfo->tdbi_ascii_id = ADTDBI_ASCII_ID;
	dbinfo->tdbi_numreqs = 1;

	/*
	**  Now define request.
	*/
	dbinfo->tdbi_reqs[0].dbi_func = IIUGnfNowFunc;
	dbinfo->tdbi_reqs[0].dbi_num_inputs = 0;
	dbinfo->tdbi_reqs[0].dbi_lenspec.adi_lncompute = ADI_FIXED;
	STcopy("_BINTIM", dbinfo->tdbi_reqs[0].dbi_reqname);
	dbinfo->tdbi_reqs[0].dbi_reqcode = 1;
	dbinfo->tdbi_reqs[0].dbi_lenspec.adi_fixedsize = 4;
	dbinfo->tdbi_reqs[0].dbi_dtr = DB_INT_TYPE;

	/*
	** set timezone in ADF cb  - Any errors must be reported
        ** after adg_init() called.
	*/

	if ( (tmtz_status = TMtz_init(&cb.adf_tzcb)) == OK)
        {
	   tmtz_status = TMtz_year_cutoff(&cb.adf_year_cutoff);
        }

	/* Always use INGRESDATE by default, and check 
	** 'ii.<node>.config.date_alias' (kibro01) b118702
	*/
	cb.adf_date_type_alias = AD_DATE_TYPE_ALIAS_INGRES;
	STprintf(date_type_alias,ERx("ii.%s.config.date_alias"),PMhost());
	date_status = PMget(date_type_alias, &cp);
	if (date_status == OK && cp != NULL && STlength(cp))
	{
	    if (STbcompare(cp, 0, ERx("ansidate"), 0, 1) == 0)
		cb.adf_date_type_alias = AD_DATE_TYPE_ALIAS_ANSI;
	    else if (STbcompare(cp, 0, ERx("ingresdate"), 0, 1) == 0)
		cb.adf_date_type_alias = AD_DATE_TYPE_ALIAS_INGRES;
	    else
		cb.adf_date_type_alias = AD_DATE_TYPE_ALIAS_NONE;
	}

	/* set timezone table to NULL in ADF cb, adg_init() will fill it */
	/* cb.adf_tz_table = NULL; - not needed, done in declaration above */

	/* Start up ADF */
    	rval = adg_startup(srv_cb_ptr, srv_size, dbinfo, 0);
	if (DB_FAILURE_MACRO(rval))
	{
	    /*
	    ** Before bailing out, try to be helpful. Since the environment
	    ** is likely not set up correctly, write hard coded messages
	    ** since error message fetch will likely fail in this situation.
	    */
	    char	*tempchar;
	    i4		dummy;
	    LOCATION	temploc;
	    NMgtAt("II_SYSTEM", &tempchar);
	    if (tempchar && *tempchar)
	    {
		LOfroms(PATH, tempchar, &temploc);
		if (LOexist(&temploc))
		{
		    tempchar = ERx("FEadfcb: II_SYSTEM DOES NOT EXIST\n");
		    SIwrite(STlength(tempchar), tempchar, &dummy, stderr);
		}
		else
		{
		    NMloc(ADMIN, FILENAME, ERx("config.dat"), &temploc);
		    if (LOexist(&temploc))
		    {
			tempchar = ERx("FEadfcb: II_SYSTEM IS NOT SET CORRECTLY\n");
			SIwrite(STlength(tempchar), tempchar, &dummy, stderr);
		    }
		}
	    }
	    else
	    {
		tempchar = ERx("FEadfcb: II_SYSTEM IS NOT SET\n");
		SIwrite(STlength(tempchar), tempchar, &dummy, stderr);
	    }
    	    EXsignal(EXFEBUG, 1, ERx("FEadfcb(start)"));
	}

	/* put the pointer to ADF's server control block in the ADF_CB */
	cb.adf_srv_cb = srv_cb_ptr;

	/* set up the error message buffer */
    	cb.adf_errcb.ad_ebuflen = DB_ERR_SIZE;
    	cb.adf_errcb.ad_errmsgp = ebuffer;

	/* initialize the ADF_CB */
    	rval = adg_init(&cb);
	if (DB_FAILURE_MACRO(rval))
	{
    	    EXsignal(EXFEBUG, 1, ERx("FEadfcb(init)"));
	}

	/* find out which natural language we should speak */
	cb.adf_slang = iiuglcd_langcode();

	/* Always QUEL; for SQL explictly change this with 'IIAFdsDmlSet()'. */
	cb.adf_qlang = DB_QUEL;

	/* lets get the multinational info */

	/* 
	** Defaults for all of these are initially set statically, above.
	*/
	NMgtAt(ERx("II_DATE_FORMAT"), &cp);
    	if ( cp != NULL && *cp != EOS )
    	{
	    FEapply_date_format(&cb,cp);
    	}

	NMgtAt(ERx("II_MONEY_FORMAT"), &cp);
    	if ( cp != NULL && *cp != EOS )
    	{
	    FEapply_money_format(&cb,cp);
    	}

	NMgtAt(ERx("II_MONEY_PREC"), &cp);
    	if ( cp != NULL && *cp != EOS )
    	{
	    FEapply_money_prec(&cb,cp);
    	}

	NMgtAt(ERx("II_DECIMAL"), &cp);
    	if ( cp != NULL && *cp != EOS )
    	{
	    FEapply_decimal(&cb,cp);
    	}

	NMgtAt(ERx("II_UNICODE_SUBS"), &cp);
	if ( !cp )
	{
	    cb.adf_unisub_status = AD_UNISUB_OFF;
	}
	else
	{
	    /* As with SET unicode_substitution take the first char */
	    cb.adf_unisub_status = AD_UNISUB_ON;
	    *cb.adf_unisub_char = cp[0];
	}

	NMgtAt(ERx("II_NULL_STRING"), &cp);
	if ( cp != NULL && *cp != EOS )
	{
	    FEapply_null(&cb,cp);
	}

	/* If there was a Timezone error other than the expected ingbuild
	** error TM_PMFILE_OPNERR, then lets report it now. */

        if (tmtz_status && (tmtz_status != TM_PMFILE_OPNERR))
        {
	    LOCATION    loc_root;
	    STATUS status = OK;
	    status = NMloc(FILES, PATH, ERx("zoneinfo"), &loc_root);
#if defined(conf_BUILD_ARCH_32_64) && defined(BUILD_ARCH64)
            status = LOfaddpath(&loc_root, ERx("lp64"), &loc_root);
#endif
#if defined(conf_BUILD_ARCH_64_32) && defined(BUILD_ARCH32)
    {
        /*
        ** Reverse hybrid support must be available in ALL
        ** 32bit binaries
        */
        char    *rhbsup;
        NMgtAt("II_LP32_ENABLED", &rhbsup);
        if ( (rhbsup && *rhbsup) &&
       ( !(STbcompare(rhbsup, 0, "ON", 0, TRUE)) ||
         !(STbcompare(rhbsup, 0, "TRUE", 0, TRUE))))
            status = LOfaddpath(&loc_root, "lp32", &loc_root);
    }
#endif /* ! LP64 */

            if ( status == OK )
            {
		status = LOexist(&loc_root);
            }
            if ( status == OK )
	    {
                   IIUGerr(tmtz_status, 0, 0);

                   /* As this may disappear from the screen quickly,
                   ** let's pause to allow the users to reflect on the
                   ** fact that the timezone info is (probably) wrong.
                   */
                   if (!IIugefa_err_function) PCsleep(5000);
	    }
        }

	/* Initialize unicode collation for UTF8 installations */
	if (CMischarset_utf8())
	{
          if (status = aduucolinit(col, MEreqmem, 
			&ucode_ctbl, &ucode_cvtbl, &sys_err))
          {
    	    EXsignal(EXFEBUG, 1, ERx("FEadfcb(alloc)"));
          }

          cb.adf_ucollation = (PTR) ucode_ctbl;

	  /* Set unicode normalization to NFC just in case 
	  ** Front end will need it.
	  */
          if ((status = adg_setnfc(&cb)) != E_DB_OK)
    	    EXsignal(EXFEBUG, 1, ERx("FEadfcb(alloc)"));
	}
	/* lets not do this again! */
    }

    return &cb;
}
Example #8
0
edit()
{
	register char		*p;
	LOCATION		t_loc,
				loc;
	FILE			*fp;
	char			errbuf[ER_MAX_LEN + 1];
	char			input[MAX_LOC + 1];
	char			*editfile;
	char			*ingedit;
	i4			rflag;
	STATUS			status;
	i4			c;
#ifdef CMS
	i4			Notempty = 1;
#endif /* CMS */

	GLOBALREF	char	*IIMOildInitLnDraw;

	FUNC_EXTERN 	char		*getfilenm();
	FUNC_EXTERN 	char		*macro();


	if (!Newline)
	{
		q_putc(Qryiop, '\n');
		Newline = TRUE;
	}

	Autoclear	= 0;
	editfile	= getfilenm();
	rflag		= 0;

	if (*editfile == '\0')
	{
		rflag	 = 1;
		input[0] = EOS;


		if ((status = NMloc( TEMP, PATH, (char *)NULL, &t_loc)) ||
		    (status = LOuniq( ERx( "query" ), ERx( "edt" ), &t_loc)))
		{
			STcopy( ERx( "queryXXX" ), input );
		}
		else
		{
			LOcopy( &t_loc, input, &loc );
		}

		status = SIfopen( &loc, ERx( "w" ), (i4)SI_TXT,
				  (i4)SI_MAX_TXT_REC, &fp );
	}
	else
	{
		/* use the path and file name the user gave you */

		STcopy(editfile, input);

		if (!(status = LOfroms(PATH & FILENAME, input, &loc)))
			status = SIfopen( &loc, ERx("w"), (i4)SI_TXT,
					  (i4)SI_MAX_TXT_REC, &fp );
	}

	if (status)
	{
		if (status == FAIL)
			errbuf[0] = '\0';
		else
			ERreport(status, errbuf);

		putprintf(ERget(F_MO000C_Cant_create_qry_file),
				input, errbuf);

		cgprompt();
		return(0);
	}

	if (q_ropen(Qryiop, 'r') == (struct qbuf *)NULL)
		/* edit: q_ropen 1 */
		ipanic(E_MO0044_1500400);

	while ((c = (i4)q_getc(Qryiop)) > 0)
		SIputc((char)c, fp);

	SIclose(fp);

	if (Nodayfile >= 0)
	{
		putprintf(ERget(F_MO000D_editor_prompt));
		SIflush(stdout);
	}

	/*
	**	macro returns NULL if undefined, UTedit uses
	**		default editor if passed NULL.
	*/

	/* Bug 4875	-	Use editor defined by environment variable
		ING_EDIT. If that is not set then use the macro(editor). 
	*/

	NMgtAt((ERx("ING_EDIT")), &ingedit);
	if ( ingedit != NULL && *ingedit != EOS )
		p = ingedit;
	else

		p = macro(ERx("{editor}"));

	if (status = UTedit(p, &loc))
	{
		ERreport(status, errbuf);
		putprintf(ERget(F_MO000E_Can_t_start_up_editor), errbuf);

		cgprompt();
		return(0);
	}

	if (!rflag)
	{
		if (q_ropen(Qryiop, 'a') == (struct qbuf *)NULL)
			/* edit: q_ropen 2 */
			ipanic(E_MO0045_1500401);
	}
	else
	{
		if (q_ropen(Qryiop, 'w') == (struct qbuf *)NULL)
			/* edit: q_ropen 3 */
			ipanic(E_MO0046_1500402);

		if (status = SIfopen( &loc, ERx("r"), (i4)SI_TXT,
				      (i4)SI_MAX_TXT_REC, &fp ))
#ifdef CMS
		{
			Notempty = 0;
		}
#else
		{
			ERreport(status, errbuf);
			/* can't reopen editfile %s: %s\n */
			ipanic(E_MO0047_1500403,
				editfile, errbuf);
		}
#endif /* CMS */

#ifdef CMS
		if (Notempty)
		{
#endif /* CMS */
		Notnull = 0;

		while ((c = SIgetc(fp)) != EOF)
		{
			if (status)
			{
				ERreport(status, errbuf);
				/* Error reading edit file: %s\n */
				ipanic(E_MO0048_1500404, errbuf);
			}

			Notnull = 1;

			q_putc(Qryiop, (char)c);
		}

		SIclose(fp);


		if (status = LOpurge(&loc, 0))
		{
			ERreport(status, errbuf);
			putprintf(ERget(F_MO000F_Cant_delete_file), editfile, errbuf);
		}
#ifdef CMS
		} /* endif Notempty */
#endif /* CMS */
	}

#ifndef FT3270
	/* Re-Initialize IT line drawing */
	{
	    if (Outisterm && IIMOildInitLnDraw != NULL)
		SIprintf(ERx("%s"), IIMOildInitLnDraw);
	}
#endif

	cgprompt();

	return(0);
}
Example #9
0
/*
** Name: cpres_mbx_assign	- get channel to target process, assign if need
**
** Description:
**	This subroutine looks up the channel to the target process. If we have
**	not yet assigned a channel to the target process, then we assign one
**	and remember it. The resulting channel is returned.
**
** Inputs:
**	pid			- the target process's pid
**
** Outputs:
**	CPchan			- Pointer to CP_CHANNEL of process.
**
** Returns:
**	OK, !OK
**
** History:
**	Summer, 1992 (bryanp)
**	    Working on the new portable logging and locking system.
**	14-dec-1992 (bryanp)
**	    ERsend() calls should be ERlog() calls.
**	23-may-1994 (bryanp) B60736
**	    Added clean_channels() routine and called it periodically to
**		ensure that a process doesn't accumulate channels to dead
**		processes indefinitely.
**	02-May-2007 (jonj)
**	    Use of CSp/v_semaphore is prohibited from within an AST as
**	    it corrupts cs_inkernel and the ready queues. Use CS_ASET/ACLR
**	    instead.
**	08-Nov-2007 (jonj)
**	    Changed function to return pointer to CP_CHANNEL instead
**	    of channel number, initialize IsDead to FALSE.
**	04-Apr-2008 (jonj)
**	    Remove disabling of ASTs here, caller will have already done
**	    that.
**	    Check if PID has been deadified by write AST; if so,
**	    cancel any pending I/O, deassign channel, mark CPchan
**	    as unusuable (dead).
*/
static STATUS
cpres_mbx_assign(PID pid, CP_CHANNEL **CPchan)
{
    i4	    	i;
    struct	dsc$descriptor_s    name_desc;
    i4		vms_status;
    char	mbx_name[100];
    char	*inst_id;
    char	msg_buf[250];
    STATUS	status;
    STATUS	cl_status;
    PID		my_pid;
    CL_ERR_DESC	local_sys_err;
    CP_CHANNEL	*NewCPchan;

    /* Loop until we get the sem */
    while ( !CS_TAS(&cpres_channels_sem) );

    for (i = 0; i < cpres_num_channels_assigned; i++)
    {
	if (cpres_channels[i].pid == pid)
	{
	    /*
	    ** If write completion AST noticed that
	    ** the reading process has died or gone away,
	    ** mark its PID as dead, cancel any leftover
	    ** I/O and deassign the channel.
	    */
	    if ( cpres_channels[i].state == CPchanIsDying )
	    {
		sys$cancel(cpres_channels[i].chan);
		sys$dassgn(cpres_channels[i].chan);

		cpres_channels[i].state = CPchanIsDead;

		STprintf(msg_buf, "%x PID %x on channel %d is dead, deassigned",
				Cs_srv_block.cs_pid,
				cpres_channels[i].pid, 
				cpres_channels[i].chan);
		ERlog(msg_buf, STlength(msg_buf), &local_sys_err);
	    }

	    /* Return channel, dead or alive */
	    *CPchan = &cpres_channels[i];
	    CS_ACLR(&cpres_channels_sem);
	    return (OK);
	}
    }

    if ( status = clean_channels() )
    {
	CS_ACLR(&cpres_channels_sem);
	return (status);
    }

    if ( cpres_num_channels_assigned <
		    (sizeof(cpres_channels)/sizeof(CP_CHANNEL)) )
    {
	/*
	** New process, and room remains in the channel array, so assign a
	** channel.
	*/
	NewCPchan = &cpres_channels[cpres_num_channels_assigned];

	NMgtAt("II_INSTALLATION", &inst_id);
	if (inst_id && *inst_id)
	    STprintf(mbx_name, "II_CPRES_%s_%x", inst_id, (i4)pid);
	else
	    STprintf(mbx_name, "II_CPRES_%x", (i4)pid);

	name_desc.dsc$a_pointer = mbx_name;
	name_desc.dsc$w_length = STlength(mbx_name);
	name_desc.dsc$b_dtype = DSC$K_DTYPE_T;
	name_desc.dsc$b_class = DSC$K_CLASS_S;

	vms_status = sys$assign(&name_desc,	/* devname */
			    &NewCPchan->chan,	/* channel */
			    0, 			/* access_mode */
			    0,			/* mbxnam */
			    AGN$M_WRITEONLY);	/* flags */

	if ( vms_status == SS$_NORMAL )
	{
	    NewCPchan->pid = pid;
	    NewCPchan->state = CPchanIsAlive;
	    *CPchan = NewCPchan;
	    cpres_num_channels_assigned++;
	    CS_ACLR(&cpres_channels_sem);
	    return (OK);
	}
	else
	{
	    STprintf(msg_buf,
		    "%x cpres_mbx_assign: Error (%x) assigning channel to %s",
		    Cs_srv_block.cs_pid, vms_status, mbx_name);
	    ERlog(msg_buf, STlength(msg_buf), &local_sys_err);
	}
    }
    else
    {
	/*
	** No room left in channels array. One possibility is to go through
	** the array looking for assigned channels to mailboxes of dead
	** processes and clean those up.
	*/
	STcopy("PANIC! No room left in channels array!", msg_buf);
	ERlog(msg_buf, STlength(msg_buf), &local_sys_err);
    }

    CS_ACLR(&cpres_channels_sem);
    return (FAIL);
}
Example #10
0
main(int argc, char **argv)
{
	char 			*value = NULL; 
	char			*host, *server_type, *command_line; 
	char 			*server_location, *env, *arguments;
	u_i4 			command_line_length;
	char 			config_string[256];
	char 			iidbms[256];
	STARTUPINFO 		si;
	PROCESS_INFORMATION 	ProcessInfo;
	BOOL 			Status;
	SECURITY_ATTRIBUTES     sa;
	HANDLE			hRead, hWrite;
	HANDLE			hStdout;
	char			buffer[512];
	DWORD			bufferl = sizeof(buffer);
	DWORD			pipe_size = 0;	/* Use default buffer size */
	DWORD			datal = 0;
	bool			havequote, failed = FALSE;


	MEadvise( ME_INGRES_ALLOC );

	switch (argc)
	{

	case 1:
		server_type = ERx("dbms");
		server_location = ERx("*");
		break;

	case 2:
		server_type = argv[1];
		server_location = ERx("*");
		break;

	default:
		server_type = argv[1];
    		if (STcompare(server_type, "recovery") == 0)
			server_location = ERx("*");
		else
			server_location = argv[2];
		break;

	}
	
	get_sys_dependencies();

	/*
	**	Get the host name, formally used iipmhost.
	*/
	host = PMhost();

	/*
	**	Build the string we will search for in the config.dat file.
	*/
	STprintf( config_string,
		  ERx("%s.%s.%s.%s.image_name"),
		  SystemCfgPrefix, host, server_type, server_location );

	/*
	**	Get set up for the PMget call.
	*/
	PMinit();
	if( PMload( NULL, (PM_ERR_FUNC *)NULL ) != OK )
		PCexit( FAIL );

	/*
	**	Go search config.dat for a match on the string we just built.
	*/
	PMget( config_string, &value );

	if ( value == NULL )
	{
		NMgtAt( SystemLocationVariable, &env );
		if (STcompare(server_type, "recovery") == 0)
		{
		    STprintf(iidbms, ERx("%s\\%s\\bin\\%sdbms"),
			     env, SystemLocationSubdirectory, SystemCfgPrefix);
		}
		else
		{
		    STprintf(iidbms, ERx("%s\\%s\\bin\\%s%s"),
			     env, SystemLocationSubdirectory, SystemCfgPrefix,
			     server_type);
		}
	}
	else if ( *value == '/' || 
		  *value == '\\' ||
		  (*(value+1) == ':' && *(value+2) == '\\') )
	{
		/* Must be a qualified path name */
		STcopy( value, iidbms );
	}
	else 
	{
		NMgtAt( SystemLocationVariable, &env );
		STprintf( iidbms, ERx("%s\\%s\\bin\\%s"),
			  env, SystemLocationSubdirectory, value );
	}
	
	/*
 	** 	Initialize the startinfo structure.	
	*/
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);

	/*
	**	Get the original command line.
	*/
	arguments = GetCommandLine();
        havequote = FALSE;
        while (*arguments != '\0' && *arguments != '\n')
        {
            if ( *arguments == '"' )
                havequote = (havequote) ? FALSE : TRUE;
            if ( CMwhite(arguments) && havequote == FALSE )
                break;
            arguments++;
        }
	/*
	** 	Put together a command line to create a process with.
	**      - 4 blank separators, quotes, null termination 
	*/
	command_line_length = STlength(arguments) + STlength(iidbms) + 
				STlength(iirun) + 6 + 1; 
	if((command_line = (char *)
		MEreqmem(0, command_line_length, TRUE, NULL)) == NULL)
	{
		error(ERx("Request for memory failed"),NULL);
	}

	STprintf( command_line, "%s \"%s\" %s", iirun, iidbms, arguments );

	/*
	**	Save standard out's handle, to be restored later.
	*/
	hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

 	/*
	**      Initialize the security attributes structure that will
	**      be used to make the pipe handles inheritable.
	*/
	sa.nLength = sizeof(sa);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;       /* Make object inheritable */

	/*
	**	Define a anonymous pipe to catch the server's startup message.
	*/
	if((Status = CreatePipe(&hRead,&hWrite,&sa,pipe_size)) != TRUE)
	{
		error(ERx("CreatePipe failed"),ERx("error code = "));
	}

	SetStdHandle(STD_OUTPUT_HANDLE,hWrite);

 	/*
	**      Initialize the security attributes structure that will
	**      be used to make the pipe handles inheritable.
	*/
	sa.nLength = sizeof(sa);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;       /* Make object inheritable */

	/*
	**	Initialize the startup information structure.
	*/
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	/* 
	**	Start it up.
	*/
	/*
	**	Start iirun which will start the server.
	*/
	if ((Status = CreateProcess(NULL,command_line,&sa,NULL,TRUE,
		HIGH_PRIORITY_CLASS, NULL,
	     NULL,&si,&ProcessInfo)) != TRUE)
	{
		DWORD dwError = GetLastError();
		switch(dwError)
		{
		     case ERROR_ACCESS_DENIED:
			error(ERROR_REQ_PRIVILEGE, ERx(""));
			break;
		     case ERROR_ELEVATION_REQUIRED:
			error(ERROR_DENIED_PRIVILEGE, ERROR_REQ_ELEVATION);
			break;
		     default:				
			error(ERx("CreateProcess failed"),ERx("error code = "));
			break;
		}
	}

	SetStdHandle(STD_OUTPUT_HANDLE,hStdout);

	for (;;)
	{
	    char	*tmpptr;

	    if((Status = ReadFile(hRead,&buffer,bufferl,&datal,NULL)) != TRUE)
	    {
		error(ERx("ReadFile failed"),ERx("error code = "));
	    }

	    buffer[datal] = '\0';	 		
	    if ((tmpptr = STstrindex(buffer, "PASS\n", 0, FALSE)))
	    {
		*tmpptr = '\0';
		if (STlength(buffer))
		    SIfprintf(stdout, "%s", buffer);

		break;
	    }

	    SIfprintf(stdout, "%s", buffer);

	    if ((tmpptr = STstrindex(buffer, bad_msg, 0, FALSE)))
	    {
		*tmpptr = '\0';
		if (STlength(buffer))
		    SIfprintf(stdout, "%s", buffer);

		failed = TRUE;
		break;
	    }
	}

	/*
	**	Close handles since we don't need them anymore.
	*/
	CloseHandle(ProcessInfo.hThread);
	CloseHandle(ProcessInfo.hProcess);
	CloseHandle(hRead);
	CloseHandle(hWrite);

	if (failed &&
	    STscompare(server_type, STlength(server_type), "gcb", 3) != 0 &&
	    STscompare(server_type, STlength(server_type), "gcc", 3) != 0 &&
	    STscompare(server_type, STlength(server_type), "jdbc", 4) != 0)
	{
		SIfprintf( stderr,"\n%s: server would not start.\n",
			   iirundbms );

		SIfprintf(stderr,
		" %s must be set in your environment.\n", 
		    SystemLocationVariable );

		SIfprintf(stderr,
		" Has the csinstall program been run?\n");

		SIfprintf(stderr,
		" %s_DATABASE, %s_CHECKPOINT, %s_JOURNAL and %s_DUMP\n",
		    SystemVarPrefix,
		    SystemVarPrefix,
		    SystemVarPrefix,
		    SystemVarPrefix );

		SIfprintf(stderr,
		" must also be set. See %s_CONFIG\\symbol.tbl.\n",
		    SystemVarPrefix );

		SIfprintf(stderr,
		" Check the file '%%%s%%\\%s\\files\\errlog.log'\n",
		    SystemLocationVariable, SystemLocationSubdirectory );

		SIfprintf(stderr,
		" for more details concerning internal errors.\n");

		SIfprintf(stderr,
		" See your Installation and Operation Guide for more\n");

		SIfprintf(stderr,
		" information concerning server startup.\n");

		PCexit(FAIL);
	}
	else
	{
		PCexit(OK);
	}
}
Example #11
0
DB_STATUS
dmc_add_db(
DMC_CB    *dmc_cb)
{
    DMC_CB		*dmc = dmc_cb;
    DM_SVCB		*svcb = dmf_svcb;
    DMC_LOC_ENTRY	*location;
    i4		loc_count;
    i4		flags;
    i4		mode;
    i4		dm2mode;
    i4		error,local_error;
    DMM_LOC_LIST	*loc_ptr[4];
    DB_STATUS		status;
    DMP_DCB		*dcb;

    CLRDBERR(&dmc->error);

    for (status = E_DB_ERROR;;)
    {
	/*	Verify control block parameters. */

	if (dmc->dmc_op_type != DMC_DATABASE_OP)
	{
	    SETDBERR(&dmc->error, 0, E_DM000C_BAD_CB_TYPE);
	    break;
	}

	if (dmc->dmc_id != svcb->svcb_id)
	{
	    SETDBERR(&dmc->error, 0, E_DM002D_BAD_SERVER_ID);
	    break;
	}

	flags = 0;
	if (dmc->dmc_flags_mask &
	    ~(DMC_NOJOURNAL | DMC_JOURNAL | DMC_FSTCOMMIT | DMC_SOLECACHE |
              DMC_CNF_LOCKED | DMC_CVCFG | DMC_ADMIN_DB | DMC_DMCM))
	{
	    SETDBERR(&dmc->error, 0, E_DM001A_BAD_FLAG);
	    break;
	}
	if (dmc->dmc_flags_mask & DMC_NOJOURNAL)
	    flags |= DM2D_NOJOURNAL;
	if (dmc->dmc_flags_mask & DMC_JOURNAL)
	    flags |= DM2D_JOURNAL;
	if (dmc->dmc_flags_mask & DMC_FSTCOMMIT)
	    flags |= DM2D_FASTCOMMIT;
	if (dmc->dmc_flags_mask & DMC_SOLECACHE)
	    flags |= DM2D_BMSINGLE;
	if (dmc->dmc_flags_mask & DMC_CVCFG)
	    flags |= DM2D_CVCFG;
        
        /* b97083 - Is the CNF file already locked by caller? */
        if (dmc->dmc_flags_mask & DMC_CNF_LOCKED)
            flags |= DM2D_CNF_LOCKED;

	if (dmc->dmc_s_type & DMC_S_SINGLE)
	    flags |= DM2D_SINGLE;
	if (dmc->dmc_s_type & DMC_S_MULTIPLE)
	    flags |= DM2D_MULTIPLE;

        /*
        ** (ICL phil.p)
        */
        if (dmc->dmc_flags_mask & DMC_DMCM)
            flags |= DM2D_DMCM;

        if (dmc->dmc_flags_mask2 & DMC2_READONLYDB)
            flags |= DM2D_READONLYDB;

	/* No MO objects if so requested */
	if ( dmc->dmc_flags_mask2 & DMC2_NODBMO ||
	     mode == DMC_A_CREATE || mode == DMC_A_DESTROY )
	{
	    flags |= DM2D_NODBMO;
	}

	/*
	** It is an error to specify Fast Commit without specifying to
	** use a single buffer manager.
        ** (ICL phil.p) UNLESS running DMCM, which effectively means
        ** running FastCommit in a Multi-Cache environment.
	*/

        if (!(flags & DM2D_DMCM))
        {
            if ((flags & (DM2D_FASTCOMMIT | DM2D_BMSINGLE)) == DM2D_FASTCOMMIT)
	    {
		SETDBERR(&dmc->error, 0, E_DM0115_FCMULTIPLE);
                break;
	    }
        }

	mode = dmc->dmc_db_access_mode;
	if (mode != DMC_A_READ &&
	    mode != DMC_A_WRITE &&
	    mode != DMC_A_CREATE &&
	    mode != DMC_A_DESTROY)
	{
	    SETDBERR(&dmc->error, 0, E_DM000F_BAD_DB_ACCESS_MODE);
	    break;
	}
	dm2mode = (mode == DMC_A_READ) ? DM2D_A_READ : DM2D_A_WRITE;

	/*  Check that at least one location was passed in. */

	location = (DMC_LOC_ENTRY *)dmc->dmc_db_location.data_address;
	loc_count = dmc->dmc_db_location.data_in_size / sizeof(DMC_LOC_ENTRY);
	if (loc_count == 0)
	{
	    SETDBERR(&dmc->error, 0, E_DM002A_BAD_PARAMETER);
	    break;
	}
	    
	/*  Check if database should be created. */

	if (mode == DMC_A_CREATE)
	{
	    SCF_CB              scf_cb;
	    SCF_SCI             sci_list[2]; 
	    DB_NAME		collation;
	    DB_NAME		ucollation;
	    char		*p;
	    char		ucolname[] = "udefault";
	    i4		dbservice;

	    scf_cb.scf_length = sizeof(SCF_CB);
	    scf_cb.scf_type = SCF_CB_TYPE;
	    scf_cb.scf_facility = DB_DMF_ID;
	    scf_cb.scf_session = (SCF_SESSION)dmc->dmc_session_id;
	    scf_cb.scf_ptr_union.scf_sci = (SCI_LIST *)sci_list;
	    sci_list[0].sci_length = sizeof(dbservice);
	    sci_list[0].sci_code = SCI_DBSERVICE;
	    sci_list[0].sci_aresult = (char *)&dbservice;
	    sci_list[0].sci_rlength = 0;
	    scf_cb.scf_len_union.scf_ilength = 1;

	    status = scf_call(SCU_INFORMATION, &scf_cb);
	    if (status != E_DB_OK)
	    {
		uleFormat(&scf_cb.scf_error, 0, (CL_ERR_DESC *)NULL, 
		    ULE_LOG, NULL, (char *)0, (i4)0, (i4 *)0, 
		    &error, 0);
		SETDBERR(&dmc->error, 0, E_DM002F_BAD_SESSION_ID);
		break;
	    }

	    /*	Collation for iidbdb can only be the default. */

	    MEfill(sizeof(collation.db_name), ' ', collation.db_name);
	    NMgtAt("II_COLLATION", &p);
	    if (p && *p)
		MEmove(STlength(p), p, ' ', sizeof(collation.db_name), 
				collation.db_name);
	    MEmove(STlength(ucolname), ucolname, ' ', 
		   sizeof(ucollation.db_name), ucollation.db_name);

	    loc_ptr[0] = (DMM_LOC_LIST *) &loc_list[0];
	    loc_ptr[1] = (DMM_LOC_LIST *) &loc_list[1];
	    loc_ptr[2] = (DMM_LOC_LIST *) &loc_list[2];
	    loc_ptr[3] = (DMM_LOC_LIST *) &loc_list[3];

	    /* Even though the iidbdb is not "operative" at this stage, we
	    ** will mark it as operative in the config file now (it will not
	    ** be marked operative in the iidatabase catalog until after it
	    ** is fully created).  Although we would like to mark the iidbdb
	    ** "inoperative" in the config file now and update it to operative
	    ** status when creation is successfully completed (as is done for
	    ** all other DBs) the internal procedure "iiqef_alter_db" which
	    ** updates this bit will not work on the iidbdb; see comments in
	    ** createdb regarding this problem.
	    */ 
	    status = dmm_add_create(0, &dmc->dmc_db_name, &dmc->dmc_db_owner,
		 1, dbservice, DU_OPERATIVE, 
		(DB_LOC_NAME *) &dbdb_location, 11, "II_DATABASE", 4, 
		loc_ptr, collation.db_name, ucollation.db_name, &dmc->error);

	    if (status != E_DB_OK)
	    {
		if (dmc->error.err_code > E_DM_INTERNAL)
		{
		    uleFormat( &dmc->error, 0, NULL, ULE_LOG , NULL,
			    (char * )0, 0L, (i4 *)0, &local_error, 0);
		    SETDBERR(&dmc->error, 0, E_DM0084_ERROR_ADDING_DB);
		}
		break;
	    }
	}
	else if (mode == DMC_A_DESTROY)
	{
	    return (E_DB_OK);
	}

	/*  Call the physical layer to construct a DCB for this database. */

	status = dm2d_add_db(flags, &dm2mode, &dmc->dmc_db_name, 
		&dmc->dmc_db_owner, loc_count, (DM2D_LOC_ENTRY *)location, &dcb, 
		(i4 *)dmc->dmc_lock_list, &dmc->error);
	if (status != E_DB_OK)
	{
	    if (dmc->error.err_code > E_DM_INTERNAL)
	    {
		uleFormat( &dmc->error, 0, NULL, ULE_LOG , NULL,
		    (char * )0, 0L, (i4 *)0, &local_error, 0);
		SETDBERR(&dmc->error, 0, E_DM0084_ERROR_ADDING_DB);
	    }
	    break;
	}

	/*  Use the access mode passed back */
	dmc->dmc_db_access_mode = 
		(dm2mode == DM2D_A_READ) ? DMC_A_READ : DMC_A_WRITE;
	dmc->dmc_db_id = (char *)dcb;
	dmc->dmc_dbservice = dcb->dcb_dbservice;
	dmc->dmc_dbcmptlvl = dcb->dcb_dbcmptlvl;
	dmc->dmc_1dbcmptminor = dcb->dcb_1dbcmptminor;
	return (E_DB_OK);
    }

    return (status);
}
Example #12
0
/*
** Name: GClanman_init
** Description:
**	LANMAN inititialization function.  This routine is called from
**	GCpinit() -- the routine GCC calls to initialize protocol drivers.
**
**	This function does initialization specific to the protocol:
**	    Creates Events and Mutex's for the protocol
**	    Finds and saves a pointer to it's input event Q.
**	    Fires up the thread which will do asynch I/O
** History:
**	11-Nov-93 (edg)
**	    created.
**      15-jul-95 (emmag)
**          Use a NULL Discretionary Access Control List (DACL) for
**          security, to give implicit access to everyone.
**	23-Feb-1998 (thaal01)
**	    Make space for port_id, stops gcc crashing on startup, sometimes.
**	13-may-2004 (somsa01)
**	    Updated config.dat string used to retrieve port information such
**	    that we do not rely specifically on the GCC port.
**	06-Aug-2009 (Bruce Lunsford)  Sir 122426
**	    Change arglist pointer in _beginthreadex for async_thread from
**	    uninitialized "dummy" to NULL to eliminate compiler warning
**	    and possible startup problem.
*/
STATUS
GClanman_init(GCC_PCE * pptr)
{

	char            *ptr, *host, *server_id, *port_id;
	char		config_string[256];
	char            buffer[MAX_COMPUTERNAME_LENGTH + 1];
	int 		real_name_size = MAX_COMPUTERNAME_LENGTH + 1;
	i4		i;
	int		tid;
	HANDLE		hThread;
	int		status;
	SECURITY_ATTRIBUTES sa;
	char		port_id_buf[8];

	port_id = port_id_buf;

	iimksec (&sa);

	/*
	** Look for trace variable.
	*/
	NMgtAt( "II_LANMAN_TRACE", &ptr );
	if ( !(ptr && *ptr) && PMget("!.lanman_trace_level", &ptr) != OK )
	{
	    GCLANMAN_trace = 0;
	}
	else
	{
	    GCLANMAN_trace = atoi( ptr );
	}

	/*
	** Create MUTEX and EVENT for the input queue of this protocol
	** driver.
	*/
	if ( ( hMutexThreadInQ = CreateMutex(&sa, FALSE, NULL) ) == NULL )
	{
	    return FAIL;
	}

	GCTRACE(3)( "GClanman_init: MutexInQ Handle = %d\n", hMutexThreadInQ );

	if ( ( hEventThreadInQ = CreateEvent(&sa, FALSE, FALSE, NULL)) == NULL )
	{
	    CloseHandle( hMutexThreadInQ );
	    return FAIL;
	}

	GCTRACE(3)( "GClanman_init: EventInQ Handle = %d\n", hEventThreadInQ );
	

	GCTRACE(4)( "Start GClanman_init\n" );

        /*
        ** Get set up for the PMget call.
        */
        PMinit();
        if( PMload( NULL, (PM_ERR_FUNC *)NULL ) != OK )
                PCexit( FAIL );

	/*
	** Construct the network port identifier. 
	*/

        host = PMhost();
	server_id = PMgetDefault(3);
 	if (!server_id)
 		server_id = "*" ;
        STprintf( config_string, ERx("!.lanman.port"),
                  SystemCfgPrefix, host, server_id);

	/*
	** Search config.dat for a match on the string we just built.
	** If we don't find it, then use the value for II_INSTALLATION 
	** failing that, default to II.
	*/
        PMget( config_string, &port_id );
	if (port_id == NULL )
	{
		NMgtAt("II_INSTALLATION", &ptr);
		if (ptr != NULL && *ptr != '\0')
		{
			STcopy(ptr, port_id);
		}
		else 
		{ 
			STcopy(SystemVarPrefix, port_id);
		}
	}

	NMgtAt( "II_NETBIOS_NODE", &ptr );
	if ( !ptr || !*ptr  )
	{
	    /*
	    ** Get Computer Name into buffer.
	    */
	    *buffer = (char)NULL;
	    GetComputerName( buffer, &real_name_size );
	    if ( !*buffer )
	        STcopy( "NONAME", buffer );
	    ptr = buffer;
	}
	/*
	** MyName holds ID for outgoing connections.
	*/
	STpolycat( 2, ptr, "_", MyName );
	/*
	** Create listen port ID.
	*/
	STpolycat( 3, ptr, "_", port_id, GCc_listen_port );
	CVupper( MyName );
	CVupper( GCc_listen_port );
	STcopy( GCc_listen_port, pptr->pce_port );

	GCTRACE(2)("GClanman_init: port = %s\n", pptr->pce_port );

	/*
	** Go thru the the protocol threads event list and find the index
	** of the lanman thread.  Set the Global Tptr for easy reference
	** to the event q's for this protocols thread.
	*/
	for ( i = 0; i < IIGCc_proto_threads.no_threads; i++ )
	{
	     THREAD_EVENTS *p = &IIGCc_proto_threads.thread[i];

	     if ( !STcompare( LANMAN_ID, p->thread_name ) )
	     {
	         Tptr = p;
	         break;
	     }
	}
	if ( Tptr == NULL )
	{
	    CloseHandle( hEventThreadInQ );
	    CloseHandle( hMutexThreadInQ );
	    return FAIL;
	}

	/*
	** Finally we start the asynchronous I/O thread
	*/

	hThread = (HANDLE)_beginthreadex(&sa,
		       GC_STACK_SIZE,
		       (LPTHREAD_START_ROUTINE) GClanman_async_thread,
		       NULL,
		       (unsigned long)NULL,
		       &tid);
	if (hThread) 
	{
		CloseHandle(hThread);
	}
	else
	{
	    status = errno;
	    GCTRACE(1)("GClanman_init: Couldn't create thread errno = %d '%s'\n",
	    		status, strerror(status) );
	    return FAIL;
	}

	return OK;
}
Example #13
0
STATUS
ME_alloc_shared(i4          flag,
                SIZE_TYPE   pages,
                char        *key,
                PTR         *memory,
                SIZE_TYPE   *allocated_pages,
                CL_ERR_DESC *err_code)
{
	STATUS          status;
	SIZE_TYPE       memsize;
#ifdef LP64
	LARGE_INTEGER	numbytes;
#endif
	HANDLE          name;
	HANDLE          map;
	PTR             temp;
	char            map_key[MAX_LOC+1];
	char            *install_code;
	char		*ObjectPrefix;

    SECURITY_ATTRIBUTES sa;
    
	CLEAR_ERR(err_code);
	GVshobj(&ObjectPrefix);

	if (key == NULL || *key == '\0') {
		return (ME_BAD_PARAM);
	}
	memsize = pages * ME_MPAGESIZE;
        /*
        **  Moved ME_makekey to be called each time ME_alloc_shared is called
        **  as this obtains a handle to the file which will be required later
        **  if this is an attach to shared memory.
        **  This file handle is closed during an MEshared_free.
        */
        if ((name = ME_makekey(key)) == (HANDLE) -1)
        {
            status = GetLastError();
            SETWIN32ERR(err_code, status, ER_alloc);
            return (FAIL);
        }

	/* 
	**  The file mapping key used to be the name of the file.
	**  This caused problems when Jasmine and Ingres were installed
	**  on the same machine.  Create a unique key name, and use
	**  that for File Mapping instead.
	*/

	NMgtAt("II_INSTALLATION", &install_code);
    STpolycat(4, ObjectPrefix, SystemVarPrefix, install_code,
		      key, map_key);

	if (flag & ME_CREATE_MASK) {
	        iimksecdacl( &sa );
		FlushFileBuffers(name);
#ifdef LP64
		numbytes.QuadPart = Int32x32To64(pages, ME_MPAGESIZE);
		map = CreateFileMapping(name,
		                        &sa,
		                        PAGE_READWRITE,
		                        numbytes.HighPart,
		                        numbytes.LowPart,
		                        map_key);
#else
		map = CreateFileMapping(name,
		                        &sa,
		                        PAGE_READWRITE,
		                        0,
		                        memsize,
		                        map_key);
#endif  /* LP64 */

		if (map == NULL) {
			status = GetLastError();
			SETWIN32ERR(err_code, status, ER_alloc);
			FlushFileBuffers(name);
			CloseHandle(name);
			switch (status) {
			case ERROR_ALREADY_EXISTS:
				return ME_ALREADY_EXISTS;
			case ERROR_NOT_ENOUGH_MEMORY:
				return ME_OUT_OF_MEM;
			default:
				return FAIL;
			}
		}

		if (map != NULL && GetLastError() == ERROR_ALREADY_EXISTS) {
			FlushFileBuffers(name);
			CloseHandle(map);
			CloseHandle(name);
			return (ME_ALREADY_EXISTS);
		}
	} else {
		map = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE,
		                      FALSE,
		                      map_key);

		if (map == NULL) {
			status = GetLastError();
			SETWIN32ERR(err_code, status, ER_alloc);
			FlushFileBuffers(name);
			CloseHandle(name);
			switch (status) {
			case ERROR_FILE_NOT_FOUND:
				return ME_NO_SUCH_SEGMENT;
			case ERROR_NOT_ENOUGH_MEMORY:
				return ME_OUT_OF_MEM;
			default:
				return FAIL;
			}
		}
	}

	/*
	 * Finally.  Now get a memory address for the sucker.
	 * 
	 * If ME_ADDR_SPEC is set, we'll attempt to hardwire the address; else
	 * we'll take whatever the system gives us.
	 */

	if (flag & ME_ADDR_SPEC) {
		temp = MapViewOfFileEx(map,
		                       FILE_MAP_WRITE | FILE_MAP_READ,
		                       0,
		                       0,
		                       0,
		                       *memory);
		if ((temp == NULL) || (temp != *memory)) {
			status = GetLastError();
			SETWIN32ERR(err_code, status, ER_alloc);
			return (FAIL);
		}
	} else {
		*memory = MapViewOfFile(map,
		                        FILE_MAP_WRITE | FILE_MAP_READ,
		                        0,
		                        0,
		                        0);
		if (*memory == NULL) {
			status = GetLastError();
			SETWIN32ERR(err_code, status, ER_alloc);
			return (FAIL);
		}
	}

        /*
        **  If this is not an attach to shared memory assume that pages value
        **  is valid.
        */
        if ((flag & ME_CREATE_MASK) ||
            !(flag & (ME_SSHARED_MASK | ME_MSHARED_MASK)))
        {
	    pages = (SIZE_TYPE)(memsize / ME_MPAGESIZE);
        }
        else
        {
        BY_HANDLE_FILE_INFORMATION sFileInfo;

            /*
            **  If attaching to shared memory ignore the page argument and
            **  calculate size of shared segment in pages from file size.
            **  Assume that a single shared memory file will not exceed 4G.
            */

            if (GetFileInformationByHandle (name, &sFileInfo) == 0)
            {
                status = GetLastError();
                SETWIN32ERR(err_code, status, ER_alloc);
                return (FAIL);
            }
            else
            {
                pages = sFileInfo.nFileSizeLow / ME_MPAGESIZE;
            }
        }


	if (allocated_pages)
		*allocated_pages = pages;

        /*
        **  if this is an attach where pages is 0 ME_reg_seg will register
        **  pages calculated from the size of the file.
        */
	if (ME_reg_seg(*memory,
	               pages,
	               map,
	               name) != OK) {
		UnmapViewOfFile(memory);
		*memory = (PTR) NULL;
		return (FAIL);
	}

	return (OK);
}
Example #14
0
/*{
** Name: main()	- collation compiler
**
** Description:
**      Top level of collation compiler.
**
** Inputs:
**	argc			argument count
**	argv			argument vector
**
** Outputs:
**	none
**
** History:
**      03-may-89 (anton)
**          Created.
**	17-Jun-89 (anton)
**	    Moved to ADU from CL
**	21-Dec-89 (anton)
**	    Fixed usage message - removed magic number - bug 9193
**    	01-jun-92 (andys)
**          Correct spelling of 'language'. [bug 44495]
**	21-jun-93 (geri)
**	    PCexit with FAIL if error encountered; added CMset_attr call
**	    to intialize CM attribute table; chaged read-in char set
**	    to use II_CHARSET symbol. These were in the 6.4 version.
**	14-mar-2001 (stephenb)
**	    Add optional unicode indicator.
**	06-sep-2002 (hanch04)
**	    The 32 and 64 bit version need to be run so call PCspawnlp64.
**	14-Jun-2004 (schka24)
**	    Use (safe) canned charmap setting routine.
**	04-Mar-2005 (hanje04)
**	    SIR 114034
**	    Add support for reverse hybrid builds, i.e. 64bit exe needs to
** 	    call 32bit version.
**	09-Mar-2007 (gupsh01)
**	    Add support for upper/lower case operations.
**	20-Jun-2009 (kschendel) SIR 122138
**	    Hybrid add-on symbol changed, fix here.
*/
main(
int	argc,
char	*argv[])
{
    ADULTABLE	*tbl;
    ADUUCETAB	*utbl;
    STATUS   	stat;
    CL_ERR_DESC cl_err;
    bool	unicode = FALSE;
#if defined(conf_BUILD_ARCH_32_64) && defined(BUILD_ARCH32)
    char        *lp64enabled;
#endif

    _VOID_ MEadvise(ME_INGRES_ALLOC);

#if defined(conf_BUILD_ARCH_32_64) && defined(BUILD_ARCH32)

    /*
    ** Try to exec the 64-bit version
    */
    NMgtAt("II_LP64_ENABLED", &lp64enabled);
    if ( (lp64enabled && *lp64enabled) &&
       ( !(STbcompare(lp64enabled, 0, "ON", 0, TRUE)) ||
         !(STbcompare(lp64enabled, 0, "TRUE", 0, TRUE))))
    {
        PCspawnlp64(argc, argv);
    }
#endif  /* hybrid */
#if defined(conf_BUILD_ARCH_64_32) && defined(BUILD_ARCH64)
    {
	char        *lp32enabled;
	/*
	** Try to exec the 32-bit version
	*/
	NMgtAt("II_LP32_ENABLED", &lp32enabled);
	if ( (lp32enabled && *lp32enabled) &&
	( !(STbcompare(lp32enabled, 0, "ON", 0, TRUE)) ||
	!(STbcompare(lp32enabled, 0, "TRUE", 0, TRUE))))
	    PCspawnlp32(argc, argv);
    }
#endif  /* reverse hybrid */

    /* Set CM character set stuff */

    stat = CMset_charset(&cl_err);
    if (stat != OK)
    {
	SIprintf("Error while processing character set attribute file.\n");
	PCexit(FAIL);
    }

    _VOID_ SIeqinit();

    if (argc != 3 && argc != 4)
    {
        SIprintf("Usage: aducompile description-file language-file [-u]\n");
        PCexit(FAIL);
    }

    if (argc == 4)
    {
	/* must be -u flag for unicode */
	if (STbcompare(argv[3], 0, "-u", 0, TRUE))
	{
	    SIprintf("Usage: aducompile description-file language-file [-u]\n");
	    PCexit(FAIL);
	}
	unicode = TRUE;
    }

    if (unicode)
    {
	utbl = makeutable(argv[1]);
	if (!utbl)
	{
	    SIprintf("aducompile: description-file syntax error\n");
	    PCexit(FAIL);
	}

	stat = dumputbl(utbl, argv[2]);
	if (stat)
	    SIprintf("aducompile: dumptbl %s failed with %x\n", argv[2], stat);
    }
    else
    {
	tbl = maketable(argv[1]);
	if (!tbl)
	{
	    SIprintf("aducompile: description-file syntax error\n");
	    PCexit(FAIL);
	}

	stat = dumptbl(tbl, argv[2]);
	if (stat)
	    SIprintf("aducompile: dumptbl %s failed with %x\n", argv[2], stat);
    }
    PCexit(stat ? FAIL : OK);
}
Example #15
0
i4
main(
i4	argc,
char *	argv[])
{
    char      c='\0';
    char      *tz_file=NULL;
    char      *tz_name=NULL;
    char      *tz_def;
    char      tzname[TM_MAX_TZNAME+1];
    char      tzfile[MAX_LOC+1];
    char      ioptarg[MAX_LOC + 1];
    char      tz_pmvalue[MAX_LOC + 1];
    char      tz_pmname[MAX_LOC + 1];
    char      *p, *ip, *pm_value;
    char      *tm_tztype;
    char      chr='/';
    char      *out_file;
    i4        ioptind=1, i;
    char      *tm_tztime;
    i4        timecnt, tempi, temptype, temptz;
    char      buf[sizeof(TM_TZ_CB)+TM_MAX_TIMECNT*(sizeof(i4)+1)];
    FILE      *fid;
    LOCATION  loc_root, tmp_loc;
    STATUS    status=OK;
    TM_TZ_CB  *tm_tz_cb;
    struct timevect time_v;

    appname = argv[0];

    if( TMtz_getopt(argc, argv, "n:name:f:file", &ioptind, ioptarg, &c) == OK)
    {
	switch (c) 
	{
	  case 'f':
	    tz_file = ioptarg;
	    break;
	  case 'n':
	    tz_name = ioptarg;
	    break;
	  default:
	    break;
	}
    }
    else
    {
	TMtz_usage();
	PCexit(FAIL);
    }

    if( tz_file == NULL)
    {
	if( tz_name == NULL)
	{
	    /* Get II_TIMEZONE_NAME value */
	    NMgtAt(ERx("II_TIMEZONE_NAME"), &tz_def);
	    if (!tz_def || !(*tz_def))
	    {
		SIprintf("%s: %s_TIMEZONE_NAME is not set\n", 
				appname, SystemVarPrefix);
		PCexit(FAIL);
	    }
	    STncpy(tzname, tz_def, TM_MAX_TZNAME);
	    tzname[ TM_MAX_TZNAME ] = EOS;
	}
	else
	{
	    STncpy(tzname, tz_name, TM_MAX_TZNAME);
	    tzname[ TM_MAX_TZNAME ] = EOS;
	}
	PMinit();	
	if( PMload( NULL, (PM_ERR_FUNC *)NULL) != OK)
	{
	    SIprintf("%s: Error loading PM %s_CONFIG/config.dat file\n", 
			appname, SystemVarPrefix);
	    PCexit(FAIL);	    
	}
	/* Get timezone file name */
	STprintf( tz_pmname, ERx("%s.*.tz.%s"), SystemCfgPrefix, tzname);
	if( PMget( tz_pmname, &pm_value) != OK)
	{
	    SIprintf("%s: Error locating %s in PM config.dat file\n",
		     appname, tz_pmname);
    	    PCexit(FAIL);	    
	}
	do
	{
	    if((status = NMloc(FILES, PATH, ERx("zoneinfo"), &loc_root)) != OK)
		break;
#if defined(conf_BUILD_ARCH_32_64) && defined(BUILD_ARCH64)
	    if((status = LOfaddpath(&loc_root, ERx("lp64"), &loc_root)) != OK)
	        break;
#endif
#if defined(conf_BUILD_ARCH_64_32) && defined(BUILD_ARCH32)
	    {
	        /*
	        ** Reverse hybrid support must be available in ALL
	        ** 32bit binaries
	        */
	        char    *rhbsup;
	        NMgtAt("II_LP32_ENABLED", &rhbsup);
	        if ( (rhbsup && *rhbsup) &&
	       ( !(STbcompare(rhbsup, 0, "ON", 0, TRUE)) ||
	         !(STbcompare(rhbsup, 0, "TRUE", 0, TRUE))))
	            status = LOfaddpath(&loc_root, "lp32", &loc_root);
	    }
#endif /* reverse hybrid */

	    STcopy( pm_value, tz_pmvalue);

	    /*
	     ** Compose the directory path 
	     */
	    for( p = tz_pmvalue, ip = tz_pmvalue; 
		(p = STchr(ip, chr)) != NULL;)
	    {
		*p = EOS;
		if((status = LOfaddpath(&loc_root, ip, &loc_root)) != OK)
		    break;
		ip = CMnext(p);
	    }
	   
	    /* 
	    ** Add file name to the directory path
	    */
	    if((status = LOfroms(FILENAME, ip, &tmp_loc)) != OK)
		break;
	    status = LOstfile( &tmp_loc, &loc_root);
	} while( FALSE);

	if( status != OK)
	{
	    SIprintf("%s: Error composing timezone file name for %s\n",
		     appname, tz_pmvalue);
	    PCexit(FAIL);
	}
    }
    else
    {
	STcopy("<unknown>", tzname);
	STncpy( tzfile, tz_file, MAX_LOC);
	tzfile[ MAX_LOC ] = EOS;
	if( LOfroms(FILENAME&PATH, tzfile, &loc_root) != OK)
	{
	    SIprintf("%s: Error composing timezone file name for %s\n",
		     appname, tz_pmvalue);
	    PCexit(FAIL);
	}
    }

    /*
    ** Now open the timezone information file
    */
    do
    {
	if((status = SIfopen( &loc_root, ERx("r"), SI_VAR, sizeof buf, &fid)) 
	             != OK)
	    break;
	status = SIread(fid, sizeof buf, &i, buf);
	status = SIclose(fid);
    } while(FALSE);

    if( status != OK)
    {
	LOtos( &loc_root, &out_file);
	SIprintf("%s: Error opening %s for timezone %s\n", 
		 appname, out_file, tzname);
	PCexit(FAIL);
    }

    tm_tz_cb = (TM_TZ_CB *)&buf;
    I4ASSIGN_MACRO( tm_tz_cb->timecnt, timecnt);

    /* Make sure the input file has correct file size */
    if( timecnt > TM_MAX_TIMECNT || timecnt < 0
        || i != sizeof(TM_TZ_CB) + timecnt*(sizeof(i4)+1))
    {
	LOtos( &loc_root, &out_file);
	SIprintf(
	  "%s: Invalid file format for timezone file %s for timezone %s\n",
          appname, out_file, tzname);
	SIprintf(
	  "         File size: %d, Expected file size: %d, time periods: %d\n",
	  i, sizeof(TM_TZ_CB) + timecnt*(sizeof(i4)+1), 
	  timecnt);
	PCexit(FAIL);
    }

    /* Now we are all set to display the content of timezone information file */
    LOtos( &loc_root, &out_file);    
    SIprintf("\n\n");
    SIprintf("timezone name:     %s\n", tzname);
    SIprintf("timezone file:     %s\n", out_file);    
    SIprintf("-------------------------------------");
    SIprintf("-------------------------------------\n");

    if(timecnt == 0)
    {
	I4ASSIGN_MACRO( tm_tz_cb->tzinfo[0].gmtoff, tempi);
	SIprintf("     Fixed GMT offset (secs): %d\n", tempi);      
    }
    else
    {
	SIprintf("\tPeriod Begin");
	SIprintf("\t\tGMT offset\n");
	SIprintf("\t(YYYY_MM_DD HH:MM)");
	SIprintf("\t(Minute)\n\n");
	tm_tztype = buf + sizeof(TM_TZ_CB);
	tm_tztime = tm_tztype + timecnt;
	i=0;
	while( i < timecnt)
	{
	    I4ASSIGN_MACRO( *tm_tztime, tempi);
	    /* Adjust for timezone */
	    if( i == 0)
		temptype = (i4)tm_tztype[i+1];
	    else
		temptype = (i4)tm_tztype[i-1];

	    I4ASSIGN_MACRO( tm_tz_cb->tzinfo[temptype].gmtoff, temptz);
	    /* Get real timezone */
	    tempi += temptz;
	    temptype = (i4)tm_tztype[i];
	    I4ASSIGN_MACRO( tm_tz_cb->tzinfo[temptype].gmtoff, temptz);
	    TMtz_cvtime( tempi, &time_v);
	    SIprintf("\t%04d_%02d_%02d %02d:%02d\t%d\t%s\n", 
		     time_v.tm_year+1900,
		     time_v.tm_mon+1, 
		     time_v.tm_mday,
		     time_v.tm_hour,
		     time_v.tm_min,
		     temptz/60,
		     tm_tz_cb->tzlabel + tm_tz_cb->tzinfo[temptype].abbrind);  
	    tm_tztime += sizeof(i4);
	    i++;
	}
    }
    PCexit(OK);
}
Example #16
0
II_EXTERN IIAPI_ENVHNDL *
IIapi_initAPI( II_LONG version, II_LONG timeout )
{
    IIAPI_ENVHNDL	*envHndl;
    IIAPI_ENVHNDL	*defEnvHndl;
    II_BOOL		first_init = FALSE;
    STATUS		status;
    char		*env;

    if ( ! IIapi_static )
    {
	/*
	** Perform global initializations which are
	** environment independent.  
	*/
	first_init = TRUE;

	if ( ! ( IIapi_static = (IIAPI_STATIC *)
		 MEreqmem( 0, sizeof( IIAPI_STATIC ), TRUE, &status ) ) )
	    return( NULL );

	QUinit( &IIapi_static->api_env_q );

	if ( MUi_semaphore( &IIapi_static->api_semaphore ) != OK )
	    goto muiFail;

	if ( MEtls_create( &IIapi_static->api_thread ) != OK )
	    goto metFail;

	/*
	** Initialize sub-systems.
	*/
	IIAPI_INITTRACE();
	IIAPI_TRACE( IIAPI_TR_TRACE )( "IIapi_initAPI: initializing API.\n" );

	/*
	** Make sure II_SYSTEM or similar is set to provide useful feedback
	** rather than just failing in one of following subsystems.
	*/
	NMgtAt( SYSTEM_LOCATION_VARIABLE, &env );
	if ( env == NULL || *env == EOS )
	{
	    IIAPI_TRACE( IIAPI_TR_FATAL )
		( "IIapi_initAPI: error - %s not set.\n",
		  SYSTEM_LOCATION_VARIABLE );
	    goto adfFail;
	}
	
	IIapi_init_mib();
	if ( ! IIapi_initADF() )	goto adfFail;
	if ( ! IIapi_initGCA(timeout) )	goto gcaFail;

	/* Initialize the unicode collation values */
	IIapi_static->api_unicol_init = FALSE;
	IIapi_static->api_ucode_ctbl = NULL; 
	IIapi_static->api_ucode_cvtbl = NULL;

	/*
	** Create the default environment.
	*/
	if ( ! (IIapi_static->api_env_default = 
				(PTR)IIapi_createEnvHndl( IIAPI_VERSION_1 )) )
	    goto defFail;

	/* Spoken Language to use */

    	if( ( status = ERlangcode( (char *)NULL, 
				   &IIapi_static->api_slang ) != OK) )
    	{
	    IIAPI_TRACE( IIAPI_TR_ERROR )
		( "IIapi_initAPI: error initializing lang 0x%x\n", status );

	    return( NULL );
    	}

	/*
	** The SQL state machines are used by default prior to
	** IIapi_connect() being called, so make sure they are
	** initialized.
	*/
	if ( IIapi_sm_init( IIAPI_SMT_SQL ) != IIAPI_ST_SUCCESS )
	    goto envFail;
    }

    /*
    ** Now do environment specific initialization.
    */
    defEnvHndl = IIapi_defaultEnvHndl();

    if ( version == IIAPI_VERSION_1 )
    {
	/*
	** Version 1 initializers share the default
	** environment.  Keep track of the number of
	** initializers so that IIapi_termAPI() can
	** determine when to do global shutdown.
	*/
	envHndl = defEnvHndl;

	MUp_semaphore( &defEnvHndl->en_semaphore );
	defEnvHndl->en_initCount++;
	MUv_semaphore( &defEnvHndl->en_semaphore );
    }
    else
    {
	/*
	** Create a new environment for the initializer.
	** These environments are saved on the global
	** environment queue.  The caller may also make
	** API calls using the default environment handle, 
	** so increment the default environment handle
	** initialization count.
	*/
	if ( (envHndl = IIapi_createEnvHndl( version )) )
	{
	    MUp_semaphore( &IIapi_static->api_semaphore );
	    QUinsert( (QUEUE *)envHndl, &IIapi_static->api_env_q );
	    MUv_semaphore( &IIapi_static->api_semaphore );

	    MUp_semaphore( &defEnvHndl->en_semaphore );
	    defEnvHndl->en_initCount++;
	    MUv_semaphore( &defEnvHndl->en_semaphore );
	}
	else
	{
	    /*
	    ** We may need to undo the global initialization.
	    ** If not, the NULL environment handle will simply
	    ** be returned.
	    */
	    if ( first_init )  goto envFail;
	}
    }

    return( envHndl );

  envFail:
    IIapi_deleteEnvHndl( (IIAPI_ENVHNDL *)IIapi_static->api_env_default );

  defFail:
    IIapi_termGCA();

  gcaFail:
    IIapi_termADF();

  adfFail:
    IIAPI_TERMTRACE();
    MEtls_destroy( &IIapi_static->api_thread, NULL );

  metFail:
    MUr_semaphore( &IIapi_static->api_semaphore );

  muiFail:
    MEfree( (PTR)IIapi_static );
    IIapi_static = NULL;

    return( NULL );
}
Example #17
0
/*{
** Name:	main
**
** Description:
**	Start Replicator (replicat) as an NT Service.
**
** Inputs:
**	argc and argv from the command line
**		server_no	- server number
**
** Outputs:
**	none
**
** Returns:
**	none
**
** History:
**      14-Aug-97 (fanra01)
**          Modified the Query loop for service status give a chance to the
**          service control manager to update status.
**	28-jan-2000 (somsa01)
**	    Services are now keyed off of the installation identifier.
*/
i4
main(
i4	argc,
char	*argv[])
{
	SC_HANDLE	scm;
	SC_HANDLE	scs;
	i4		svc_argc;
	char		**svc_argv;
	SERVICE_STATUS	svc_status;
	TCHAR		svc_name[32];
	DWORD		ckpt = 0;
        BOOL            blCheck = TRUE;
	char		*cptr;

        MEfill (sizeof (SERVICE_STATUS), 0, &svc_status);
        svc_status.dwWaitHint = 2000;   /* default time set after start */
                                        /* service */

	if (argc < 2)
	{
		SIprintf("usage: rpserver <server_no> [args]\n");
		PCexit(FAIL);
	}
	NMgtAt("II_INSTALLATION", &cptr);
	STprintf(svc_name, ERx("%s_%s_%s"), SVC_NAME, cptr, argv[1]);

	/* connect to the service control manager */
	scm = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
	if (scm == NULL)
	{
		SIprintf("Error %d in OpenSCManager.\n", (i4)GetLastError());
		PCexit(FAIL);
	}

	scs = OpenService(scm, svc_name, SERVICE_START | SERVICE_QUERY_STATUS);
	if (scs == NULL)
	{
		DWORD dwError = GetLastError();
		switch(dwError)
		{
		     case ERROR_ACCESS_DENIED:
			SIprintf(ERROR_DENIED_PRIVILEGE);
			SIprintf(ERROR_REQ_ELEVATION);
			CloseServiceHandle(scm);
			PCexit(dwError);
		     default:
			SIprintf("Error %d in OpenService.\n", dwError);
			CloseServiceHandle(scm);
			PCexit(FAIL);
		}
	}

	svc_argc = argc - 2;
	svc_argv = (svc_argc == 0 ? NULL : argv + 2);
	if (!StartService(scs, svc_argc, svc_argv))
	{
		SIprintf("Error %d in StartService.\n", (i4)GetLastError());
		CloseServiceHandle(scs);
		CloseServiceHandle(scm);
		PCexit(FAIL);
	}

        Sleep (svc_status.dwWaitHint);

        do
        {
            ckpt = svc_status.dwCheckPoint; /* update check point */

            if (!QueryServiceStatus(scs, &svc_status))
            {
                SIprintf("Error %d in QueryServiceStatus.\n",
                         (i4)GetLastError());
		CloseServiceHandle(scs);
		CloseServiceHandle(scm);
                PCexit(FAIL);
            }

            /*
            ** if the check point hasn't moved since last
            ** check stop checking
            */
            switch (svc_status.dwCurrentState)
            {
                case SERVICE_START_PENDING:
                case SERVICE_CONTINUE_PENDING:
                    Sleep(svc_status.dwWaitHint);
                    break;
                case SERVICE_RUNNING:
                case SERVICE_STOPPED:
                default:
                    blCheck = FALSE;
                    break;
            }
        } while (blCheck);

	if (svc_status.dwCurrentState != SERVICE_RUNNING)
	{
		SIprintf("%s service not started:\n", svc_name);
		SIprintf("  Current State: %d\n",
			(i4)svc_status.dwCurrentState);
		SIprintf("  Exit Code: %d\n",
			(i4)svc_status.dwWin32ExitCode);
		SIprintf("  Service Specific Exit Code: %d\n",
			(i4)svc_status.dwServiceSpecificExitCode);
	}

	CloseServiceHandle(scs);
	CloseServiceHandle(scm);
}
Example #18
0
/*{
** Name: LGK_initialize()	-  initialize the lg/lk shared mem segment.
**
** Description:
**	This routine is called by the LGinitialize or LKinitialize routine.  IT
**	assumes that a previous caller has allocated the shared memory segment.
**
**	If it discovers that the shared memory segment has not yet been
**	initialized, it calls the LG and LK initialize-memory routines to do so.
**
** Inputs:
**	flag		- bit mask of:
**			  LOCK_LGK_MEMORY to lock the shared data segment
**			  LGK_IS_CSP if process is CSP process this node.
**
** Outputs:
**	sys_err		- place for system-specific error information.
**
**	Returns:
**	    OK	- success
**	    !OK - failure (CS*() routine failure, segment not mapped, ...)
**	
**  History:
**	Summer, 1992 (bryanp)
**	    Working on the new portable logging and locking system.
**	19-oct-1992 (bryanp)
**	    Check memory version number when attaching.
**	22-oct-1992 (bryanp)
**	    Change LGLKDATA.MEM to lglkdata.mem.
**	23-Oct-1992 (daveb)
**	    name the semaphore too.
**	13-feb-1993 (keving)
**	    Remove support for II_LGK_MEMORY_SIZE. If II_LG_MEMSIZE
**	    is not set then calculate memory size from PM values. 
**	24-may-1993 (bryanp)
**	    If the shared memory is the wrong version, don't install the
**	    at_exit handlers (the rundown routines won't be able to interpret
**	    the memory properly).
**	26-jul-1993 (jnash)
**	    Add 'flag' param lock the LGK data segment.
**	20-sep-1993 (bryanp)
**	    In addition to calling PCatexit, call (on VMS) sys$dclexh, since
**		there are some situations (image death and image rundown without
**		process rundown) which are caught neither by PCatexit (since
**		PCexit isn't run) nor by check-dead threads (since process
**		rundown never happened). This fixes a hole where an access-
**		violating ckpdb or auditdb command never got cleaned up.
**	31-jan-1994 (bryanp)
**	    Back out a few "features" which are proving countereffective:
**	    1) Don't bother checking mem_creator_pid to see if the previous
**		creator of the shared memory has died. This was an attempt to
**		gracefully re-use sticky shared memory following a system crash,
**		but it is suspected as being the culprit in a series of system
**		failures by re-initializing the shared memory at inopportune
**		times.
**	    2) Don't complain if the shared memory already exists but is of a
**		different size than you expected. Just go ahead and try to use
**		it anyway.
**	21-feb-1994 (bryanp)
**	    Reverse item (1) of the above 31-jan-1994 change and re-enable the
**		graceful re-use of shared memory. People weren't happy with
**		having to run ipcclean and csinstall all the time.
**	23-may-1994 (bryanp)
**	    On VMS, disable ^Y for LG/LK-aware processes. We don't want to allow
**		^Y because you might interrupt the process right in the middle
**		of an LG or LK operation, while holding the shared memory
**		semaphore, and this would then wedge the whole installation.
**          
**      17-May-1994 (daveb) 59127
**          Attach lgk_mem semaphore if we're attaching to the segment.
**      30-jan-1995 (lawst01) bug 61984
**          Use memory needed calculation from the 'lgk_calculate_size'
**          function to determine the size of the shared memory pool for
**          locking and locking. If the II_LG_MEMSIZE variable is specified
**          with a value larger than needed use the supplied value. If
**          lgk_calculate_size is unable to calculate a size then use the
**          magic number of 400000.  In addition issue a warning message
**          and continue executing in the event the number of pages
**          allocated is less than the number requested. 
**	24-apr-1997 (nanpr01)
**	    Reinstate Bryanp's change. In the process of fixing bug 61984
**	    by Steve Lawrence and subsequent undo of Steve's fix by Nick
**	    Ireland on 25-jun-96 (nick) caused the if 0 code removed.
**	    Part of the Steve's change was not reinstated such as not returning
**	    the status and exit and continue.
**	    1. Don't complain if the shared memory already exists but is of a
**	    different size than you expected. Just go ahead and try to use
**	    it.
**     18-aug-1998 (hweho01)
**          Reclaim the kernel resource if LG/LK shared memory segment is  
**          reinitialized. If the shared segment is re-used (the previous creator 
**          of the shared segment has died), the cross-process semaphores get 
**          initialized more than once at the same locations. That cause the
**          kernel resource leaks on DG/UX (OS release 4.11MU04). To fix the 
**          problem, CS_cp_sem_cleanup() is called to destroy all the 
**          semaphores before LG/LK shraed segment get recreated. 
**          CS_cp_sem_cleanup() is made dependent on xCL_NEED_SEM_CLEANUP and
**          OS_THREADS_USED, it returns immediately for most platforms.  
**	27-Mar-2000 (jenjo02)
**	    Added test for crossed thread types, refuse connection
**	    to LGK memory with E_DMA811_LGK_MT_MISMATCH.
**	18-apr-2001 (devjo01)
**	    s103715 (Portable cluster support)
**	    - Add CX mem requirement calculations.
**	    - Add LGK_IS_CSP flag to indicate that LGK memory is being
**	      initialized for a CSP process.
**	    - Add basic CX initialization.
**      19-sep-2002 (devjo01)
**          If running NUMA clustered allocate memory out of local RAD.
**	30-Apr-2003 (jenjo02)
**	    Rearchitected to silence long-tolerated race conditions.
**	    BUG 110121.
**	27-feb-2004 (devjo01)
**	    Rework allocation of CX shared memory to be compatible
**	    with race condition fix introduced for bug 110121.
**	29-Dec-2008 (jonj)
**	    If lgk_calculate_size() returns FAIL, the total memory
**	    needed exceeds MAX_SIZE_TYPE and we can't continue, but
**	    tell what we can about the needs of the various bits of
**	    memory before quitting.
**	06-Aug-2009 (wanfr01)
**	    Bug 122418 - Return E_DMA812 if LOCK_LGK_MUST_ATTACH is
**	    is passed in and memory segment does not exist
**      20-Nov-2009 (maspa05) bug 122642
**          In order to synchronize creation of UUIDs across servers added
**          a semaphore and a 'last time' variable into LGK memory. 
**      14-Dec-2009 (maspa05) bug 122642
**          #ifdef out the above change for Windows. The rest of the change
**          does not apply to Windows so the variables aren't defined.
*/
STATUS
LGK_initialize(
i4	  	flag,
CL_ERR_DESC	*sys_err,
char		*lgk_info)
{
    PTR		ptr;
    SIZE_TYPE	memleft;
    SIZE_TYPE	size;
    STATUS	ret_val;
    STATUS	mem_exists;
    char	mem_name[15];
    SIZE_TYPE	allocated_pages;
    i4		me_flags;
    i4		me_locked_flag;
    SIZE_TYPE	memory_needed;
    char	*nm_string;
    SIZE_TYPE	pages;
    LGK_MEM	*lgk_mem;
    i4		err_code;
    SIZE_TYPE   min_memory;
    i4		retries;
    i4		i;
    i4		attached;
    PID		*my_pid_slot;
    i4		clustered;
    u_i4	nodes;
    SIZE_TYPE	cxmemreq;
    PTR		pcxmem;
    LGLK_INFO	lgkcount;
    char	instid[4];

    CL_CLEAR_ERR(sys_err);

    /*
    ** if LGK_base is set then this routine has already been called.  It is
    ** set up so that both LGiniitalize and LKinitialize calls it, but only
    ** the first call does anything.
    */

    if (LGK_base.lgk_mem_ptr)
	return(OK);

    PCpid( &LGK_my_pid );

    memory_needed = 0;
    NMgtAt("II_LG_MEMSIZE", &nm_string);
    if (nm_string && *nm_string)
#if defined(LP64)
	if (CVal8(nm_string, (long*)&memory_needed))
#else
	if (CVal(nm_string, (i4 *)&memory_needed))
#endif /* LP64 */
	    memory_needed = 0;

    /* Always calculate memory needed from PM resource settings  */
    /* and compare with supplied value, if supplied value is less */
    /* than minimum then use minimum                             */

    min_memory = 0;
    if ( OK == lgk_get_counts(&lgkcount, FALSE))
    {
	if ( lgk_calculate_size(FALSE, &lgkcount, &min_memory) )
	{
	    /*
	    ** Memory exceeds MAX_SIZE_TYPE, can't continue.
	    ** 
	    ** Do calculation again, this time with "wordy"
	    ** so user can see allocation bits, then quit.
	    */
	    lgk_calculate_size(TRUE, &lgkcount, &min_memory);
	    return (E_DMA802_LGKINIT_ERROR); 
	}
    }
    if (min_memory)
       memory_needed = (memory_needed < min_memory) ? min_memory
                                                    : memory_needed;
    else
       memory_needed = (memory_needed < 400000 ) ? 400000 
                                                 : memory_needed;

    clustered = (i4)CXcluster_enabled();
    cxmemreq = 0;
    if ( clustered )
    {

	if ( OK != CXcluster_nodes( &nodes, NULL ) )
	    nodes = 0;
	cxmemreq = CXshm_required( 0, nodes, lgkcount.lgk_max_xacts,
		    lgkcount.lgk_max_locks, lgkcount.lgk_max_resources );
	if ( MAX_SIZE_TYPE - memory_needed < cxmemreq )
	{
	    /*
	    ** Memory exceeds MAX_SIZE_TYPE, can't continue.
	    ** 
	    ** Do calculation again, this time with "wordy"
	    ** so user can see allocation bits, then quit.
	    */
	    SIprintf("Total LG/LK/CX allocation exceeds max of %lu bytes by %lu\n"
	    	     "Adjust logging/locking configuration values and try again\n",
		         MAX_SIZE_TYPE, cxmemreq - (MAX_SIZE_TYPE - memory_needed));
	    lgk_calculate_size(TRUE, &lgkcount, &min_memory);
	    return (E_DMA802_LGKINIT_ERROR); 
	}
	memory_needed += cxmemreq;
    }

    if ( memory_needed < MAX_SIZE_TYPE - ME_MPAGESIZE )
	pages = (memory_needed + ME_MPAGESIZE - 1) / ME_MPAGESIZE;
    else
        pages = memory_needed / ME_MPAGESIZE;

    /*
    ** Lock the LGK segment if requested to do so
    */
    if (flag & LOCK_LGK_MEMORY)
	me_locked_flag = ME_LOCKED_MASK;
    else
	me_locked_flag = 0;

    me_flags = (me_locked_flag | ME_MSHARED_MASK | ME_IO_MASK | 
		ME_CREATE_MASK | ME_NOTPERM_MASK | ME_MZERO_MASK);
    if (CXnuma_user_rad())
        me_flags |= ME_LOCAL_RAD;

    STcopy("lglkdata.mem", mem_name);

    /*
    ** In general, we just want to attach to the shared memory and detect if
    ** we are the first process to do so. However, there are ugly race
    ** conditions to consider, as well as complications because the shared
    ** memory may be left around following a system crash.
    **
    ** First we attempt to create the shared memory. Usually it already exists,
    ** so we check for and handle the case of "already exists".
    */

    /*
    ** (jenjo02)
    **
    ** Restructured to better handle all those ugly race conditions
    ** which are easily reproduced by running two scripts, one that
    ** continuously executes "lockstat" while the other is starting
    ** and stopping Ingres.
    **
    ** For example,
    **
    **		lockstat A	acquires and init's the memory
    **		RCP		attaches to "A" memory
    **		lockstat A	terminates normally
    **		lockstat B	attaches to "A" memory, sees that
    **				"A"s pid is no longer alive, and
    **				reinitializes the memory, much to
    **				the RCP's chagrin.
    ** or (more commonly)
    **
    **		lockstat A	acquires and begins to init the mem
    **		RCP		attaches to "A" memory which is
    **				still being zero-filled by lockstat,
    **				checks the version number (zero),
    **				and fails with a E_DMA434 mismatch.
    **
    ** The fix utilizes the mem_ext_sem to synchronize multiple
    ** processes; if the semaphore hasn't been initialized or
    ** if mem_version_no is zero, we'll wait one second and retry,
    ** up to 60 seconds before giving up. This gives the creating
    ** process time to complete initialization of the memory.
    **
    ** Up to LGK_MAX_PIDS are allowed to attach to the shared
    ** memory. When a process attaches it sets its PID in the
    ** first vacant slot in lgk_mem->mem_pid[]; if there are
    ** no vacant slots, the attach is refused. When the process
    ** terminates normally by calling LGK_rundown(), it zeroes
    ** its PID slot.
    **
    ** When attaching to an existing segment, we check if  
    ** there are any live processes still using the memory;
    ** if so, we can't destroy it (no matter who created it).
    ** If there are no live processes attached to the memory,
    ** we destroy and reallocate it (based on current config.dat
    ** settings).
    */

    for ( retries = 0; ;retries++ )
    {
	LGK_base.lgk_mem_ptr = (PTR)NULL;
	
	/* Give up if unable to get memory in one minute */
#if defined(conf_CLUSTER_BUILD)
        if (retries > 1)
#else
	if ( retries )
#endif
	{
	    if ( retries < 60 )
		PCsleep(1000);
	    else
	    {
		/* Another process has it blocked way too long */
		uleFormat(NULL, E_DMA800_LGKINIT_GETMEM, (CL_ERR_DESC *)NULL,
				ULE_LOG, NULL, NULL, 0, NULL, &err_code, 0);
		/* Unable to attach allocated shared memory segment. */
		return (E_DMA802_LGKINIT_ERROR); 
	    }
	}

	ret_val = MEget_pages(me_flags,
				pages, mem_name, (PTR*)&lgk_mem,
				&allocated_pages, sys_err);

	if ( mem_exists = ret_val )
	{
	    if (ret_val == ME_ALREADY_EXISTS)
	    {
		ret_val = MEget_pages((me_locked_flag | 
				       ME_MSHARED_MASK | ME_IO_MASK),
				      pages, mem_name, (PTR*)&lgk_mem,
				      &allocated_pages, sys_err);
#if defined(conf_CLUSTER_BUILD)
                if (ret_val && !retries)
                    continue;  /* try one more time */
#endif
	    }
	    if (ret_val)
	    {
		uleFormat(NULL, ret_val, sys_err,
				ULE_LOG, NULL, NULL, 0, NULL, &err_code, 0);
		uleFormat(NULL, E_DMA800_LGKINIT_GETMEM, (CL_ERR_DESC *)NULL,
				ULE_LOG, NULL, NULL, 0, NULL, &err_code, 0);
		/* Unable to attach allocated shared memory segment. */
		return (E_DMA802_LGKINIT_ERROR); 
	    }
	}
	else if (flag & LOCK_LGK_MUST_ATTACH)
	{	
	    /* Do not use the shared segment you just allocated */
	    MEfree_pages((PTR)lgk_mem, allocated_pages, sys_err);
	    return (E_DMA812_LGK_NO_SEGMENT); 
	}

	size = allocated_pages * ME_MPAGESIZE;

	/* Expose this process to the memory */
	LGK_base.lgk_mem_ptr = (PTR)lgk_mem;

	if ( mem_exists )
	{
	    /*
	    ** Memory exists.
	    **
	    ** Try to acquire the semaphore. If it's
	    ** uninitialzed, retry from the top.
	    **
	    ** If the version is zero, then another
	    ** process is initializing the memory;
	    ** keep retrying until the version is 
	    ** filled in.
	    **
	    */
	    if ( ret_val = CSp_semaphore(1, &lgk_mem->mem_ext_sem) )
	    {
		if ( ret_val != E_CS000A_NO_SEMAPHORE )
		{
		    uleFormat(NULL, ret_val, sys_err,
				ULE_LOG, NULL, NULL, 0, NULL, &err_code, 0);
		    ret_val = E_DMA802_LGKINIT_ERROR;
		    break;
		}
		continue;
	    }

	    /* Retry if still being init'd by another process */
	    if ( !lgk_mem->mem_version_no )
	    {
		CSv_semaphore(&lgk_mem->mem_ext_sem);
		continue;
	    }

	    /*
	    ** Check pids which appear to be attached to
	    ** the memory:
	    **
	    ** If any process is still alive, then we
	    ** assume the memory is consistent and use it.
	    **
	    ** If a process is now dead, it terminated
	    ** without going through LGK_rundown
	    ** to zero its PID slot, zero it now.
	    **
	    ** If there are no live PIDs attached to 
	    ** the memory, we destroy and recreate it.
	    */
	    my_pid_slot = (PID*)NULL;
	    attached = 0;

	    for ( i = 0; i < LGK_MAX_PIDS; i++ )
	    {
		if ( lgk_mem->mem_pid[i] && 
		     PCis_alive(lgk_mem->mem_pid[i]) )
		{
		    attached++;
		}
		else
		{
		    /* Vacate the slot */
		    if (lgk_mem->mem_pid[i])
		    {
			uleFormat(NULL, E_DMA499_DEAD_PROCESS_INFO, (CL_ERR_DESC *)NULL,
				ULE_LOG, NULL, NULL, 0, NULL, &err_code, 2,
				0, lgk_mem->mem_pid[i],
				0, lgk_mem->mem_info[i].info_txt);
		    }
		    lgk_mem->mem_pid[i] = (PID)0;
		    lgk_mem->mem_info[i].info_txt[0] = EOS;

		    /* Use first vacant slot for this process */
		    if ( !my_pid_slot )
		    {
			my_pid_slot = &lgk_mem->mem_pid[i];
			LGK_base.lgk_pid_slot = i;
		    }
		}
		/* Quit when both questions answered */
		if ( attached && my_pid_slot )
		    break;
	    }

	    /* If no living pids attached, destroy/reallocate */
	    if ( !attached )
	    {
		CSv_semaphore(&lgk_mem->mem_ext_sem);
		if ( LGK_destroy(allocated_pages, sys_err) )
		{
		    ret_val = E_DMA802_LGKINIT_ERROR;
		    break;
		}
		continue;
	    }

	    /* All attached pids alive? */
	    if ( !my_pid_slot )
	    {
		/* ... then there's no room for this process */
		uleFormat(NULL, E_DMA80A_LGK_ATTACH_LIMIT, (CL_ERR_DESC *)NULL,
		    ULE_LOG, NULL, NULL, 0, NULL, &err_code, 1,
		    0, attached);
	        ret_val = E_DMA802_LGKINIT_ERROR;
	    }
	    else if (lgk_mem->mem_version_no != LGK_MEM_VERSION_CURRENT)
	    {
		uleFormat(NULL, E_DMA434_LGK_VERSION_MISMATCH, (CL_ERR_DESC *)NULL,
		    ULE_LOG, NULL, NULL, 0, NULL, &err_code, 2,
		    0, lgk_mem->mem_version_no, 0, LGK_MEM_VERSION_CURRENT);
		ret_val = E_DMA435_WRONG_LGKMEM_VERSION;
	    }
	    /*
	    ** Don't allow mixed connections of MT/non-MT processes.
	    ** Among other things, the mutexing mechanisms are 
	    ** incompatible!
	    */
	    else if ( (CS_is_mt() && (lgk_mem->mem_status & LGK_IS_MT) == 0) ||
		     (!CS_is_mt() &&  lgk_mem->mem_status & LGK_IS_MT) )
	    {
		uleFormat(NULL, E_DMA811_LGK_MT_MISMATCH, (CL_ERR_DESC *)NULL,
		    ULE_LOG, NULL, NULL, 0, NULL, &err_code, 2,
		    0, (lgk_mem->mem_status & LGK_IS_MT) ? "OS"
							 : "INTERNAL",
		    0, (CS_is_mt()) ? "OS"
				    : "INTERNAL");
		ret_val = E_DMA802_LGKINIT_ERROR;
	    }
	    else
	    {
		/*
		** CX memory (if any) will lie immediately past LGK header.
		*/
		pcxmem = (PTR)(lgk_mem + 1);
		pcxmem = (PTR)ME_ALIGN_MACRO(pcxmem, sizeof(ALIGN_RESTRICT));

		LGK_base.lgk_lkd_ptr = (char *)LGK_base.lgk_mem_ptr +
					lgk_mem->mem_lkd;
		LGK_base.lgk_lgd_ptr = (char *)LGK_base.lgk_mem_ptr +
					lgk_mem->mem_lgd;
		
		/* Stuff our pid in first vacant slot */
		*my_pid_slot = LGK_my_pid;
		STlcopy(lgk_info, lgk_mem->mem_info[i].info_txt, LGK_INFO_SIZE-1);
	    }

#if defined(VMS) || defined(UNIX)
	    /* set up pointers to reference the uuid mutex and last time
	     * variable */

	    if (!ID_uuid_sem_ptr)
           	ID_uuid_sem_ptr=&lgk_mem->id_uuid_sem;

	    if (!ID_uuid_last_time_ptr)
                ID_uuid_last_time_ptr=&lgk_mem->uuid_last_time;

	    if (!ID_uuid_last_cnt_ptr)
                ID_uuid_last_cnt_ptr=&lgk_mem->uuid_last_cnt;
#endif

	    CSv_semaphore(&lgk_mem->mem_ext_sem);
	}
	else
	{

	    /* Memory did not exist */
	    /* Zero the version to keep other processes out */
	    lgk_mem->mem_version_no = 0;

#if defined(VMS) || defined(UNIX)
	    /* set up the uuid mutex and last time pointers to
	     * reference the objects in shared memory */

	    {
	        STATUS id_stat;

	        ID_uuid_sem_ptr=&lgk_mem->id_uuid_sem;
                ID_uuid_last_time_ptr=&lgk_mem->uuid_last_time;
                ID_uuid_last_cnt_ptr=&lgk_mem->uuid_last_cnt;
	        *ID_uuid_last_cnt_ptr=0;
	        ID_UUID_SEM_INIT(ID_uuid_sem_ptr,CS_SEM_MULTI,"uuid sem",
				&id_stat);
	    }
#endif

	    /* ... then initialize the mutex */
	    CSw_semaphore(&lgk_mem->mem_ext_sem, CS_SEM_MULTI,
	    			    "LGK mem ext sem" );

	    /* Record if memory created for MT or not */
	    if ( CS_is_mt() )
		lgk_mem->mem_status = LGK_IS_MT;

	    /*
	    ** memory is as follows:
	    **
	    **	-----------------------------------------------------------|
	    **	| LGK_MEM struct (keep track of this mem)	           |
	    **	|							   |
	    **	-----------------------------------------------------------|
	    **	| If a clustered installation memory reserved for CX       |
	    **	|							   |
	    **	------------------------------------------------------------
	    **	| LKD - database of info for lk system			   |
	    **	|							   |
	    **	------------------------------------------------------------
	    **	| LGD - database of info for lg system			   |
	    **	|							   |
	    **	------------------------------------------------------------
	    **	| memory manipulated by LGKm_* routines for structures used |
	    **	| by both the lk and lg systems.			   |
	    **	|							   |
	    **	------------------------------------------------------------
	    */

	    /* put the LGK_MEM struct at head of segment leaving ptr pointing 
	    ** at next aligned piece of memory
	    */

	    /*
	    ** CX memory (if any) will lie immediately past LGK header.
	    */
	    pcxmem = (PTR)(lgk_mem + 1);
	    pcxmem = (PTR)ME_ALIGN_MACRO(pcxmem, sizeof(ALIGN_RESTRICT));

	    LGK_base.lgk_lkd_ptr = pcxmem + cxmemreq;
	    LGK_base.lgk_lkd_ptr = (PTR) ME_ALIGN_MACRO(LGK_base.lgk_lkd_ptr,
						sizeof(ALIGN_RESTRICT));
	    lgk_mem->mem_lkd = (i4)((char *)LGK_base.lgk_lkd_ptr -
					 (char *)LGK_base.lgk_mem_ptr);

	    LGK_base.lgk_lgd_ptr = (PTR) ((char *) LGK_base.lgk_lkd_ptr +
					    sizeof(LKD));
	    LGK_base.lgk_lgd_ptr = (PTR) ME_ALIGN_MACRO(LGK_base.lgk_lgd_ptr,
						sizeof(ALIGN_RESTRICT));
	    lgk_mem->mem_lgd = (i4)((char *)LGK_base.lgk_lgd_ptr -
					 (char *)LGK_base.lgk_mem_ptr);

	    /* now initialize the rest of memory for allocation */

	    /* how much memory is left? */

	    ptr = ((char *)LGK_base.lgk_lgd_ptr + sizeof(LGD));
	    memleft = size - (((char *) ptr) - ((char *) LGK_base.lgk_mem_ptr));

	    if ( (ret_val = lgkm_initialize_mem(memleft, ptr)) == OK &&
		 (ret_val = LG_meminit(sys_err)) == OK &&
		 (ret_val = LK_meminit(sys_err)) == OK )
	    {
		/* Clear array of attached pids and pid info */
		for ( i = 0; i < LGK_MAX_PIDS; i++ )
		{
		    lgk_mem->mem_pid[i] = (PID)0;
		    lgk_mem->mem_info[i].info_txt[0] = EOS;
		}

		/* Set the creator pid */
		LGK_base.lgk_pid_slot = 0;
		lgk_mem->mem_creator_pid = LGK_my_pid;

		/* Set the version, releasing other processes */
		lgk_mem->mem_version_no = LGK_MEM_VERSION_CURRENT;
	    }
	    else
	    {
		uleFormat(NULL, ret_val, (CL_ERR_DESC *)NULL,
			    ULE_LOG, NULL, NULL, 0, NULL, &err_code, 0);
		ret_val = E_DMA802_LGKINIT_ERROR;

		/* Destroy the shared memory */
		LGK_destroy(allocated_pages, sys_err);
	    }
	}

	if ( ret_val == OK )
	{
	    PCatexit(LGK_rundown);

	    if ( clustered )
	    {
		/*
		** Perform preliminary cluster connection and CX memory init.
		*/

		/* Get installation code */
		NMgtAt("II_INSTALLATION", &nm_string);
		if ( nm_string )
		{
		    instid[0] = *(nm_string);
		    instid[1] = *(nm_string+1);
		}
		else
		{
		    instid[0] = 'A';
		    instid[1] = 'A';
		}
		instid[2] = '\0';
		ret_val = CXinitialize( instid, pcxmem, flag & LGK_IS_CSP );
		if ( ret_val )
		{
		    /* Report error returned from CX */
		    uleFormat(NULL, ret_val, (CL_ERR_DESC *)NULL,
			ULE_LOG, NULL, NULL, 0, NULL, &err_code, 0 );
		    break;
		}
	    }

#ifdef VMS
	    {
	    static $EXHDEF	    exit_block;
	    i4			ctrl_y_mask = 0x02000000;

	    /*
	    ** On VMS, programs like the dmfjsp and logstat run as images in
	    ** the shell process. That is, the system doesn't start and stop
	    ** a process for each invocation of the program, it just starts
	    ** and stops an image in the same process. This means that if
	    ** the program should die, the image may be rundown but the process
	    ** will remain, which means that the check-dead threads of other
	    ** processes in the installation will not feel that they need to
	    ** rundown this process, since it's still alive.
	    **
	    ** By declaring an exit handler, which will get a chance to run
	    ** even if PCexit isn't called, we improve our chances of getting
	    ** to perform rundown processing if we should die unexpectedly.
	    **
	    ** Furthermore, we ask DCL to disable its ^Y processing, which
	    ** lessens the chance that the user will interrupt us while we
	    ** are holding the semaphore.
	    */
	    exit_block.exh$g_func = LGK_rundown;
	    exit_block.exh$l_argcount = 1;
	    exit_block.exh$gl_value = &exit_block.exh$l_status;

	    if (sys$dclexh(&exit_block) != SS$_NORMAL)
		ret_val = FAIL;

	    lib$disable_ctrl(&ctrl_y_mask, 0);
	    }
#endif
	}
	break;
    }

    if ( ret_val )
	LGK_base.lgk_mem_ptr = NULL;

    return(ret_val);
}
Example #19
0
/*{
** Name: CK_subst - build a CK command from template and requirements
**
** Description:
**	This function will search a CK command template file for
**	a line meeting the requirements of the inputs and will substitute
**	various esacpe sequences with other strings such as file names.
**
**	Based on a II_subst of the 5.0 UNIX CL.
**
** Inputs:
**	comlen			length of cline space
**	oper			operation - one of 'B'egin, 'E'nd, 'W'ork
**	dev			device type - one of 'T'ape, 'D'isk
**	dir			direction - one of 'S'ave, 'R'estore
**	type			type (device type) 0 for disk, 1 for tape
**	locnum			location number (sequence or quantity)
**	di_l_path		length of di path string
**	di_path			di path string
**	ckp_l_path		length of checkpoint path string
**	ckp_path		checkpoint path string
**	ckp_l_file		length of checkpoint file string
**	ckp_file		checkpoint file string
**
** Outputs:
**	cline			space for generated command
**
**	Returns:
**	    CK_FILENOTFOUND	template file can't be found
**	    E_DB_OK
**
**	Exceptions:
**	    none
**
** Side Effects:
**	    none
**
** History:
**      27-oct-88 (anton)
**	    Created.
**	16-may-90 (walt)
**	    Return CK_FILENOTFOUND if the template file (cktmpl.def) can't
**	    be opened.
**	23-may-1994 (bryanp)
**	    Modified Walt's 16-may-90 fix to use CK_TEMPLATE_MISSING, rather
**		than CK_FILENOTFOUND, since CK_TEMPLATE_MISSING is a more
**		specific, and therefore hopefully more useful, error message.
**	03-jan-1995 (dougb)
**	    Cross-integrate Unix change 415365:
**	    02-dec-1994 (andyw)
**		Check on granularity for partial backup
*/
STATUS
CK_subst(
char	*cline,
i4	comlen,
char	oper, 
char	dev, 
char	dir,
u_i4	type, 
u_i4	locnum, 
u_i4	di_l_path, 
char	*di_path,
u_i4	ckp_l_path, 
char	*ckp_path,
u_i4	ckp_l_file,
char	*ckp_file)
{
    STATUS		ret_val = OK;
    auto LOCATION	loc;
    auto char		*s;
    auto FILE		*fp;
    auto char		*cp;
    char		*command;

    command = MEreqmem(0, comlen, TRUE, &ret_val);

    if (!ret_val)
    {
	NMgtAt("II_CKTMPL_FILE", &s);
	if (s == NULL || *s == EOS)
	{
	    ret_val = NMf_open("r", "cktmpl.def", &fp);
	}
	else
	{
	    LOfroms( PATH & FILENAME, s, &loc );
	    ret_val = SIopen( &loc, "r", &fp);
	}
	if (ret_val)
	{
	    ret_val = CK_TEMPLATE_MISSING;
	}
    }

    /* find command line - skip comments and blank lines */
    if (!ret_val)
    {
	while ((ret_val = SIgetrec(command, comlen, fp)) == OK)
	{
	    if (*command == '\n')
	    {
		continue;
	    }
	    if (command[0] == oper
		&& (command[1] == dir || command[1] == 'E')
		&& (command[2] == dev || command[2] == 'E')
		&& (command[3] == 'D' || command[3] == 'E')
		&& command[4] == ':')
	    {
		break;
	    }
	}
    }

    _VOID_ SIclose(fp);

    if (!ret_val)
    {
	/* found the line - do the substitution */
	s = command + 5;
	cp = cline;
	while (*s != '\n')
	{
	    if (*s == '%')
	    {
		switch (*++s)
		{
		case '%':
		    *cp++ = '%';
		    break;
		case 'D':
		    CK_lfill(&cp, di_l_path, di_path);
		    break;
		case 'C':
		    CK_lfill(&cp, ckp_l_path, ckp_path);
		    break;
		case 'F':
		    CK_lfill(&cp, ckp_l_file, ckp_file);
		    break;
		case 'A':
		    CK_lfill(&cp, ckp_l_path, ckp_path);
# ifdef	UNIX
		    *cp++ = '/';
# endif
		    CK_lfill(&cp, ckp_l_file, ckp_file);
		    break;
		case 'T':
		    *cp++ = type ? '1' : '0';
		    break;
		case 'N':
		    CVna(locnum, cp);
		    while (*cp)
			cp++;
		    break;
		default:
		    *cp++ = '%';
		    *cp++ = *s;
		}
		++s;
	    }
	    else
	    {
		*cp++ = *s++;
	    }
	}
	*cp = EOS;
    }

# ifdef	xDEBUG
    TRdisplay("CK_subst %c %c %c: %s\n", oper, dir, dev, cline);
# endif
    return(ret_val);
}
Example #20
0
/* Name: adu_getconverter - Obtains the name of converter mapping file
**			    to use for unicode coercion. 
** Description:
**
** To obtain the mapping file to be used for carrying out unicode-local
** character conversion. The following mechanism is followed:
**
** 1. Check symbol table for user defined converter setting
**    II_UNICODE_CONVERTER. If set then return this setting 
** 2. If the variable is not set then 
**	2.a Get the platform character set
**	2.b Read the aliasmaptbl file. 
** 	2.c Search the alias file for platform charset.
** 3. If still not found then find the II_CHARSETxx value
**    for ingres installation and search the alias file for 
**    this value. 
** 4. If none of these attempts succeed then return default 
**    with a warning to the errorlog if this happens 
** 
** Input:
**	converter -	Place holder for the output string, 
**			It is assumed that the area is at least MAX_LOC
**			chars in size.
** Output:
**	converter -	Pointer to string where the output
**			converter name is stored.
** History:
**
**	22-jan-2004 (gupsh01)
**	    Added.
**	14-Jun-2004 (schka24)
**	    Safe charset name handling.
*/
STATUS
adu_getconverter(
    char	*converter)
{
    STATUS		stat;
    char		*tptr;
    char		*env = 0;
    char		chset[CM_MAXATTRNAME+1];
    char		pcs[CM_MAXLOCALE+1]; /* platform character set */
    char		norm_pcs[CM_MAXLOCALE+1];
    CL_ERR_DESC         syserr;
    char                *alias_buffer = NULL;
    char                *bufptr = NULL;
    char                *buf = NULL;
    ADU_ALIAS_MAPPING   *aliasmapping;
    ADU_ALIAS_DATA	*aliasdata;	
    char 		*datasize;
    SIZE_TYPE		filesize = 0;
    SIZE_TYPE		sizemap = 0;
    SIZE_TYPE		sizedata = 0;
    i4			bytes_read;
    char		*abufptr;
    i4			i = 0;
    i4			index = 0;


/* STEP 1 */
    NMgtAt(ERx("II_UNICODE_CONVERTER"), &env);
    if (env && *env)
    {
        STlcopy(env, converter, MAX_LOC-1);
	return OK;
    }

/* STEP 2 */
    stat = CM_getcharset(pcs);
    
    if (CMopen_col("aliasmaptbl", &syserr, CM_UCHARMAPS_LOC) != OK)
    {
      /* return an ERROR if we are unable to open the file */
      return FAIL;
    }

    /* initialize buf to help read from the aliasmaptbl file */
    buf = MEreqmem(0, COL_BLOCK, TRUE, &stat);
    if (buf == NULL || stat != OK)
    {
       CMclose_col(&syserr, CM_UCHARMAPS_LOC);
       return (FAIL);
    }

    /* First file buffer has size information. */
    stat = CMread_col(buf, &syserr);
    if (stat != OK)
    {
        MEfree((char *)buf);
        CMclose_col(&syserr, CM_UCHARMAPS_LOC);
       return (FAIL);
    }

    tptr = buf;
    bytes_read = COL_BLOCK;

    /* filesize is the first entry of the map file */
    filesize = *(SIZE_TYPE *) buf;
    tptr += sizeof(SIZE_TYPE);
    tptr = ME_ALIGN_MACRO(tptr, sizeof(PTR));

    /* allocate working space for the data */
    alias_buffer = (char *)MEreqmem(0, filesize, TRUE, &stat);
    if (alias_buffer == NULL || stat != OK)
    {
       CMclose_col(&syserr, CM_UCHARMAPS_LOC);
       return (FAIL);
    }
    abufptr = alias_buffer;
    MEcopy (buf, COL_BLOCK, abufptr);
    abufptr += COL_BLOCK;

    /* Read the file till it is read completely */
    for ( ;bytes_read < filesize;)
    {
        stat = CMread_col(buf, &syserr);
        if (stat != OK)
        {
          MEfree((char *)buf);
          MEfree((char *)alias_buffer);
          CMclose_col(&syserr, CM_UCHARMAPS_LOC);
          return (FAIL);
	}
	bytes_read += COL_BLOCK;
        MEcopy (buf, COL_BLOCK, abufptr);
        abufptr += COL_BLOCK;
    }

    if (bytes_read < filesize)
    {
      /* we had to exit for some unknown reason */
      MEfree((char *)buf);
      MEfree((char *)alias_buffer);
      CMclose_col(&syserr, CM_UCHARMAPS_LOC);
      return (FAIL);
    }
    tptr = alias_buffer;
    tptr += sizeof(SIZE_TYPE);
    tptr = ME_ALIGN_MACRO(tptr, sizeof(PTR));

    /* Read the size of the MappingArray nodes */
    sizemap = *(SIZE_TYPE *) tptr;
    tptr += sizeof(SIZE_TYPE);
    tptr = ME_ALIGN_MACRO(tptr, sizeof(PTR));

    /* initialize buffer for ADU_ALIAS_MAPPING buffer */
    aliasmapping = (ADU_ALIAS_MAPPING *) MEreqmem(0, sizemap, TRUE, &stat);
    if (aliasmapping == NULL)
    {
      MEfree((char *)buf);
      MEfree((char *)alias_buffer);
      CMclose_col(&syserr, CM_UCHARMAPS_LOC);
      return (FAIL);
    }

    /* Copy data for ADU_ALIAS_MAPPING array */
    MEcopy(tptr, sizemap, aliasmapping);
    tptr += sizemap;
    tptr = ME_ALIGN_MACRO(tptr, sizeof(PTR));

    /* Get size for the aliasdata */
    sizedata = *(SIZE_TYPE *) tptr;
    tptr += sizeof(SIZE_TYPE);
    tptr = ME_ALIGN_MACRO(tptr, sizeof(PTR));

     /* Initialize buffer for ADU_ALIAS_MAPPING buffer */
    aliasdata = (ADU_ALIAS_DATA *) MEreqmem(0, sizedata, TRUE, &stat);
    if (aliasdata == NULL)
    {
      MEfree((char *)buf);
      MEfree((char *)alias_buffer);
      MEfree((char *)aliasmapping);
      CMclose_col(&syserr, CM_UCHARMAPS_LOC);
      return (FAIL);
    }

    /* Copy the ADU_ALIAS_DATA array */
    MEcopy(tptr, sizedata, aliasdata);
    tptr += sizedata;
    tptr = ME_ALIGN_MACRO(tptr, sizeof(PTR));

    /* Close the "aliasmaptbl" file */
    CMclose_col(&syserr, CM_UCHARMAPS_LOC);

    /* Normalize pcs */

    adu_csnormalize (pcs, STlength(pcs), norm_pcs);

    /* Retrieve the pcs value */
    for (i=0; i < sizedata/sizeof(ADU_ALIAS_DATA); i++)
    {
      if ((STcompare (aliasdata[i].aliasNameNorm, norm_pcs)) == 0)
      {
	index = aliasdata[i].aliasMapId; 
	/* found */
	STcopy (aliasmapping[index].mapping_id, 
		  converter);

        /* cleanup */
        MEfree((char *)buf);
        MEfree((char *)alias_buffer);
        MEfree((char *)aliasmapping);
        MEfree((char *)aliasdata);

        return (OK);
      } 
    }

/* STEP 3 */
    /* Obtain Ingres characterset */
    STcopy("default", converter);
    CMget_charset_name(&chset[0]);
    if (STcasecmp(chset, "UTF8") != 0)
    { 
	    /* search maptable for env  */ 
	for (i=0; i < sizedata/sizeof(ADU_ALIAS_DATA); i++)
	{
	    if ((STcompare (aliasdata[i].aliasNameNorm, norm_pcs)) == 0)
	    {
		index = aliasdata[i].aliasMapId; 
		/* found */
		STcopy (aliasmapping[index].mapping_id, converter);
		break;
	    }
	}
    }

    /* cleanup */
    MEfree((char *)buf);
    MEfree((char *)alias_buffer);
    MEfree((char *)aliasmapping);
    MEfree((char *)aliasdata);

    /* FIXME warning or error if still "default" ? */

    return (OK);
}
Example #21
0
STATUS
ERsend(i4 flag, char *message, i4 msg_length, CL_ERR_DESC *err_code)
{
# ifdef NT_GENERIC
    static bool		er_init = FALSE;
    static bool		is_w95 = FALSE;
# else /* !NT_GENERIC */
    static int		er_ifi = -2;
    static int          ar_ifi = -2;
# endif /* !NT_GENERIC */
    STATUS		status;
    char                tmp_buf[ER_MAX_LEN];
    char*               logmsg = message;

    /*	Check for bad paramters. */

    CL_CLEAR_ERR( err_code );

    if ((message == 0 || msg_length == 0) && flag != ER_AUDIT_MSG)
        return (ER_BADPARAM);

    if ((flag != ER_ERROR_MSG) && (flag != ER_AUDIT_MSG) &&
        ( flag != ER_OPER_MSG))
        return (ER_BADPARAM);

# ifndef NT_GENERIC
    if (flag & ER_AUDIT_MSG)
    {
        key_t msg_key;
        char  *ipc_number;
        struct
        {
            long    mtype;
            char    mtext[ER_MAX_LEN];
        }   msg;

        if (ar_ifi == -2)
        {
            NMgtAt("II_AUDIT_IPC", &ipc_number);
            if (ipc_number && ipc_number[0])
            {
                CVal(ipc_number, &msg_key);
                ar_ifi = msgget(msg_key, 0);
                if (ar_ifi == -1)
                {
                    SETCLERR(err_code, 0, ER_open);
                    return(ER_NO_AUDIT);
                }
            }
            else
            {
                SETCLERR(err_code, 0, ER_open);
                return(ER_NO_AUDIT);
            }

        }
 
        /*  Handle special case to connect only but not send message. */
 
        if (msg_length == 0 && message == 0)
                return (OK);

        MEcopy(message, msg_length, msg.mtext);
        msg.mtype = 1;
        if (msgsnd(ar_ifi, &msg, msg_length, 0))
        {
            SETCLERR(err_code, 0, ER_open);
            return(ER_BADSEND);
        }
        return (OK);
    }
    else
# endif /* ! NT_GENERIC */
    if (flag & ER_OPER_MSG)
    {
        char    hostname[GL_MAXNAME];
        STATUS  status;
 
        message[msg_length] = EOS;
        TRdisplay("ER Operator:\"%s\"\n",message);
	if (!ERsysinit)
	    ERinitsyslog();
# ifdef NT_GENERIC
        {
        wchar_t *wmessage = NULL;

        /*
        ** Update the ReportEvent to report information in the event log.
        */
        if ( ReportEvent( EventLog,
                        (WORD) EVENTLOG_INFORMATION_TYPE,
                        (WORD) 0,             /* event category */
                        (DWORD) I_ING_INFO,   /* event identifier */
                        (PSID) NULL,
                        (WORD) 1,             /* number of strings */
                        (DWORD) 0,
                        &message,
                        NULL ) == FALSE)   
                status = GetLastError();
	if ( !er_init )
	{
	    char		VersionString[256];
	    FUNC_EXTERN BOOL	GVosvers(char *OSVersionString);

	    GVosvers(VersionString);
	    is_w95 = ( STstrindex(VersionString, "Microsoft Windows 9",
				  0, FALSE) != NULL ) ? TRUE : FALSE;

	    if ( !is_w95 ) /* netapi32 only on NT */
	    {
		HANDLE hDll;
                if ((hDll = LoadLibrary(TEXT("netapi32.dll"))) != NULL)
                {
                    pNetMessageNameAdd = 
		     (NET_API_STATUS (*)(LPCWSTR,LPCWSTR))
		     GetProcAddress(hDll, TEXT("NetMessageNameAdd"));
                    pNetMessageNameDel = 
		     (NET_API_STATUS (*)(LPCWSTR,LPCWSTR))
		     GetProcAddress(hDll, TEXT("NetMessageNameDel"));
                    pNetMessageBufferSend = 
		      (NET_API_STATUS (*)(LPCWSTR,LPCWSTR,LPCWSTR,LPBYTE,DWORD))
		      GetProcAddress(hDll, TEXT("NetMessageBufferSend"));
		}
		/* if any problem, pretend we don't support it */
		if ( pNetMessageNameAdd == NULL ||
		     pNetMessageNameDel == NULL ||
		     pNetMessageBufferSend == NULL )
		    is_w95 = TRUE;
	    }
	}

	if ( !is_w95 )
	{
	    /*
	    ** Now, send the message to the server console,
	    ** putting up a message box (if the messenger service
	    ** is running.  Everything must be in Unicode.
	    */

	    if ( whostname[0] == 0 )
	    {
		unsigned int len = sizeof(hostname);
                /* 
		** get the hostname in Unicode format for use 
		** by messenger service 
		*/
                GetComputerName( (char *)hostname, &len );
		MultiByteToWideChar( GetACP(), 0,
				     hostname, sizeof(hostname),
				     whostname, sizeof(whostname) );
	    }
            /* initialize the messenger service */
            status = (*pNetMessageNameAdd)( whostname, msgname );
            if ( status != NERR_Success )
	        status = GetLastError();

	    /* Allocate a buffer for the Unicode */
	    wmessage = (wchar_t *) MEreqmem( 0, msg_length * sizeof(wchar_t), 
				             TRUE, &status );
	    if ( wmessage )
	    {
	        /* copy the message to the Unicode buffer */
		MultiByteToWideChar( GetACP(), 0,
				     message, msg_length,
				     wmessage, msg_length * sizeof(wchar_t) );
                status = (*pNetMessageBufferSend)( whostname, 
					       msgname, 
					       NULL, 
				               (LPBYTE) wmessage, 
					       msg_length*sizeof(wchar_t) );
                if ( status != NERR_Success )
	            status = GetLastError();
	        MEfree( (PTR)wmessage );
	    }

            /* re-initialize the messenger service */
            status = (*pNetMessageNameDel)( whostname, msgname );
            if ( status != NERR_Success )
	        status = GetLastError();

	}
	}
# elif defined(OS_THREADS_USED) && defined(any_aix)
	syslog_r( LOG_ALERT|LOG_ERR, message );
# else
	syslog( LOG_ALERT|LOG_ERR, message );
# endif /* NT_GENERIC */
    }

    if (flag & ER_OPER_MSG)
    {
        i4 msglen = 0;
	char* host = PMhost();

        MEfill( ER_MAX_LEN, 0, tmp_buf );

        /*
        ** Format the message string for the event log.  As the source is
        ** not known a fixed string of INGSYSLOG is used.
        */
        TRformat( NULL, 0, tmp_buf, ER_MAX_LEN - 1,
            "%8.8t::[INGSYSLOG         , 00000000]: %@ ", STlength(host),
            host );
        msglen = STlength(tmp_buf);
        STcat( tmp_buf, message );  /* append original message */
        msg_length += msglen;
        logmsg = tmp_buf;
    }
    status = ERlog( logmsg, msg_length, err_code );
    return( status );
}
Example #22
0
int
main( int argc, char **argv )
{
    CL_ERR_DESC err;
    PTR handle;
    PTR handle1;
    PTR handle2;
    PTR addr;
    STATUS status;
    int (*int_fcn)();
    char *(*str_fcn)();
    int int_ret;
    char *cp_ret;
    LOCATION srcfile;
    char srcbuf[MAX_LOC+1];
    LOCATION objfile;
    char objbuf[MAX_LOC+1];
    bool pristine;
    LOCATION modloc;
    char modbuf[MAX_LOC+1];
    LOCATION dlloc;
    char dlbuf[MAX_LOC+1];
    LOCATION errloc;
    char errbuf[MAX_LOC+1];
    LOCATION nameloc;
    char namebuf[MAX_LOC+1];
    char *nameptr;
    char *parms[2];
    i4  flags;
    STATUS mod2status = OK;
    
    /* find the working directory */
    NMgtAt( "IIDLDIR", &cp_ret );
    if ( cp_ret == NULL || *cp_ret == EOS )
    {
	SIprintf( "%sDLDIR not set\n", SystemVarPrefix );
	PCexit( 1 );
    }

    /* save the directory name into a larger buffer for LO */
    STcopy( cp_ret, srcbuf );

    /* initialize a LOCATION with the directory */
    LOfroms( PATH, srcbuf, &srcfile );

    /* initialize the object file LOCATION with same directory */
    LOcopy( &srcfile, objbuf, &objfile );
    LOcopy( &srcfile, modbuf, &modloc );
    LOcopy( &srcfile, dlbuf, &dlloc );
    LOcopy( &srcfile, errbuf, &errloc );
    
    /* add filenames to LOCATION */
    LOfstfile( srcs[0], &srcfile );
    LOfstfile( objs[0], &objfile );
    LOfstfile( erroutput, &errloc );
    
    /* compile with error */
#ifdef NT_GENERIC
    parms[0] = "-g";
#else NT_GENERIC
    parms[0] = "-Zi";
#endif NT_GENERIC
    parms[1] = NULL;
    status = UTcompile_ex( &srcfile, &objfile, &errloc, parms, FALSE, &pristine, &err );
    if ( status != OK )
    {
        SIprintf( "Compile error test returns: " );
        if ( status == UT_CO_FILE )
            SIprintf( 
		"\n  utcom.def file not found or II_COMPILE_DEF not set\n" );
        else if ( status == UT_CO_IN_NOT )
            SIprintf( "source file not found.\n" );
        else
            SIprintf( "%d\n", status );
        SIprintf( "Contents of error file:\n" );
        SIprintf( "------------------------------------------------------\n" );
        SIcat( &errloc, stdout );
        SIprintf( "------------------------------------------------------\n" );
        SIprintf( "\n" );
    }
    else
    {
        SIprintf( "Test of compile error returned OK.\n" );
        SIprintf( "Contents of error file:\n" );
        SIprintf( "------------------------------------------------------\n" );
        SIcat( &errloc, stdout );
        SIprintf( "------------------------------------------------------\n" );
        SIprintf( "\n" );
    }

    /* add filenames to LOCATION */
    LOfstfile( srcs[0], &srcfile );
    LOfstfile( objs[0], &objfile );

    /* do a good compile */
#ifdef NT_GENERIC
    parms[0] = "-Zi";
#else NT_GENERIC
    parms[0] = "-g";
#endif NT_GENERIC
    status = UTcompile_ex( &srcfile, &objfile, NULL, parms, FALSE, &pristine, &err );
    if ( status != OK )
    {
	SIprintf( "Error compiling module: %d\n", status );
	PCexit( 1 );
    }

    LOfstfile( srcs1[0], &srcfile );
    LOfstfile( objs1[0], &objfile );

    status = UTcompile( &srcfile, &objfile, NULL, &pristine, &err );
    if ( status != OK )
    {
	SIprintf( "Error compiling module1\n" );
	PCexit( 1 );
    }

    LOfstfile( srcs2[0], &srcfile );
    LOfstfile( objs2[0], &objfile );

    mod2status = UTcompile( &srcfile, &objfile, NULL, &pristine, &err );
    if ( mod2status != OK )
    {
	SIprintf( "Error compiling module2\n" );
	SIprintf( "This is not an error if C++ is not installed.\n" );
	SIprintf( "Skipping further processing of this module\n\n" );
    }

    /* link first module into shared library */
    if ( DLcreate( NULL, NULL, module, objs, NULL, lookups, &err) != OK )
    {
	SIprintf( "Error creating module\n" );
	PCexit( 1 );
    }

    if ( DLcreate_loc( NULL, NULL, module1, objs1, NULL, lookups1, 
		       &dlloc, NULL, &errloc, FALSE, NULL, &err) != OK )
    {
	SIprintf( "Error creating module1\n" );
	PCexit( 1 );
    }
    SIprintf( "Contents of DLcreate_loc() error file for module1:\n" );
    SIprintf( "------------------------------------------------------\n" );
    SIcat( &errloc, stdout );
    SIprintf( "------------------------------------------------------\n" );
    SIprintf( "\n" );

    if ( mod2status == OK )
    {
        if ( DLcreate_loc( NULL, NULL, module2, objs2, NULL, lookups2, 
		           &dlloc, NULL, &errloc, FALSE, "C++", &err) != OK )
        {
	    SIprintf( "Error creating module2\n" );
	    PCexit( 1 );
        }
        SIprintf( "Contents of DLcreate_loc() error file for module2:\n" );
        SIprintf( "------------------------------------------------------\n" );
        SIcat( &errloc, stdout );
        SIprintf( "------------------------------------------------------\n" );
        SIprintf( "\n" );
    }

    STcopy( module1, namebuf );
    LOfroms( FILENAME, namebuf, &nameloc );
    DLconstructloc( &nameloc, namebuf, &nameloc, &err );
    LOtos( &nameloc, &nameptr );
    SIprintf( "Full path for %s is \"%s\"\n", module1, nameptr );

    LOcopy( &dlloc, namebuf, &nameloc );
    LOfstfile( module, &nameloc );
    DLconstructloc( &nameloc, namebuf, &nameloc, &err);
    LOtos( &nameloc, &nameptr );
    SIprintf( "Full path for %s is \"%s\"\n", module, nameptr );

    /* test an error */
    SIprintf( "Testing DLprepare of non-existant module.\n" );
    if ( DLprepare((char *)NULL, "XXX", lookups, &handle, &err) == OK )
    {
	SIprintf( "Error:  returned success, should be failure.\n" );
	PCexit( 1 );
    }

    /* load the modules into the executable */
    SIprintf( "Now loading the real modules.\n" );
    if ( DLprepare((char *)NULL, module, lookups, &handle, &err) != OK )
    {
	SIprintf( "Error loading module\n" );
	PCexit( 1 );
    }
    if ( mod2status == OK &&
         DLprepare((char *)NULL, module2, lookups2, &handle2, &err) != OK )
    {
	SIprintf( "Error loading module2\n" );
	PCexit( 1 );
    }
    putenv( "IIDLDIR=XXX" );
    flags=0;
    if ( DLprepare_loc((char *)NULL, module1, lookups1, &dlloc, flags,
                       &handle1, &err) != OK )
    {
	SIprintf( "Error loading module1\n" );
	PCexit( 1 );
    }

    /* get the address of a function and test it */
    if ( DLbind(handle1, "returns_onehundred", &addr, &err) != OK )
    {
	/* "returns_onehundred" function isn't there */
	DLunload( handle, &err );
	PCexit( 1 );
    }
    int_fcn = (int (*)()) addr;
    int_ret = (*int_fcn)();
    SIprintf( "\"returns_onehundred\" returns %d\n", int_ret );
    if ( int_ret != 100 )
    {
	/* function didn't correctly return 100 */
	PCexit( 1 );
    }

    if ( mod2status == OK )
    {
        if ( DLbind(handle2, "returns_ninetynine", &addr, &err) != OK )
        {
	    SIprintf( "Error binding \"returns_ninetynine\"\n" );

	    /* "returns_ninetynine" function isn't there */
	    DLunload( handle2, &err );
	    PCexit( 1 );
        }
        int_fcn = (int (*)()) addr;
        int_ret = (*int_fcn)();
        SIprintf( "\"returns_ninetynine\" returns %d\n", int_ret );
        if ( int_ret != 99 )
        {
	    /* function didn't correctly return 99 */
	    PCexit( 1 );
        }
    }

    if ( DLbind(handle, "returns_one", &addr, &err) != OK )
    {
	/* "returns_one" function isn't there */
	DLunload( handle, &err );
	PCexit( 1 );
    }
    int_fcn = (int (*)()) addr;
    int_ret = (*int_fcn)();
    SIprintf( "\"returns_one\" returns %d\n", int_ret );
    if ( int_ret != 1 )
    {
	/* function didn't correctly return 1 */
	PCexit( 1 );
    }

    if ( DLbind(handle, "returns_zero", &addr, &err) != OK )
    {
	/* "returns_zero" function isn't there */
	DLunload( handle, &err );
	PCexit( 1 );
    }
    int_fcn = (int (*)()) addr;
    int_ret = (*int_fcn)();
    SIprintf( "\"returns_zero\" returns %d\n", int_ret );
    if ( int_ret != 0 )
    {
	/* function didn't correctly return 0 */
	PCexit( 1 );
    }

    if ( DLbind(handle, "returns_minus_one", &addr, &err) != OK )
    {
	/* "returns_minus_one" function isn't there */
	DLunload( handle, &err );
	PCexit( 1 );
    }
    int_fcn = (int (*)()) addr;
    int_ret = (*int_fcn)();
    SIprintf( "\"returns_minus_one\" returns %d\n", int_ret );
    if ( int_ret != -1 )
    {
	/* function didn't correctly return -1 */
	PCexit( 1 );
    }

    if ( DLbind(handle, "returns_string", &addr, &err) != OK )
    {
	/* "returns_string" function isn't there */
	DLunload( handle, &err );
	PCexit( 1 );
    }
    str_fcn = (char *(*)()) addr;
    cp_ret = (*str_fcn)();
    SIprintf( "\"returns_string\" returns \"%s\"\n", cp_ret );
    if ( STcompare(cp_ret, "String") != OK )
    {
	/* function didn't correctly return "String" */
	PCexit( 1 );
    }

    /* functions were called successfully, now unload the modules */
    if ( DLunload( handle, &err ) != OK )
    {
	SIprintf( "Error unloading module.\n" );
	PCexit( 1 );
    }
    if ( DLunload( handle1, &err ) != OK )
    {
	SIprintf( "Error unloading module.\n" );
	PCexit( 1 );
    }
    if ( mod2status == OK && 
         DLunload( handle2, &err ) != OK )
    {
	SIprintf( "Error unloading module2.\n" );
	PCexit( 1 );
    }

    if ( DLdelete_loc( module1, &dlloc, &err ) != OK )
    {
	SIprintf( "Error deleting module1.\n" );
	PCexit( 1 );
    }

    SIprintf( "Successfully executed.\n" );
    PCexit( 0 );
}
Example #23
0
static STATUS
initialize( i4 argc, char **argv )
{
    CL_ERR_DESC	cl_err;
    char	*instance = ERx("*");
    char	*env;
    char	name[ 16 ];
    i4		i;

    GCD_global.language = 1;
    MHsrand( TMsecs() );

    for( i = 1; i < argc; i++ )
	if ( ! STbcompare( argv[i], 0, ERx("-instance"), 9, TRUE ) )
	{
	    if ( argv[i][9] == ERx('=')  &&  argv[i][10] != EOS )
		instance = &argv[i][10];
	    else  if ( argv[i][9] == EOS  &&  (i + 1) < argc )
		instance = argv[++i];
	    break;
	}

    NMgtAt( ERx("II_INSTALLATION"), &env );
    STprintf( name, ERx("II_CHARSET%s"), (env  &&  *env) ? env : "" );
    NMgtAt( name, &env );

    if ( ! env  ||  ! *env || STlength(env) > CM_MAXATTRNAME)
    {
	switch( CMgetDefCS() )
	{
#if ( !defined(UNIX) && !defined(VMS) )
	case CM_IBM :	    env = "IBMPC850";	break;
#endif
	case CM_DECMULTI :  env = "DECMULTI";	break;
	default :	    env = "ISO88591";	break;
	}
    }

    GCD_global.charset = STalloc( env );
    CVupper( GCD_global.charset );
    gcu_read_cset( gcd_cset_id );

    if ( CMset_attr( GCD_global.charset, &cl_err) != OK )
    {
	gcu_erlog( 0, GCD_global.language, 
		    E_GC0105_GCN_CHAR_INIT, NULL, 0, NULL );
	return( E_GC0105_GCN_CHAR_INIT );
    }

    PMinit();

    switch( PMload( (LOCATION *)NULL, (PM_ERR_FUNC *)NULL ) )
    {
	case OK: break;

	case PM_FILE_BAD:
	    gcu_erlog( 0, GCD_global.language, 
			E_GC003D_BAD_PMFILE, NULL, 0, NULL );
	    return( E_GC003D_BAD_PMFILE );
	    break;

	default:
	    gcu_erlog( 0, GCD_global.language, 
			E_GC003E_PMLOAD_ERR, NULL, 0, NULL );
	    return( E_GC003E_PMLOAD_ERR );
	    break;
    }

    PMsetDefault( 0, SystemCfgPrefix );
    PMsetDefault( 1, PMhost() );
    PMsetDefault( 2, ERx("gcd") );
    PMsetDefault( 3, instance );

    gcd_tl_services[0] = &gcd_dmtl_service;
    gcd_tl_services[1] = &gcd_jctl_service;
    GCD_global.tl_services = gcd_tl_services;
    GCD_global.tl_srvc_cnt = ARR_SIZE( gcd_tl_services );

    QUinit( &GCD_global.pib_q );
    QUinit( &GCD_global.rcb_q );
    QUinit( &GCD_global.ccb_q );
    QUinit( &GCD_global.ccb_free );
    for( i = 0; i < ARR_SIZE( GCD_global.cib_free ); i++ )  
	QUinit( &GCD_global.cib_free[ i ] );

    env = NULL;
    gcu_get_tracesym( NULL, ERx("!.client_max"), &env );
    if ( env  &&  *env )
    {
	i4 count;

	if ( CVal( env, &count ) == OK  &&  count > 0 )
	    GCD_global.client_max = count;
    }

    env = NULL;
    gcu_get_tracesym( NULL, ERx("!.client_timeout"), &env );
    if ( env  &&  *env )  
    {
	i4 timeout;

	if ( CVal( env, &timeout ) == OK  &&  timeout > 0 )
	    GCD_global.client_idle_limit = timeout * 60; /* Cnvt to seconds */
    }

    env = NULL;
    gcu_get_tracesym( NULL, ERx("!.connect_pool_status"), &env );
    if ( env  &&  *env )
    {
	if ( ! STbcompare( env, 0, "optional", 0, TRUE ) )
	    GCD_global.client_pooling = TRUE;

	if ( GCD_global.client_pooling  ||
	     ! STbcompare( env, 0, "on", 0, TRUE ) )
	{
	    env = NULL;
	    gcu_get_tracesym( NULL, ERx("!.connect_pool_size"), &env );
	    if ( env  &&  *env )  CVal( env, &GCD_global.pool_max );

	    env = NULL;
	    gcu_get_tracesym( NULL, ERx("!.connect_pool_expire"), &env );
	    if ( env  &&  *env )  
	    {
		i4 limit;

		if ( CVal( env, &limit ) == OK  &&  limit > 0 )
		    GCD_global.pool_idle_limit = limit * 60; /* Seconds */
	    }
	}
    }

    env = NULL;
    gcu_get_tracesym( "II_GCD_TRACE", ERx("!.gcd_trace_level"), &env );
    if ( env  &&  *env )  CVal( env, &GCD_global.gcd_trace_level );

    env = NULL;
    gcu_get_tracesym( "II_GCD_LOG", ERx("!.gcd_trace_log"), &env );
    if ( env  &&  *env ) 
	TRset_file( TR_F_OPEN, env, (i4)STlength( env ), &cl_err );

    return( OK );
}
Example #24
0
/*
** Name: PCexec_suid - Execute a command as the ingres user.
**
** Description:
**	This procedure works with the Ingres service to run the given
**	command as the ingres user. It mimicks the "setuid" bit in UNIX.
**
** Inputs:
**	cmdbuf - command to execute as the ingres user
**
** Outputs:
**	none
**
** Returns:
**	OK
**	FAIL
**
** Side Effects:
**	none
**
** History:
**	08-jan-1998 (somsa01)
**	    Created.
**	19-feb-1998 (somsa01)
**	    We need to pass to the service the current working directory
**	    as well.  (Bug #89006)
**	25-feb-1998 (somsa01)
**	    We now have an input file for the process' stdin which
**	    runs through the OpenIngres service.
**	19-jun-1998 (somsa01)
**	    Use SYSTEM_PRODUCT_NAME for the name of the service.
**	10-jul-1998 (kitch01)
**		Bug 91362. If user is 'system' run through OpenIngres service
**		despite having access to server shared memory 'system' does not
**		have required privilege to access semaphores/mutexes.
**	11-jun-1999 (somsa01)
**	    If the command is a startup command, then it is always run through
**	    the Ingres service.
**	03-nov-1999 (somsa01)
**	    A failure from ControlService() should be treated as a severe
**	    error which should not let us continue.
** 	22-jan-2000 (somsa01)
**	    Return the exit code of the spawned process. Also, if the
**	    files exist, truncate them. The service name is now keyed off
**	    of II_INSTALLATION.
**	05-jun-2000 (somsa01)
**	    The Ingres installation may be started as the SYSTEM account,
**	    in which the 'ingres' user will not automatically have access
**	    to the shared memory segments. Therefore, even if the real
**	    user is 'ingres', check to see if he has access.
**	24-oct-2000 (somsa01)
**	    Removed the check on shared memory access. Access to the shared
**	    memory segment does not necessarily mean that the user running
**	    the process does not need to run the specified process as the
**	    Ingres owner. Also, generalized the check of the user with
**	    IDname_service().
**	18-dec-2000 (somsa01)
**	    Modified the cases to run the command "as is" without the Ingres
**	    service.
**	20-mar-2002 (somsa01)
**	    If all is well, return the exit code of the child process that
**	    was executed.
**	29-mar-2002 (somsa01)
**	    Properly return the child process exit code.
**	11-apr-2003 (somsa01)
**	    While waiting for "pending" to not be set, give some CPU back
**	    to the OS.
**      29-Jul-2005 (drivi01)
**	    Allow user to run the command if he/she owns a shared
**	    segment and ingres is not running as a service.
**	06-Dec-2006 (drivi01)
**	    Adding support for Vista, Vista requires "Global\" prefix for
**	    shared objects as well.  Replacing calls to GVosvers with 
**	    GVshobj which returns the prefix to shared objects.
**	    Added PCadjust_SeDebugPrivilege to allow quering of 
**	    System processes.
**	25-Jul-2007 (drivi01)
**		On Vista, PCexec_suid is unable to use SE_DEBUG Privilege
**	    to query process status and retireve its exit code.
**		The routine for monitoring a process and retrieving 
**	    its exit code has been moved to Ingres Service.
**	05-Nov-2009 (wanfr01) b122847
**	    Don't do a PCsleep unless you are waiting for more input
*/
STATUS
PCexec_suid(char *cmdbuf)
{
    EX_CONTEXT		context;
    SERVICE_STATUS	ssServiceStatus;
    LPSERVICE_STATUS	lpssServiceStatus = &ssServiceStatus;
    struct SETUID	setuid;
    DWORD		ProcID;
    HANDLE		SaveStdout;
    SECURITY_ATTRIBUTES	sa;
    CHAR		szRealUserID[25] = "";
    CHAR		*pszRealUserID = szRealUserID;
    CHAR		szServiceUserID[25] = "";
    CHAR		*pszServiceUserID = szServiceUserID;
    DWORD		BytesWritten, BytesRead = 0;
    CHAR		*inst_id;
    CHAR		SetuidShmName[64];
    CHAR		*temp_loc;
    CHAR		InBuf[256], OutBuf[256];
    static CHAR		SetuidPipeName[32];
    CL_ERR_DESC		err_code;
    CHAR		ServiceName[255];
    DWORD		ExitCode = 0;
    CHAR		tchII_INSTALLATION[3];
    BOOL		SetuidDbCmd = FALSE, ServiceCommand = FALSE;
    int			i, cmdlen;
    char		*ObjectPrefix;
	u_i4		drType;
    SC_HANDLE		schSCManager, OpIngSvcHandle;
    BOOL		bServiceStarted = FALSE;

    if (EXdeclare(ex_handler, &context) != OK)
    {
	EXdelete();
	PCexit(FAIL);
    }
    NMgtAt("II_INSTALLATION", &inst_id);
    STcopy(inst_id, tchII_INSTALLATION);

    /*
    ** See if this is a command that MUST be run through the Ingres
    ** service.
    */
    cmdlen = (i4)STlength(cmdbuf);
    for (i = 0; ServiceCommands[i] ; i++)
    {
	if (STbcompare( cmdbuf, cmdlen, ServiceCommands[i],
			(i4)STlength(ServiceCommands[i]), FALSE ) == 0)
	{
	    ServiceCommand = TRUE;
	    break;
	}
    }

    /*
    ** If the user is the same as the user who started the Ingres
    ** service, just spawn the command.
    */
    if (!ServiceCommand)
    {
	IDname(&pszRealUserID);
	if (!IDname_service(&pszServiceUserID) &&
	    STcompare(pszServiceUserID, pszRealUserID) == 0 && 
		PCisAdmin())
	{
	    /*
	    ** Attempt to just execute the command.
	    */
	    return( PCcmdline( (LOCATION *) NULL, cmdbuf, PC_WAIT,
		    (LOCATION *) NULL, &err_code) );
	}
	else
	{
	    /*
	    ** If current user is not the same as service user and ingres is not
	    ** running as a service, check if shared memory segment is owned
	    ** by current user, if user has access to shared segment allow him
	    ** to run the command.
	    */
	    PTR	shmem;
	    SIZE_TYPE	allocated_pages=0;
	    STATUS status;

	    if((status = MEget_pages(ME_MSHARED_MASK, 1, "lglkdata.mem",
	                 &shmem, &allocated_pages, &err_code)) == OK)
	    {
	        STprintf(ServiceName, "%s_Database_%s", SYSTEM_SERVICE_NAME, 
		tchII_INSTALLATION);
	        if ((schSCManager = OpenSCManager(NULL, NULL, 
					SC_MANAGER_CONNECT)) != NULL)
	        {
		    if ((OpIngSvcHandle = OpenService(schSCManager, ServiceName,
					SERVICE_QUERY_STATUS)) != NULL)
		    {
		       if (QueryServiceStatus(OpIngSvcHandle,lpssServiceStatus))
		       {
		    	if (ssServiceStatus.dwCurrentState != SERVICE_STOPPED)
			     bServiceStarted = TRUE;
		        }
		    }
	        }	
	        if (!bServiceStarted)
		    return(PCcmdline( (LOCATION *) NULL, cmdbuf, PC_WAIT,
			(LOCATION *) NULL, &err_code) );
	    }

	}

	/*
	** See if this command is an Ingres command which needs to interact
	** with at least one database.
	*/
	for (i = 0; validSetuidDbCmds[i] ; i++)
	{
	    if (STbcompare( cmdbuf, cmdlen, validSetuidDbCmds[i],
			    (i4)STlength(validSetuidDbCmds[i]), FALSE ) == 0)
	    {
		SetuidDbCmd = TRUE;
		break;
	    }
	}

	/*
	** If the user has access to the Ingres shared memory segment,
	** just spawn the command provided that it is not in the
	** validSetuidDbCmds list.
	*/
	if (!SetuidDbCmd)
	{
	    PTR	shmem;
	    SIZE_TYPE	allocated_pages=0;
	    STATUS	status;

	    if (((status = MEget_pages(ME_MSHARED_MASK, 1, "lglkdata.mem",
		&shmem,
		&allocated_pages, &err_code)) == OK) ||
		(status == ME_NO_SUCH_SEGMENT))
	    {
		if (status != ME_NO_SUCH_SEGMENT)
		    MEfree_pages(shmem, allocated_pages, &err_code);
		
		return( PCcmdline( (LOCATION *) NULL, cmdbuf, PC_WAIT,
			(LOCATION *) NULL, &err_code) );
	    }
	}
    }

    /*
    ** We must run the command through the Ingres service.
    */

    if ( STstrindex(cmdbuf, "-silent", 0, FALSE ) )
	SilentMode = TRUE;

    iimksec(&sa);


	GVshobj(&ObjectPrefix);
	STprintf(SetuidShmName, "%s%sSetuidShm", ObjectPrefix, tchII_INSTALLATION);

    if ( (SetuidShmHandle = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE,
					    FALSE,
					    SetuidShmName)) == NULL )
    {
	error_exit(GetLastError());
	return(FAIL);
    }
    if ( (SetuidShmPtr = MapViewOfFile(SetuidShmHandle,
				       FILE_MAP_WRITE | FILE_MAP_READ,
				       0,
				       0,
				       sizeof(struct SETUID_SHM))) == NULL )
    {
	error_exit(GetLastError());
	return(FAIL);
    }

    /* Set up the information to send to the service. */
    STcopy(cmdbuf, setuid.cmdline);
    GetCurrentDirectory(sizeof(setuid.WorkingDirectory),
			setuid.WorkingDirectory);
	NMgtAt("II_TEMPORARY", &temp_loc);
	drType = GetDriveType(NULL);
	if (drType == DRIVE_REMOTE)
	{
		STcopy(temp_loc, setuid.WorkingDirectory);
	}
    SaveStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    CVla(GetCurrentProcessId(), setuid.ClientProcID);
    STprintf(SetuidPipeName, "\\\\.\\PIPE\\INGRES\\%s\\SETUID", inst_id);

    /* Set up the stdout file for the command. */
    STprintf(OutfileName, "%s\\%sstdout.tmp", temp_loc, setuid.ClientProcID);
    if ( (OutFile = CreateFile(OutfileName,
			       GENERIC_READ | GENERIC_WRITE,
			       FILE_SHARE_READ | FILE_SHARE_WRITE,
			       &sa,
			       CREATE_ALWAYS,
			       FILE_ATTRIBUTE_NORMAL,
			       NULL)) == INVALID_HANDLE_VALUE )
    {
	error_exit(GetLastError());
	return(FAIL);
    }

    /* Set up the stdin file for the command. */
    STprintf(InfileName, "%s\\%sstdin.tmp", temp_loc, setuid.ClientProcID);
    if ( (InFile = CreateFile(InfileName,
			      GENERIC_READ | GENERIC_WRITE,
			      FILE_SHARE_READ | FILE_SHARE_WRITE,
			      &sa,
			      CREATE_ALWAYS,
			      FILE_FLAG_WRITE_THROUGH,
			      NULL)) == INVALID_HANDLE_VALUE )
    {
	error_exit(GetLastError());
	return(FAIL);
    }

    /* Wait until the service is ready to process our request. */
    while (SetuidShmPtr->pending == TRUE)
	PCsleep(100);
    SetuidShmPtr->pending = TRUE;

    /* Trigger the "setuid" event of the service. */
    if ( (schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT)) == NULL)
    {
	error_exit(GetLastError());
	return(FAIL);
    }

    STprintf(ServiceName, "%s_Database_%s", SYSTEM_SERVICE_NAME,
	     tchII_INSTALLATION );
	OpIngSvcHandle = OpenService(schSCManager, ServiceName,
						SERVICE_USER_DEFINED_CONTROL);
	if (OpIngSvcHandle == NULL)
	{
		STprintf(ServiceName, "%s_DBATools_%s", SYSTEM_SERVICE_NAME,
	     tchII_INSTALLATION );
		OpIngSvcHandle = OpenService(schSCManager, ServiceName,
						SERVICE_USER_DEFINED_CONTROL);
	}
    if ( OpIngSvcHandle == NULL)
    {
	error_exit(GetLastError());
	return(FAIL);
    }
    if (!ControlService(OpIngSvcHandle, RUN_COMMAND_AS_INGRES,
			lpssServiceStatus))
    {
	error_exit(GetLastError());
	CloseServiceHandle(schSCManager);
	return(FAIL);
    }

    WaitNamedPipe(SetuidPipeName, NMPWAIT_WAIT_FOREVER);

    /* Send the information to the service. */
    if ( (Setuid_Handle = CreateFile(SetuidPipeName,
				     GENERIC_READ|GENERIC_WRITE,
				     FILE_SHARE_READ|FILE_SHARE_WRITE,
				     &sa,
				     OPEN_EXISTING,
				     FILE_ATTRIBUTE_NORMAL,
				     NULL)) == INVALID_HANDLE_VALUE )
    {
	error_exit(GetLastError());
	return(FAIL);
    }
    if (!WriteFile(Setuid_Handle, &setuid, sizeof(struct SETUID),
		   &BytesWritten, NULL))
    {
	error_exit(GetLastError());
	return(FAIL);
    }

    /*
    ** Retrieve information back from the service, and then
    ** disconnect from the pipe.
    */
    if (!ReadFile(Setuid_Handle, &setuid, sizeof(struct SETUID),
		  &BytesRead, NULL))
    {
	error_exit(GetLastError());
	return(FAIL);
    }

    ProcID = setuid.CreatedProcID;
    SetuidShmPtr->pending = FALSE;

    UnmapViewOfFile(SetuidShmPtr);
    SetuidShmPtr = NULL;
    CloseHandle(SetuidShmHandle);

    if ( (ProcID != -1) && (ProcID != -2) )
    {
	/*
	** Wait for the "spawned" process to exit, reading its output
	** from the stdout file.
	*/
	for (;;)
	{
	    if ( ((!ReadFile(OutFile, OutBuf, sizeof(OutBuf), &BytesRead, NULL)
		  || (BytesRead == 0)) && setuid.ExitCode != STILL_ACTIVE ))
		break;

	    if ( BytesRead &&
		 (!WriteFile(SaveStdout, OutBuf, BytesRead, &BytesWritten,
		  NULL)) && setuid.ExitCode != STILL_ACTIVE)
		break;
	    else if (BytesRead < sizeof(OutBuf))
		PCsleep(200);

	    /*
	    ** Currently, the only DBA program which can require
	    ** user input is verifydb. Therefore, when it spits out
	    ** the appropriate messages asking for user input, get
	    ** it from the end user and pass it along to the spawned
	    ** process.
	    */
	    if ( (STrstrindex(OutBuf, "S_DU04FF_CONTINUE_PROMPT", 0, FALSE)
			!= NULL) ||
		 (STrstrindex(OutBuf, "S_DU0300_PROMPT", 0, FALSE) != NULL) )
	    {
		SIflush(stdout);
		MEfill(sizeof(OutBuf), ' ', &OutBuf);
		MEfill(sizeof(InBuf), ' ', &InBuf);
		SIgetrec(InBuf, 255, 0);
		WriteFile(InFile, InBuf, sizeof(OutBuf), &BytesWritten, NULL);
	    }
	}

	ExitCode = setuid.ExitCode;
	CloseHandle(Setuid_Handle);
	CloseHandle(InFile);
	DeleteFile(InfileName);
	CloseHandle(OutFile);
	DeleteFile(OutfileName);
	CloseServiceHandle(OpIngSvcHandle);
	CloseServiceHandle(schSCManager);
        return(ExitCode);
    }
    else
    {
	error_exit(GetLastError());
	return(FAIL);
    }
}
Example #25
0
/*
** Name: sxapo_init_cnf - Initialize SXAPO configuration from the PM file.
**
** Description:
**	This routine initializes the SXAPO configuration from the
**	PM configuration file.
**
** Inputs:
**	None.
**
** Outputs:
**	err_code		Error code returned to caller.
**
** Returns:
**	DB_STATUS
**
** History:
**	6-jan-94 (stephenb)
**	    Initial creation.
*/
static DB_STATUS
sxapo_init_cnf(
	i4		*err_code)
{
    DB_STATUS		status = E_DB_OK;
    STATUS		clstat;
    i4		local_err;
    char		*pmfile;
    char		*pmvalue;

    *err_code = E_SX0000_OK;
    for (;;)
    {
    	/*
    	** Allow private override on PM file
    	*/
	NMgtAt("II_SXF_PMFILE", &pmfile);
	if (pmfile && *pmfile)
	{
		LOCATION	pmloc;
		TRdisplay("Loading SXF-PM file '%s'\n",pmfile);
		LOfroms(PATH & FILENAME, pmfile, &pmloc);
		if(PMload(&pmloc,NULL)!=OK)
		TRdisplay("Error loading PMfile '%s'\n",pmfile);
	}
	/*
	** Get auditing status
	*/
	if (PMget(SX_C2_MODE,&pmvalue) == OK)
	{
		if (!STbcompare(pmvalue, 0, SX_C2_MODE_ON, 0, TRUE))
		{
		    /*
		    ** Auditing on
		    */
		    Sxapo_cb->sxapo_status=SXAPO_ACTIVE;
		}
		else if ((STbcompare(pmvalue, 0, SX_C2_MODE_OFF, 0, TRUE)!=0))
		{
		    /*
		    ** Niether ON nor OFF, Invalid mode
		    */
		    *err_code=E_SX1061_SXAP_BAD_MODE;
		    break;
		}
	}
	else
	{
		/*
		** No value, this is an error
		*/
		*err_code=E_SX1061_SXAP_BAD_MODE;
		break;
	}
	/*
	** Get action on error
	*/
	if ((PMget("II.*.C2.ON_ERROR",&pmvalue) == OK))
	{
		if (!STcasecmp(pmvalue, "STOPAUDIT" ))
		{
		    Sxf_svcb->sxf_act_on_err=SXF_ERR_STOPAUDIT;
		}
		else if (!STcasecmp(pmvalue, "SHUTDOWN" ))
		{
		    Sxf_svcb->sxf_act_on_err=SXF_ERR_SHUTDOWN;
		}
		else
		{
		/*
		** Invalid value
		*/
		*err_code=E_SX1060_SXAP_BAD_ONERROR;
		break;
		}
	}
	else
	{
		/*
		** No value, this is an error
		*/
		*err_code=E_SX1060_SXAP_BAD_ONERROR;
		break;
	}
	break;
    }
    /* handle errors */
    if (*err_code != E_SX0000_OK)
    {
	_VOID_ ule_format(*err_code, NULL, ULE_LOG, NULL, NULL,
		0L, NULL, &local_err, 0);
	*err_code = E_SX1020_SXAP_INIT_CNF;
	status = E_DB_ERROR;
    }
    return (status);
}
Example #26
0
i4
main (int argc, char **argv) 
{
    STATUS status=OK;
    PTR drvH=NULL;
    char **list=NULL;
    ATTR_ID **attrList=NULL;
    char **defAttr=NULL;
    i4 count=0, attrCount = 0, retcount;
    i4 i;
    bool badCmdLine = FALSE, rmPkg = FALSE, has_default = FALSE, has_alt
        = FALSE, isReadOnly = FALSE, mgrSpecified = FALSE, batch = FALSE,
	def_or_alt=FALSE;
    i4 pathType = OCFG_SYS_PATH; 
    char altPath[OCFG_MAX_STRLEN] = "\0";
    char drvMgr[OCFG_MAX_STRLEN] = "\0";
    char line[MAXLINE],prompt[MAXLINE];
    char driverPath[OCFG_MAX_STRLEN];
    char *dirPath;
    char driverName[OCFG_MAX_STRLEN];
    char *ii_installation;
    char *p = NULL;
    char custName[OCFG_MAX_STRLEN];
    char etxt[512];

    ATTR_ID driverList[6] = 
    {
        { DRV_ATTR_DRIVER,          "\0" },
        { DRV_ATTR_DRIVER_ODBC_VER, DRV_STR_VERSION },
        { DRV_ATTR_DRIVER_READONLY, DRV_STR_N },
        { DRV_ATTR_DRIVER_TYPE,     DRV_STR_INGRES },
        { DRV_ATTR_VENDOR,          DRV_STR_INGRES_CORP },
        { DRV_ATTR_DONT_DLCLOSE,    DRV_STR_ONE }
    };
    int drvCount = sizeof(driverList) / sizeof(driverList[0]);

    ATTR_ID **drvList = (ATTR_ID **)MEreqmem( (u_i2) 0, 
	(u_i4)drvCount, TRUE, (STATUS *) NULL);

    for (i = 0; i < drvCount; i++)
    {
        drvList[i] = (ATTR_ID *)MEreqmem( (u_i2) 0, 
	    (u_i4)sizeof(ATTR_ID), TRUE, (STATUS *) NULL);
        drvList[i]->id = driverList[i].id;
        drvList[i]->value = (char *)MEreqmem( (u_i2) 0, 
    	    (u_i4)OCFG_MAX_STRLEN, TRUE, (STATUS *) NULL);
        STcopy(driverList[i].value, drvList[i]->value);
    }

    if ( argc > 7 )
        badCmdLine = TRUE;

    /*
    ** Parse the command line.  Reject invalid arguments.
    */
    if ( !badCmdLine && argc > 1 )
    {
	if (checkArgs("-h", argc, argv, NULL, NULL ) )
	{
	   display_help();
           PCexit(0);	
	}
	if (checkArgs("-help", argc, argv, NULL, NULL ) )
	{
	   display_help();
           PCexit(0);	
	}
        if ( checkArgs("-batch", argc, argv, NULL, NULL ) )
            batch = TRUE;
        if ( checkArgs("-rmpkg", argc, argv, NULL, NULL ) )
            rmPkg = TRUE;
        if (checkArgs("-r", argc, argv, NULL, NULL ) )
            isReadOnly = TRUE;
        if ( checkArgs("-p", argc, argv, altPath, NULL ) )
            pathType = OCFG_ALT_PATH;
        if ( checkArgs("-m", argc, argv, NULL, drvMgr ) )
			mgrSpecified = TRUE;
    }

    /*
    ** Set driver manager according to user input.  Default is unixODBC.
    */
    if (mgrSpecified && !STbcompare( drvMgr, 0, MGR_STR_CAI_PT, 0, TRUE ) )
        driverManager = MGR_VALUE_CAI_PT;
    else
	driverManager = MGR_VALUE_UNIX_ODBC;

    /*
    ** If none of the arguments are recognized, flag an error.
    */
    if ( !batch && !rmPkg && !isReadOnly && pathType != OCFG_ALT_PATH && !mgrSpecified && argc > 1)
        badCmdLine = TRUE;

    if ( badCmdLine )
    {
        display_help();
        PCexit(FAIL);
    }
    
    if ( isReadOnly )
        STcopy(DRV_STR_Y, drvList[2]->value); 
    else
        STcopy(DRV_STR_N, drvList[2]->value); 

    if ( !writeMgrFile( altPath ) )
    {
        SIprintf("Aborting due to error writing %s/files/%s\n",
           SYSTEM_LOCATION_SUBDIRECTORY, MGR_STR_FILE_NAME); 
        PCexit(FAIL);
    }
    defAttr = getDefaultInfo(); 
    if (defAttr == NULL)
    {
        SIprintf("Aborting due to error reading %s/install/%s\n",
            SYSTEM_LOCATION_VARIABLE, INFO_STR_FILE_NAME);
        PCexit(FAIL);
    }

    /*
    ** Get the path of the driver library and create the path/libname string.
    */
    NMgtAt(SYSTEM_LOCATION_VARIABLE,&dirPath);  /* usually II_SYSTEM */
    if (dirPath != NULL && *dirPath)
        STlcopy(dirPath,driverPath,sizeof(driverPath)-20-1);
    else
    {
        SIprintf("Error--%s is not defined\n",SYSTEM_LOCATION_VARIABLE);
        PCexit(FAIL);
    }
# ifdef VMS
    STcat(driverPath,"[");
    STcat(driverPath,SYSTEM_LOCATION_SUBDIRECTORY);  /* usually "ingres"  */
    STcat(driverPath,".library]");
    if ( isReadOnly )
        STcat(driverPath,defAttr[INFO_ATTR_RONLY_DRV_FNAME]);
    else
        STcat(driverPath,defAttr[INFO_ATTR_DRIVER_FILE_NAME]);
# else
    STcat(driverPath,"/");
    STcat(driverPath,SYSTEM_LOCATION_SUBDIRECTORY);  /* usually "ingres"  */
    STcat(driverPath,"/lib/");
    if ( isReadOnly )
        STcat(driverPath,defAttr[INFO_ATTR_RONLY_DRV_FNAME]);
    else
        STcat(driverPath,defAttr[INFO_ATTR_DRIVER_FILE_NAME]);
# endif /* ifdef VMS */
    STcopy(driverPath,drvList[0]->value);
    /*
    ** Initialize the cache from the odbcinst.ini file.
    */
    openConfig(NULL, pathType, altPath, &drvH, &status);
    if (status != OK)
    {
        STprintf(etxt,"Could not open from path %s.\n",
            pathType == OCFG_ALT_PATH ? altPath : "/usr/local/etc");
        display_err(etxt,status);
        PCexit(FAIL);
    }
    if (rmPkg)
    {
        delConfigEntry( drvH, defAttr[INFO_ATTR_DRIVER_NAME], &status );
        delConfigEntry( drvH, defAttr[INFO_ATTR_ALT_DRIVER_NAME], &status );
        closeConfig(drvH, &status);
        PCexit(OK);
    }
    /*
    ** Get the driver count.
    */
    retcount = listConfig( drvH, count, list, &status );
    if (status != OK)
    {
        STprintf(etxt,"Could not list drivers.\n");
        display_err(etxt,status);
        PCexit(FAIL);
    }
    count = retcount;
    if (count)
    {
        /*
        ** Get the list of recognized drivers.
        */
	list = (char **)MEreqmem( (u_i2) 0, 
	    (u_i4)(count * sizeof(char *)), TRUE, 
	    (STATUS *) NULL);
	for (i = 0; i < count; i++)
	    list[i] =  (char *)MEreqmem( (u_i2) 0, (u_i4)OCFG_MAX_STRLEN, 
	        TRUE, (STATUS *) NULL);
        listConfig( drvH, count, list, &status );
        if (status != OK)
        {
            STprintf(etxt,"Could not list drivers.\n");
            display_err(etxt,status);
            PCexit(FAIL);
        }
    }
    for (i = 0; i < count; i++)
    {
        def_or_alt = FALSE;
	if (!has_default)
	{
            has_default = STbcompare( list[i], 0, 
                defAttr[INFO_ATTR_DRIVER_NAME], 0, TRUE ) 
                   == 0 ? TRUE : FALSE;
            if (has_default)
                def_or_alt = TRUE; 
        }
        if (!has_alt)
        {
            has_alt = STbcompare( list[i], 0, 
                defAttr[INFO_ATTR_ALT_DRIVER_NAME], 0, 
                   TRUE ) == 0 ? TRUE : FALSE;
            if (has_alt)
                def_or_alt = TRUE; 
        }
        if (def_or_alt)
        {
            if ( !batch )
	    {
                STprintf(prompt,
         "\tInstallation has pre-defined version of %s.\n\tOverwrite? (Yes/No)", 
		list[i]);
                if ( line_get( prompt, "", FALSE, line ) == EOF )
                {
                    SIprintf("ODBC driver installation safely aborted\n");
                    PCexit(OK);
                }
                STzapblank(line,line);
                if ( line[0] != 'y' && line [0] != 'Y' )
                {
                    SIprintf( "%s left untouched\n", list[i] );
		    continue; 
                }
            } /* if (!batch) */
            STcopy(list[i],driverName);
            setConfigEntry( drvH, driverName, drvCount, drvList, &status );
            if (status != OK)
            {
                STprintf(etxt,"Could not write driver entry.\n");
                display_err(etxt,status);
                PCexit(FAIL);
            }
        } /* if (has_default || has_alt) */ 
        else if ( !batch )
        {
                STprintf(prompt,
         "\tInstallation has custom version of %s.\n\tDelete? (Yes/No)", 
		list[i]);
                if ( line_get( prompt, "", FALSE, line ) == EOF )
                {
                    SIprintf("ODBC driver installation safely aborted\n");
                    PCexit(OK);
                }
                STzapblank(line,line);
                if ( line[0] != 'y' && line [0] != 'Y' )
                {
                    SIprintf( "%s left untouched\n", list[i] );
                    continue;
                }
            STcopy(list[i],driverName);
            delConfigEntry( drvH, driverName, &status );
            if (status != OK)
            {
                STprintf(etxt,"Could not write driver entry.\n");
                display_err(etxt,status);
                PCexit(FAIL);
            } 
        } /* if (!batch) && !has_default */
    } /* for (count... */
    if (!has_default) 
    {
        setConfigEntry( drvH, defAttr[INFO_ATTR_DRIVER_NAME], drvCount,
	    drvList, &status );
        if (status != OK)
        {
            STprintf(etxt,"Could not write driver entry.\n");
            display_err(etxt,status);
            PCexit(FAIL);
        }
    }
    if (!has_alt) 
    {
        setConfigEntry( drvH, defAttr[INFO_ATTR_ALT_DRIVER_NAME], drvCount,
	    drvList, &status );
        if (status != OK)
        {
            STprintf(etxt,"Could not write driver entry.\n");
            display_err(etxt,status);
            PCexit(FAIL);
        }
    }
    closeConfig(drvH, &status);
    if (status != OK)
    {
        STprintf(etxt,"Could not close driver info.\n");
        display_err(etxt,status);
        PCexit(FAIL);
    }
    if (count)
    {
        for (i = 0; i < count; i++)
	    MEfree((PTR)list[i]);
        MEfree((PTR)list);
    }
    for (i = 0; i < drvCount; i++)
    {
        MEfree((PTR)drvList[i]->value);
        MEfree((PTR)drvList[i]);
    }
    MEfree((PTR)drvList);

    PCexit(OK);
}
Example #27
0
/*
** Name: check_user
**
** Description:
**      Test the characters in the username as returned from
**      the operating system.
**
** Inputs:
**      None.
**
** Output:
**      error_msg   pointer to the area where an error message should be
**                  copied
**
** Returns:
**      None.
**
** History:
**      14-Feb-2005 (fanra01)
**          Created.
*/
static i4
check_user()
{
    i4			result;
    char                username[UNLEN + 1] = { 0 };
    i4                  nsize = MAX_COMPNAME;
#if defined(UNIX)
    struct   passwd     *p_pswd, pwd;
    char                pwuid_buf[BUFSIZ];
    int                 size = BUFSIZ;
#endif

    /*
    ** Get current user name
    */
    nsize = UNLEN;
#if defined(UNIX)
   MEfill ( sizeof(pwuid_buf), '\0', pwuid_buf );
   if( ( p_pswd = iiCLgetpwuid(getuid(), &pwd, pwuid_buf, size) ) != NULL) 
    {
       STcopy( p_pswd->pw_name, username ); 
#else   /* UNIX */
    if (GetUserName( username, &nsize ))
    {
#endif  /* UNIX */
        /*
        ** Check if the username contains unsupported characters
        */
        if (!CMvalidusername( username ))
        {
            result = II_INVALID_USER;
            return(result);
        }
    }
    else
    {
        result = II_GET_USER_FAIL;
        return(result);
    }

    result = II_SUCCESSFUL;
    return(result);
}

/*
** Name: check_os_arch - Verify OS and architecture
**
** Description:
**  Function verifies the OS version and the operating architecture and
**  determines whether the platform should support an installation of
**  Ingres.
**
**  The following checks are applied:
**      a. Verify the minimum OS version
**      b. Verfiy execution mode.
**      c. Verify architecture.
**
** Inputs:
**  None.
**
** Outputs:
**  None.
**
** Returns:
**  0           Platform verified successfully
**  non-zero    Error verifying platform
**
** History:
**      14-Dec-2004 (fanra01)
**          Created.
**
*/
# ifdef NT_GENERIC
/*
** Name: OS_ARCH
**
** Description:
**  Structure to describe Ingres architecture coupled with actual hardware
**  architecture.
**
**      inghw    Ingres hardware code will run on the processor architecture.
**      procarch Processor architecture.
**
** History:
**      15-Dec-2004 (fanra01)
**          Created.
*/

typedef struct _os_arch
{
    i4 inghw;
    i4 procarch;
}OS_ARCH;

static OS_ARCH platform[] = 
{
    { II_IA32,  PROCESSOR_ARCHITECTURE_INTEL }, /* 32-bit Ingres on IA32 */
    { II_IA32,  PROCESSOR_ARCHITECTURE_AMD64 }, /* 32-bit Ingres on AMD64 */
    { II_IA64,  PROCESSOR_ARCHITECTURE_IA64  }, /* 64-bit Ingres on IA64 */
    { II_AMD64, PROCESSOR_ARCHITECTURE_AMD64 }, /* 64-bit Ingres on AMD64 */
    { 0x000000, 0 }
};

static i4
check_os_arch( i4 architecture )
{
    typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS)(HANDLE hProcess,PBOOL Wow64Process);
    typedef VOID (WINAPI *LPFN_GETNATIVESYSTEMINFO)(LPSYSTEM_INFO lpSystemInfo);
    BOOL bIsWow64 = FALSE;
    BOOL bVersVerified = FALSE;
    LPFN_ISWOW64PROCESS fnIsWow64Process;
    LPFN_GETNATIVESYSTEMINFO fnGetNativeSystemInfo;
    DWORDLONG dwlConditionMask = 0;
    i4  result = 0;
    i4  i;
    
    SYSTEM_INFO sysinfo;
    OSVERSIONINFOEX osvi;

    MEfill( sizeof(SYSTEM_INFO), 0, &sysinfo );
    MEfill( sizeof(OSVERSIONINFOEX), 0, &osvi );
 
    /*
    ** Test the processing mode.  bIsWow64 is TRUE if this is 32-bit code
    ** running in a 32-bit execution layer on a 64-bit processor.
    */
    if ((fnIsWow64Process =
        (LPFN_ISWOW64PROCESS)GetProcAddress( GetModuleHandle("kernel32"),
            "IsWow64Process")) != NULL)
    {
        if((fnGetNativeSystemInfo =
            (LPFN_GETNATIVESYSTEMINFO)GetProcAddress(
                GetModuleHandle("kernel32"), "GetNativeSystemInfo")) == NULL)
        {
            result = GetLastError();
        }
        if (result == 0)
        {
            if (!fnIsWow64Process(GetCurrentProcess(),&bIsWow64))
            {
                result = GetLastError();
            }
        }
    }
    if (result == 0)
    {
        /*
        ** Verify the minimum version requirement.
        ** This has been set at Windows NT 4 SP3.
        */
        osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
        osvi.dwMajorVersion = 4;
        osvi.dwMinorVersion = 0;
        osvi.wServicePackMajor = 3;
        VER_SET_CONDITION( dwlConditionMask, VER_MAJORVERSION, 
            VER_GREATER_EQUAL );
        VER_SET_CONDITION( dwlConditionMask, VER_MINORVERSION, 
            VER_GREATER_EQUAL );
        VER_SET_CONDITION( dwlConditionMask, VER_SERVICEPACKMAJOR, 
            VER_GREATER_EQUAL );
        bVersVerified = VerifyVersionInfo( &osvi, 
            VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR,
            dwlConditionMask);
        if (bVersVerified == FALSE)
        {
            result = GetLastError();
        }
        else
        {
            /*
            ** Get the system information that includes the processor
            ** architecture.
            */
            if ((bIsWow64 == TRUE) &&
                (fnGetNativeSystemInfo != NULL))
            {
                /*
                ** Running 32-bit execution layer on a 64-bit platform
                ** Use function that gets true architecture.
                */
                fnGetNativeSystemInfo( &sysinfo );
            }
            else
            {
                GetSystemInfo( &sysinfo );
            }
            if (result == 0)
            {
                result = FAIL;
                for( i=0; platform[i].inghw != 0; i+=1 )
                {
                    if ((architecture == platform[i].inghw) &&
                        (sysinfo.wProcessorArchitecture == platform[i].procarch))
                    {
                        /*
                        ** Return true if and only if the Ingres hardware
                        ** platform is specifically associated with the
                        ** processor architecture.
                        */
                        result = OK;
                        break;
                    }
                }
            }
        }
    }
    return(result);
}
# endif /* NT_GENERIC */

# if defined(UNIX) 
/*
** Name: check_os_arch - Verify OS and architecture on UNIX/LINUX
**
** Description:
**  Function verifies the hardware architecture and OS system, 
**  determines whether the platform should support an installation of
**  Ingres.
**
**
** Inputs: Ingres architecture  ( defined as GV_HW in gv.h )   
**
**
** Returns:
**  0           Platform verified successfully
**  non-zero    Error verifying platform
**
** History:
**      15-Oct-2006 (hweho01)
**          Added for Unix/Linux platforms.
**
*/
/*
** Name: OS_ARCH
**
** Description:
**  Structure to describe Ingres architecture coupled with actual OS  
**  system name.
**
**      inghw    Ingres hardware code will run on the OS system.
**      os_name  system name.
**
*/
typedef struct _os_arch
{
    i4 inghw;
    char os_name[20];
}OS_ARCH;

static OS_ARCH platform[] = 
{
    { II_IA32,  "LINUX" }, /* 32-bit Ingres on IA32 */
    { II_IA32,  "LINUX" }, /* 32-bit Ingres on AMD64 */
    { II_IA64,  "LINUX" }, /* 64-bit Ingres on IA64 */
    { II_AMD64, "LINUX" }, /* 64-bit Ingres on AMD64 */
    { II_SPARC, "SUNOS" }, /* 32/64  Ingres on Sun Solaris */
    { II_PARISC, "HP-UX" }, /* 32/64  Ingres on HP UNIX */
    { II_POWERPC, "AIX" },   /* 32/64  Ingres on IBM POWERPC */
    { 0x000000,   NULL  } 
};

static i4
check_os_arch( i4 architecture )
{

   struct  utsname  sysinfo;  
   i4  ret,  i ; 
   i4  result = 0;
               
      /* check the running OS info */
      ret = uname( &sysinfo );
   
      result = FAIL;
      for( i=0; platform[i].inghw != 0; i+=1 )
         {
           if ((architecture == platform[i].inghw) &&
               (STcasecmp( sysinfo.sysname, platform[i].os_name) == 0))
                 {
                    result = OK;
                    break;
                 }
          }
    return(result);
}
# endif  /* UNIX */


/*
** Name: check_platform - Verify software platform
**
** Description:
**  Function determines the operating platform and verifies that the
**  minimum requirements are fulfilled.
**
** Inputs:
**  None.
**
** Outputs:
**  None.
**
** Returns:
**  0           architecture verification succeeded
**  non-zero    architecture failed verification
**
** History:
**  13-Dec-2004 (fanra01)
**      Created.
*/
static i4
check_platform( i4 architecture )
{
    i4 result = 0;
    ING_VERSION ingver;
    char* plat_override = NULL;
    
    NMgtAt(ERx("II_RELAX_PLATFORM"), &plat_override);
    if (plat_override && *plat_override)
    {
        return(result);
    }

    /*
    ** No architecture has been specified, use the internal compiled one.
    */
    if (architecture == II_DEFARCH)
    {
        MEfill( sizeof(ING_VERSION), 0, &ingver );
        /*
        ** Retrieve the hardware architecture used to build this version
        */
        if ((result = GVver( GV_M_HW, &ingver )) == OK)
        {
            /*
            ** Reassign the architecture to the retrieved one.
            */
            architecture = ingver.hardware;
        }
    }

    if (result == OK)
    {
        result = check_os_arch( architecture );
    }

    return(result);
}
Example #28
0
/*
** Name: GCwintcp_init
** Description:
**	WINTCP inititialization function.  This routine is called from
**	GCwinsock_init() -- the routine GCC calls to initialize protocol 
**	drivers.
**
**	This function does initialization specific to the protocol:
**	   Reads any protocol-specific env vars.
**	   Sets up the winsock protocol-specific control info.
** History:
**	05-Nov-93 (edg)
**	    created.
**	23-Feb-1998 (thaal01)
**	    Allow space for port_id, stops GCC crashing on startup sometimes.
**	07-Jul-1998 (macbr01)
**	    Bug 91972 - jasgcc not receiving incoming communications. This is 
**	    due to incorrect usage of PMget() in function GCwintcp_init(). 
**	    Changed to test return code of PMget() instead of testing passed 
**	    in parameter for not equal to NULL.
**	15-jul-1998 (canor01)
**	    Move assignment of port_id to port_id_buf to prevent possible
**	    access violation. Clean up comments.
**	09-feb-2004 (somsa01)
**	    When working with instance identifiers as port IDs, make sure
**	    we initialize sbprt with the trailing number, if set.
**	13-may-2004 (somsa01)
**	    Updated config.dat string used to retrieve port information such
**	    that we do not rely specifically on the GCC port. Also, corrected
**	    function used to convert subport into a number.
**      26-Jan-2006 (loera01) Bug 115671
**          Added GCWINTCP_log_rem_host to allow of gethostbyaddr() to be
**          disabled.
**      06-Feb-2007 (Ralph Loen) SIR 117590
**          Removed GCWINTCP_log_rem_host, since gethostbyaddr() is no
**          longer invoked for network listens.
**      22-Feb-2008 (rajus01) Bug 119987, SD issue 125582
**          Bridge server configuration requires listening on a specified
**          three character listen address. During protocol initialization
**          the bridge server fails to start when three character listen
**          address is specified. For example,
**          the following configuration entries in config.dat
**               ii.<host>.gcb.*.wintcp.port: <xxn>,
**               ii.<host>.gcb.*.wintcp.status:<prot_stat>
**          are for command line configuration. When these entries are
**          present in addition to the CBF VNODE configuration (shown below )
**                ii.rajus01.gcb.*.wintcp.port.v1:<xxn>
**                ii.rajus01.gcb.*.wintcp.status.v1:<prot_stat>
**          the bridge server fails even though the port is available for use.
**          It has been found that the global 'sbprt' variable gets set
**          by the bridge server during protocol initialization to 'n' in the
**          three charater listen address 'xxn'. Later, while resolving the
**          three character portname into port number by GCwintcp_port routine
**          it assumes that this port is already in use even though it is not
**          the case.
**	    Added server_type to determine the GCF server type.
**          The error messages from errlog.log are the following:
**          rajus01 ::[R3\BRIDGE\12c4    , 4804      , ffffffff]: Tue Feb 19
**          19:49:27 2008 E_GC2808_NTWK_OPEN_FAIL  Network open failed for
**          protocol TCP_IP, port R3; status follows.
**          rajus01 ::[R3\BRIDGE\12c4    , 4804      , ffffffff]: Tue Feb 19
**          19:49:27 2008 E_CL2787_GC_OPEN_FAIL    An attempted network open
**          failed.
**	    Change description:
**		The code that clears the third character in the listen address
**		specified in the config.dat has been removed. This
**		appears to be a wrong assumption in the protocol driver based
**	        on the documentation in "Appendix A:TCP/IP protocol, Listen
**		Address Format seciton of Connectivity Guide". With these
**		changes the protocol driver will behave the way UNIX does.
**
**		WARNING: This DOES introduce the behavioural changes in the
**		following cases when starting one or more servers by increa-
**		sing the startup count in config.dat.
**		
**		Case 1: 
**		   Both tcp_ip and win_tcp status are set to ON with Listen
**		   Addresses II5 and II5 for example.
**		   New behaviour: The GCF server will come up and listen on 
**	           one protocol using port II5, but will fail on the other 
**		   protocol. 
**		   Original behaviour:
**		   The GCF server will listen on port II5 on the first
**		   protocol and the second one will listen on II6.
**		   This seems to be a bug in the driver as this is not the 
**		   behaviour documented in the connectivity guide. 
**		Case 2:
**		   Both tcp_ip and win_tcp status are set to ON with Listen
**		   Addresses (win_tcp=II, tcp_ip = II1).
**		   Original behaviour:
**		   First GCF server will come up OK (II0, II1). The second
**		   GCF server will come up fine too ( II2, II3 ).
**		   New Behaviour:
**		   First GCF server will come up fine. The second GCF server
**		   will fail for tcp_ip protocol, but will come up on win_tcp
**		   protocol. This doesn't seem to be much of an issue because
**		   the second GCF server will still come up using win_tcp. 
**	13-Apr-2010 (Bruce Lunsford)  SIR 122679
**	    Set wsd->pce_driver from GCC PCT rather than from ex-global
**	    WS_wintcp.
*/
STATUS
GCwintcp_init(GCC_PCE * pptr, GCC_WINSOCK_DRIVER *wsd)
{

	char           *ptr = NULL;
	char            real_name_size[] = "100";
	char           *host, *server_id, *port_id;
	char            config_string[256];
	char            install[32]; //II_INSTALLATION code

        /*
        ** Get set up for the PMget call.
        */
        PMinit();
        if( PMload( NULL, (PM_ERR_FUNC *)NULL ) != OK )
                PCexit( FAIL );

        /*
        ** Construct the network port identifier.
        */

        host = PMhost();
        server_id = PMgetDefault(3);
        if (!server_id)
                server_id = "*" ;
        STprintf( config_string, ERx("!.wintcp.port"),
                  SystemCfgPrefix, host, server_id);

        /*
        ** Search config.dat for a match on the string we just built.
        ** If we don't find it, then use the value for II_INSTALLATION
        ** failing that, default to II.
        */
        if ((PMget( config_string, &port_id ) != OK) ||
            (port_id == NULL ))
        {
                NMgtAt("II_INSTALLATION", &ptr);
		port_id = install; 
                if (ptr != NULL && *ptr != '\0')
                {
                        STcopy(ptr, port_id);
                }
                else
                {
                        STcopy(SystemVarPrefix, port_id);
                }
        }

	STcopy(port_id, pptr->pce_port);
	GCTRACE(1)("GCwintcp_init: port = %s\n", pptr->pce_port );


	/*
	** Fill in protocol-specific info
	*/
	wsd->addr_len = sizeof( struct sockaddr_in );
	wsd->sock_fam = AF_INET;
	wsd->sock_type = SOCK_STREAM;
	wsd->sock_proto = 0;
	wsd->block_mode = FALSE;
	wsd->pce_driver = pptr->pce_driver;

	/*
	** Get trace variable
	*/
        ptr = NULL;
	NMgtAt( "II_WINTCP_TRACE", &ptr );
	if ( !(ptr && *ptr) && PMget("!.wintcp_trace_level", &ptr) != OK )
	{
	    GCWINTCP_trace = 0;
	}
	else
	{
	    GCWINTCP_trace = atoi( ptr );
	}

	return OK;
}
Example #29
0
BOOL CWinstartApp::InitInstance()
{
    char	*ii_installation;
    HWND	hWnd;
    CString	csWindow;

    NMgtAt(ERx( "II_INSTALLATION" ), &ii_installation);
    if (ii_installation == NULL || *ii_installation == EOS)
        ii_installation = ERx("II");
    else
        ii_installation = STalloc(ii_installation);
    csSemaphore.Format("IngresII_Winstart_%s", ii_installation);
    csWindow.Format(IDS_CAPTIONTEXT,(LPCTSTR)ii_installation);

    hSemaphore = OpenSemaphore( SEMAPHORE_ALL_ACCESS, FALSE,
                                (LPCTSTR)csSemaphore );
    if (hSemaphore)
    {
        /*
        ** We've already got a WINSTART running for this installation.
        ** Attempt to find it and change focus to it.
        */
        CloseHandle(hSemaphore);
        hWnd = FindWindow(NULL, csWindow);
        if(hWnd)
        {
            SetForegroundWindow(hWnd);
            ShowWindow(hWnd, SW_RESTORE);
            exit(0);
        }
    }

    hSemaphore = CreateSemaphore(NULL, cMax, cMax, (LPCTSTR)csSemaphore);

    /*
    ** Standard initialization
    ** If you are not using these features and wish to reduce the size
    ** of your final executable, you should remove from the following
    ** the specific initialization routines you do not need.
    */
    InitCommonControls();
    CWinApp::InitInstance();

    AfxEnableControlContainer ();

    /* Load standard INI file options (including MRU) */
    LoadStdProfileSettings();

    CWinstartDlg dlg;
    m_pMainWnd = &dlg;

    CString strCmdLine="";
    if (m_lpCmdLine)
        strCmdLine = m_lpCmdLine;

    strCmdLine.MakeLower();

    if (strCmdLine.Find("/start") != -1)
        dlg.m_bStartFlag = TRUE;
    else
        dlg.m_bStartFlag = FALSE;

    if (strCmdLine.Find("/stop") != -1)
        dlg.m_bStopFlag = TRUE;
    else
        dlg.m_bStopFlag = FALSE;

    int i, iPos, iLen, iLeft, iChars=0;
    TCHAR p;
    dlg.m_strParam="";

    iPos = strCmdLine.Find("/param=\"");
    if (iPos != -1)
    {
        dlg.m_bParamFlag = TRUE;
        iLen = strCmdLine.GetLength();
        iLeft = iPos + 8;
        for (i=iLeft; i<iLen; i++)
        {
            p = strCmdLine.GetAt(i);
            if (p == '\"')
                break;
            iChars++;
        }

        dlg.m_strParam=strCmdLine.Mid(iLeft, iChars);
    }
    else
        dlg.m_bParamFlag = FALSE;

    dlg.DoModal();
    /*
    ** Since the dialog has been closed, return FALSE so that we exit the
    ** application, rather than start the application's message pump.
    */
    return FALSE;
}