Example #1
0
/*  Chase ID references - follow IDREF(s) attributes until we find
 *  a GI named 'gi', then perform given action on that GI.
 *  Arguments:
 *	Pointer to element under consideration.
 *	Name of GI we're looking for.
 *	Spec ID of action to take.
 *	FILE pointer to where to write output.
 */
void
ChaseIDRefs(
    Element_t	*e,
    char	*gi,
    char *	action,
    FILE	*fp
)
{
    int		ntok, i, ei;
    char	**tok, **s, *atval;

    /* First, see if we got what we came for with this element */
    if (StrEq(e->gi, gi)) {
	TranTByAction(e, action, fp);
	return;
    }
    GetIDREFnames();

    /* loop for each attribute of type IDREF(s) */
    for (s=idrefs; *s; s++) {
	/* is this IDREF attr set? */
	if ((atval = FindAttValByName(e, *s))) {
	    ntok = 0;
	    tok = Split(atval, &ntok, 0);
	    for (i=0; i<ntok; i++) {
		/* get element pointed to */
		if ((e = FindElemByID(tok[i]))) {
		    /* OK, we found a matching GI name */
		    if (StrEq(e->gi, gi)) {
			/* process using named action */
			TranTByAction(e, action, fp);
			return;
		    }
		    else {
			/* this elem itself did not match, try its children */
			for (ei=0; ei<e->necont; ei++) {
			    if (StrEq(e->econt[ei]->gi, gi)) {
				TranTByAction(e->econt[ei], action, fp);
				return;
			    }
			}
			/* try this elem's IDREF attributes */
			ChaseIDRefs(e, gi, action, fp);
			return;
		    }
		}
		else {
		    /* should not happen, since parser checks ID/IDREFs */
		    fprintf(stderr, "Error: Could not find ID %s\n", atval);
		}
	    }
	}
    }
    /* if the pointers didn't lead to the GI, give error */
    if (!s)
	fprintf(stderr, "Error: Could not find '%s'\n", gi);
}
Example #2
0
static void
tr_find_gipar(
    Element_t	*e,
    Descent_t	*ds
)
{
    if (StrEq(ds->gi, e->gi) && e->parent &&
		StrEq(ds->gi2, e->parent->gi))
	if (ds->action[0]) TranTByAction(e, ds->action, ds->fp);
}
Example #3
0
/*  Descend tree, finding elements that match criteria, then perform
 *  given action.
 *  Arguments:
 *	Pointer to element under consideration.
 *	Number of tokens in special variable.
 *	Vector of tokens in special variable (eg, "find" "gi" "TITLE")
 *	FILE pointer to where to write output.
 */
void
Find(
    Element_t	*e,
    int		ac,
    char	**av,
    FILE	*fp
)
{
    Descent_t	DS;		/* state passed to recursive routine */

    memset(&DS, 0, sizeof(Descent_t));
    DS.elem = e;
    DS.fp   = fp;

    /* see if we should start at the top of instance tree */
    if (StrEq(av[1], "top")) {
	av++;
	ac--;
	e = DocTree;
    }
    if (ac < 4) {
	fprintf(stderr, "Bad '_find' specification - missing args.\n");
	return;
    }
    /* Find elem whose GI is av[2] */
    if (StrEq(av[1], "gi")) {
	DS.gi     = av[2];
	strcpy(DS.action, av[3]);
	DescendTree(e, tr_find_gi, 0, 0, &DS);
    }
    /* Find elem whose GI is av[2] and whose parent GI is av[3] */
    else if (StrEq(av[1], "gi-parent")) {
	DS.gi     = av[2];
	DS.gi2    = av[3];
	strcpy(DS.action, av[4]);
	DescendTree(e, tr_find_gipar, 0, 0, &DS);
    }
    /* Find elem whose parent GI is av[2] */
    else if (StrEq(av[0], "parent")) {
	DS.gi     = av[2];
	strcpy(DS.action, av[3]);
	DescendTree(e, tr_find_parent, 0, 0, &DS);
    }
    /* Find elem whose attribute av[2] has value av[3] */
    else if (StrEq(av[0], "attr")) {
	DS.gi     = av[2];
	DS.gi2    = av[3];
	strcpy(DS.action, av[4]);
	DescendTree(e, tr_find_attr, 0, 0, &DS);
    }
}
Example #4
0
static char *SetLinkParms( char **pparm )
{
    char        *parm;
    char        arg1[7];
    int         arg1_len;
    char        *result;        /* result of ParsePortSpec or SetComPort */

    parm = *pparm;
    MaxBaud = 0;                /* default max baud is 115200 */

    /* strip leading white spaces */
    while( *parm == ' ' || *parm == '\t' ) ++parm;

    result = ParsePortSpec( &parm );
    if( result != NULL ) return( result );

    arg1_len = 0;
    if( *parm == '.' ) {
        ++parm;
        parm = CollectParm( parm, arg1, &arg1_len );
        if( arg1_len >= 7 ) return( TRP_ERR_invalid_baud_rate );
    }
    *pparm = parm;
    if( arg1_len == 0 ) return( NULL );
    arg1[ arg1_len ] = '\0';
    if( StrEq( arg1, "0" ) ) {
        MaxBaud = MIN_BAUD;
        return( NULL );
    }
    if( arg1_len < 2 ) return( TRP_ERR_ambiguous_baud_rate );
    return( SetMaxBaud( arg1 ) );
}
TEST_F( JavaScriptExecuterTest, creating_attribute_ZCL_uint8_log_type_two_time) {
	ZEndpoint zEndpoint { NWK_ADDRESS, ENDPOINT_ID, PROFILE_ID, DEVICE_ID, DEVICE_VER, IN_CLUSTERS, OUT_CLUSTERS };
	ZDevice zDevice { extAddress, NWK_ADDRESS, 0, { zEndpoint } };
	Log log;
	std::stringstream js;
	jsExecuter = make_shared<JavaScriptExecuter>(singletonObjects, log);
	EXPECT_CALL(*zDevices, exists(extAddress)).WillOnce(Return(true));
	EXPECT_CALL(*zDevices, getDevice(extAddress)).WillOnce(Return(&zDevice));
	string objectName = "Z" + ZCL_uint8_Attribute::name();

	js << "var log = Log();";
	js << "if (a == null){";
	js << "  var a = " <<  objectName << "('" << EXTENDED_ADDRESS << "', " << ENDPOINT_ID << ", " << BASIC_CLUSTER << "," << APPLICATION_VERSION_ID << ");";
	js << "} else {";
	js << "  log.info(a);";
	js << "};";

	jsExecuter->run(js.str());
	jsExecuter->join();
	ASSERT_TRUE(log.empty());
	jsExecuter->run(js.str());
	jsExecuter->join();

	ASSERT_FALSE(log.empty());
	Log::LogData logData = log.get();
	ASSERT_THAT(logData.level, Log::INFO) << logData.msg;
	ASSERT_THAT(logData.msg, StrEq("[object " + objectName+ "]"));

	jsExecuter.reset();
}
Example #6
0
static void
tr_find_gi(
    Element_t	*e,
    Descent_t	*ds
)
{
    if (StrEq(ds->gi, e->gi))
	if (ds->action[0]) TranTByAction(e, ds->action, ds->fp);
}
Example #7
0
static void
tr_find_attr(
    Element_t	*e,
    Descent_t	*ds
)
{
    char	*atval;
    if ((atval = FindAttValByName(e, ds->gi)) && StrEq(ds->gi2, atval))
	TranTByAction(e, ds->action, ds->fp);
}
TEST_F(LineIOSegmentManipulatorTests, Parsing_Failed_MissingVariable) {
    istringstream in("42  ");

    try {
        LineIOSegmentManipulator::parse(segment, &in);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Cannot parse for 'B'. Found: <whitespace>"));
    }
}
TEST_F(GridIOSegmentBuilderTests, Building_Failed_NoVariables) {
    try {
        builder
                .setSize(2, 3)
                .build();
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Grid segment must have exactly one variable"));
    }
}
TEST_F(LineIOSegmentManipulatorTests, Parsing_WithVectorWithoutSize_Failed_MissingSpaceOrNewline) {
    istringstream in("42 123 1 2 3 4 5");

    try {
        LineIOSegmentManipulator::parse(segmentWithVectorWithoutSize, &in);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Expected: <space> or <newline> after 'D[2]'"));
    }
}
TEST_F(GridIOSegmentBuilderTests, Building_Failed_SizeNotSet) {
    try {
        builder
                .addMatrixVariable(Matrix::create(M, "M"))
                .build();
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Grid segment must define matrix sizes"));
    }
}
TEST_F(LineIOSegmentManipulatorTests, Parsing_Failed_MissingNewline) {
    istringstream in("42 123 1 2");

    try {
        LineIOSegmentManipulator::parse(segment, &in);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Expected: <newline> after 'C'"));
    }
}
Example #13
0
static int
FindCfgLine(char *FileName,char *SectionName, char *VarName, char *Data)
/*
** Find a VarName within SectionName in file FileName.
** Return TRUE on success, else FALSE
*/
{
 FILE *CfgFile;
 char line[LINE_INPUT_MAX];
 char SectionWanted[LINE_INPUT_MAX];
 char var[LINE_INPUT_MAX];
 int InSection=FALSE;

CfgFile=fopen(FileName,"r");
if (CfgFile==NULL)
  {
   DumpDebug("File %s not found.\n",FileName);
   return FALSE;
  }

sprintf(SectionWanted,"[%s]",SectionName);

while (ReadLine(CfgFile,line))
   {
    if (StrEq(line,SectionWanted))        InSection=TRUE;
    else if (InSection && (line[0]=='[')) InSection=FALSE;
    if (InSection)
        {
         ParseLine(line,var,Data);
         if (StrEq(VarName,var))
           {
            fclose(CfgFile);
            return TRUE;
           }
        }
   }

fclose(CfgFile);
*Data='\0';
return FALSE;
}
Example #14
0
char *SetMaxBaud( char *str )
{
    int i;              /* loop index */

    for( i = 0; i <= MIN_BAUD; ++i ) {
        if( StrEq( str, BaudTable[i].name ) ) {  /* strings are equal */
            MaxBaud = i;
            return( NULL );
        }
    }
    return( TRP_ERR_invalid_maximum_baud_rate );
}
TEST_F(LineIOSegmentManipulatorTests, Printing_Failed_SizeMismatch) {
    ostringstream out;

    C = {1, 2, 3};

    try {
        LineIOSegmentManipulator::print(segment, &out);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("Number of elements of vector 'C' unsatisfied. Expected: 2, actual: 3"));
    }
}
Example #16
0
TEST_F(MagicTests, GRID_Invalid) {
    GRID_Tester tester;
    tester.prepareForInputFormat();

    try {
        tester.testInvalid();
        tester.build();
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("The type of variable 'bogus' is not supported for a grid segment"));
    }
}
Example #17
0
static enum LineTypes SectionLine(char *line,
                                  char *SectionWanted,
                                  char *CurrentSection)
{
      enum LineTypes linetype;

      line = StripLeadingSpaces(line);
      if (!line || NUL == *line)
            return EmptyLine;

      /*
      ** Comments are started with a "%", ";" or "#"
      */

      if (';' == *line)
            return CommentLine;
      if ('%' == *line)
            return CommentLine;
      if ('#' == *line)
            return CommentLine;

      if ('[' == line[0])  /* Section Header */
      {
            linetype = NewSection;
            if (StrEq(CurrentSection, SectionWanted))
                  linetype = LeavingSection;

            strcpy(CurrentSection, line);
            if (StrEq(line, SectionWanted))
                  linetype = FoundSection;
      }
      else
      {            /* Just a regular line */
            linetype = NotInSection;
            if (StrEq(CurrentSection, SectionWanted))
                  linetype = InSection;
      }

      return linetype;
}
Example #18
0
TEST_F(ArgsParserTests, Parsing_InvalidOption) {
    char* argv[] = {
            (char*) "./runner",
            (char*) "--blah"};
    int argc = sizeof(argv) / sizeof(char*);

    try {
        ArgsParser::parse(argc, argv);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("tcframe: option --blah unknown"));
    }
}
Example #19
0
TEST_F(ArgsParserTests, Parsing_MissingOptionArgument) {
    char* argv[] = {
            (char*) "./runner",
            (char*) "--slug"};
    int argc = sizeof(argv) / sizeof(char*);

    try {
        ArgsParser::parse(argc, argv);
        FAIL();
    } catch (runtime_error& e) {
        EXPECT_THAT(e.what(), StrEq("tcframe: option --slug requires an argument"));
    }
}
Example #20
0
TEST_F(EventTest, testConstructorThrowsIfCreateEventFailed) {{
	InSequence s;
	EXPECT_CALL(winApi, CreateEvent((LPSECURITY_ATTRIBUTES)88876,
			TRUE, FALSE, StrEq(TEXT("foobar"))))
		.Times(1)
		.WillOnce(Return((HANDLE)NULL));
	EXPECT_CALL(winApi, GetLastError())
		.Times(1)
		.WillOnce(Return(5567));

	ASSERT_THROW(auto_drop<Event> e(new Event(&winApi,
		(LPSECURITY_ATTRIBUTES)88876, TRUE, FALSE, TEXT("foobar"))),
		WinApiErrorException);
}}
Example #21
0
/* compare filenames.
 * FileNamesEq compares two filenames obeying the naming
 * conventions of the current platform (case sensitive or not).
 * returns 1 if filenames are equal, 0 of not
 */
int FileNamesEq(
	const char *fileName1,  /* first fileName without spaces */
	const char *fileName2)  /* second fileName  without spaces */
{
	PRECOND(fileName1 != NULL);
	PRECOND(fileName2 != NULL);
#ifdef DOS_FS
	return StrCaseEq(fileName1, fileName2);
#else
# ifdef UNIX_FS
	return StrEq(fileName1, fileName2);
# else
#       error no filesystem defined (UNIX_FS or DOS_FS)
# endif
#endif
}
Example #22
0
BOOL Midi_LookupPortIndexes(MIDI *midi)
{
    BOOL setupValid = TRUE;
    int midiInDevCnt = midiInGetNumDevs();
    int midiOutDevCnt = midiOutGetNumDevs();
    int i;
    
    if (StrEq(midi->inPortName, _T("Disabled"))) {
        midi->inPort = -1;
        goto InPortFound;
    }
    for (i = 0; i < midiInDevCnt; i++) {
        MIDIINCAPS midiDevInfo;

        midiInGetDevCaps(i, &midiDevInfo, sizeof midiDevInfo);
        if (StrEq(midi->inPortName, midiDevInfo.szPname)) {
            midi->inPort = i;
            goto InPortFound;
        }
    }
    setupValid = FALSE;
InPortFound:
    if (StrEq(midi->outPortName, _T("Disabled"))) {
        midi->outPort = -1;
        goto OutPortFound;
    }
    for (i = 0; i < midiOutDevCnt; i++) {
        MIDIOUTCAPS midiDevInfo;

        midiOutGetDevCaps(i, &midiDevInfo, sizeof midiDevInfo);
        if (StrEq(midi->outPortName, midiDevInfo.szPname)) {
            midi->outPort = i;
            goto OutPortFound;
        }
    }
    setupValid = FALSE;
OutPortFound:
    if (StrEq(midi->masterInPortName, _T("Disabled"))) {
        midi->masterInPort = -1;
        goto MasterInPortFound;
    }
    for (i = 0; i < midiInDevCnt; i++) {
        MIDIINCAPS midiDevInfo;

        midiInGetDevCaps(i, &midiDevInfo, sizeof midiDevInfo);
        if (StrEq(midi->masterInPortName, midiDevInfo.szPname)) {
            midi->masterInPort = i;
            goto MasterInPortFound;
        }
    }
MasterInPortFound:

    return setupValid;
}
Example #23
0
/* Searches group for the requested data item */
int FindData(NXhandle fileId, char *dataName)
{
    int status, dataType;
    NXname name, nxclass;

    NXinitgroupdir(fileId);
    do {
        status = NXgetnextentry(fileId, name, nxclass, &dataType);
        if (status == NX_ERROR)
            return NX_ERROR;
        if (status == NX_OK) {
            if (StrEq(dataName, name)) {
                if (!strncmp(nxclass, "SDS", 3)) {	/* Data has class "SDS" */
                    return NX_OK;
                } else {
                    printf("NX_ERROR: %s is not data\n", dataName);
                    return NX_ERROR;
                }
            }
        }
    } while (status != NX_EOD);
    printf("NX_ERROR: %s does not exist\n", dataName);
    return NX_EOD;
}
	void expectCompletedLine(string text) {
		EXPECT_CALL(handler, handleLine(StrEq(text))).InSequence(sequence);
	}
Example #25
0
Trans_t *
FindTrans(
    Element_t	*e
)
{
    char	context[LINESIZE], *cp, **vec, *atval;
    int		i, a, match;
    Trans_t	*t, *tt;

    /* loop through all transpecs */
    for (t=TrSpecs; t; t=t->next)
    {
	/* Only one of gi or gilist will be set. */
	/* Check if elem name matches */
	if (t->gi && !StrEq(t->gi, e->gi)) continue;

	/* Match one in the list of GIs? */
	if (t->gilist) {
	    for (match=0,vec=t->gilist; *vec; vec++) {
		if (StrEq(*vec, e->gi)) {
		    match = 1;
		    break;
		}
	    }
	    if (!match) continue;
	}

	/* Check context */

	/* Special case of context */
	if (t->parent)
	    if (!QRelation(e, t->parent, REL_Parent)) continue;

	if (t->context) {	/* no context specified -> a match */
	    FindContext(e, t->depth, context);

	    /* If reg expr set, do regex compare; else just string compare. */
	    if (t->context_re) {
		if (! tpt_regexec(t->context_re, context)) continue;
	    }
	    else {
		/* Is depth of spec deeper than element's depth? */
		if (t->depth > e->depth) continue;

		/* See if context of element matches "context" of transpec */
		match = ( (t->context[0] == context[0]) &&
			    !strcmp(t->context, context) );
		if (!match) continue;
	    }
	}

	/* Check attributes.  Loop through list, comparing each. */
	if (t->nattpairs) {	/* no att specified -> a match */
	    for (match=1,a=0; a<t->nattpairs; a++) {
		if (!(atval = FindAttValByName(e, t->attpair[a].name))) {
		    match = 0;
		    break;
		}
		if (!tpt_regexec(t->attpair[a].rex, atval)) match = 0;
	    }
	    if (!match) continue;
	}

	/* Check relationships:  child, parent, ancestor, sib, ...  */
	if (t->relations) {
	    Mapping_t *r;
	    match = 1;
	    for (r=t->relations->maps,i=0; i<t->relations->n_used; i++) {
		if (!CheckRelation(e, r[i].name, r[i].sval, 0, 0, RA_Current)) {
		    match = 0;
		    break;
		}
	    }
	    if (!match) continue;
	}

	/* check this element's parent's attribute */
	if (t->pattrset && e->parent) {
	    char *p, **tok;

	    i = 2;
	    match = 1;
	    tok = Split(t->pattrset, &i, S_STRDUP);
	    if ( i == 2 ) {
		p = FindAttValByName(e->parent, tok[0]);
		if ( !p || strcmp(p, tok[1]) )
		    match = 0;
	    } else {
		if (!FindAttValByName(e->parent, t->pattrset))
		    match = 0;
	    }
	    free(tok[0]);
	    if (!match) continue;
	}

	/* check this element's "birth order" */
	if (t->nth_child) {
	    /* First one is called "1" by the user.  Internally called "0". */
	    i = t->nth_child;
	    if (i > 0) {	/* positive # -- count from beginning */
		if (e->my_eorder != (i-1)) continue;
	    }
	    else {		/* negative # -- count from end */
		i = e->parent->necont + i;
		if (e->my_eorder != i) continue;
	    }
	}

	/* check that variables match */
	if (t->var_name) {
	    cp = FindMappingVal(Variables, t->var_name);
	    if (!cp || strcmp(cp, t->var_value)) continue;
	}

	/* check content */
	if (t->content) {		/* no att specified -> a match */
	    for (match=0,i=0; i<e->ndcont; i++) {
		if (tpt_regexec(t->content_re, e->dcont[i])) {
		    match = 1;
		    break;
		}
	    }
	    if (!match) continue;
	}

	/* -------- at this point we've passed all criteria -------- */

	/* See if we should be using another transpec's actions. */
	if (t->use_id) {
	    if (t->use_id < 0) return &NullTrans;	/* missing? */
	    /* see if we have a pointer to that transpec */
	    if (t->use_trans) return t->use_trans;
	    for (tt=TrSpecs; tt; tt=tt->next) {
		if (t->use_id == tt->my_id) {
		    /* remember pointer for next time */
		    t->use_trans = tt;
		    return t->use_trans;
		}
	    }
	    t->use_id = -1;	/* flag it as missing */
	    fprintf(stderr, "Warning: transpec ID (%d) not found for %s.\n",
		t->use_id, e->gi);
	    return &NullTrans;
	}

	return t;
    }

    /* At this point, we have not found a matching spec.  See if there
     * is a wildcard, and if so, use it. (Wildcard GI is named "*".) */
    if ((t = FindTransByName("*"))) return t;

    if (warnings)
	fprintf(stderr, "Warning: transpec not found for %s\n", e->gi);

    /* default spec - pass character data and descend node */
    return &NullTrans;
}
Example #26
0
void
ExpandSpecialVar(
    char	*name,
    Element_t	*e,
    FILE	*fp,
    int		track_pos
)
{
    FILE	*infile;
    char	buf[LINESIZE], *cp, *cp2, *atval;
    char	**tok;
    int		ntok, n, i, actioni;
    char	*action, *action1;
    Element_t	*ep;
    Trans_t	*t, *tt;
    Entity_t	*entp;

    /* Run a command.
     * Format: _! command args ... */
    if (*name == '!') {
	name++;
	if ((infile = popen(name, "r"))) {
	    while (fgets(buf, LINESIZE, infile)) fputs(buf, fp);
	    pclose(infile);
	    fflush(fp);
	}
	else {
	    fprintf(stderr, "Could not start program '%s': %s",
		name, strerror(errno));
	}
	return;
    }

    /* See if caller wants one of the tokens from _eachatt or _eachcon.
     * If so, output it and return.  (Yes, I admit that this is a hack.)
     */
    if (*name == 'A' && name[1] == EOS && each_A) {
	OutputString(each_A, fp, track_pos);
	return;
    }
    if (*name == 'C' && name[1] == EOS && each_C) {
	OutputString(each_C, fp, track_pos);
	return;
    }

    ntok = 0;
    tok = Split(name, &ntok, 0);

    /* Include another file.
     * Format: _include filename */
    if (StrEq(tok[0], "include")) {
	name = tok[1];
	if (ntok > 1 ) {
	    if ((infile=OpenFile(name)) == NULL) {
		sprintf(buf, "Can not open included file '%s'", name);
		perror(buf);
		return;
	    }
	    while (fgets(buf, LINESIZE, infile)) fputs(buf, fp);
	    fclose(infile);
	}
	else fprintf(stderr, "No file name specified for include\n");
	return;
    }

    /* Print location (nearest title, line no, path).
     * Format: _location */
    else if (StrEq(tok[0], "location")) {
	PrintLocation(e, fp);
    }

    /* Print path to this element.
     * Format: _path */
    else if (StrEq(tok[0], "path")) {
	(void)FindElementPath(e, buf);
	OutputString(buf, fp, track_pos);
    }

    /* Print name of this element (gi).
     * Format: _gi [M|L|U] */
    else if (StrEq(tok[0], "gi")) {
	strcpy(buf, e->gi);
	if (ntok >= 2) {
	    if (*tok[1] == 'L' || *tok[1] == 'l' ||
		*tok[1] == 'M' || *tok[1] == 'm') {
		for (cp=buf; *cp; cp++)
		    if (isupper(*cp)) *cp = tolower(*cp);
	    }
	    if (*tok[1] == 'M' || *tok[1] == 'm')
		if (islower(buf[0])) buf[0] = toupper(buf[0]);
	}
	OutputString(buf, fp, track_pos);
    }

    /* Print filename of this element's associated external entity.
     * Format: _filename */
    else if (StrEq(tok[0], "filename")) {
    	if ( ntok >= 2 )	{
	    cp2 = FindAttValByName(e, tok[1]);
	    if ( ! (entp = FindEntity(cp2)) )	{
	    	fprintf(stderr, "Can't find entity named %s (via _filename expression):\n", tok[1]);
	    	PrintLocation(e, stderr);
	    	return;
	    }
	    OutputString(entp->sysid, fp, track_pos);
	} else	{
	    if (!e->entity) {
	    	fprintf(stderr, "Expected ext entity (element %s) - no ->entity (internal error? bug?):\n", e->gi);
	    	PrintLocation(e, stderr);
	    	return;
	    }
	    if (!e->entity->fname) {
	    	fprintf(stderr, "Expected filename (element %s) - no ->entity->fname (internal error? bug?):\n", e->gi);
	    	PrintLocation(e, stderr);
	    	return;
	    }
	    OutputString(e->entity->sysid, fp, track_pos);
	}
    }

    /* Value of parent's attribute, by attr name.
     * Format: _pattr attname */
    else if (StrEq(tok[0], "pattr")) {
	ep = e->parent;
	if (!ep) {
	    fprintf(stderr, "Element does not have a parent:\n");
	    PrintLocation(ep, stderr);
	    return;
	}
	if ((atval = FindAttValByName(ep, tok[1]))) {
	    OutputString(atval, fp, track_pos);
	}
    }

    /* Use an action, given transpec's SID.
     * Format: _action action */
    else if (StrEq(tok[0], "action")) {
	TranTByAction(e, tok[1], fp);
    }

    /* Number of child elements of this element.
     * Format: _nchild */
    else if (StrEq(tok[0], "nchild")) {
	if (ntok > 1) {
	    for (n=0,i=0; i<e->necont; i++)
		if (StrEq(e->econt[i]->gi, tok[1])) n++;
	}
	else n = e->necont;
	sprintf(buf, "%d", n);
	OutputString(buf, fp, track_pos);
    }

    /* number of 1st child's child elements (grandchildren from first child).
     * Format: _n1gchild */
    else if (StrEq(tok[0], "n1gchild")) {
	if (e->necont) {
	    sprintf(buf, "%d", e->econt[0]->necont);
	    OutputString(buf, fp, track_pos);
	}
    }

    /* Chase this element's pointers until we hit the named GI.
     * Do the action if it matches.
     * Format: _chasetogi gi action */
    else if (StrEq(tok[0], "chasetogi")) {
	if (ntok < 3) {
	    fprintf(stderr, "Error: Not enough args for _chasetogi.\n");
	    return;
	}
	actioni = atoi(tok[2]);
	if (actioni) ChaseIDRefs(e, tok[1], tok[2], fp);
    }

    /* Follow link to element pointed to, then do action.
     * Format: _followlink [attname] action. */
    else if (StrEq(tok[0], "followlink")) {
	char **s;
	if (ntok > 2) {
	    if ((atval = FindAttValByName(e, tok[1]))) {
		if ((ep = FindElemByID(atval))) {
		    TranTByAction(ep, tok[2], fp);
		    return;
		}
	    }
	    else fprintf(stderr, "Error: Did not find attr: %s.\n", tok[1]);
	    return;
	}
	GetIDREFnames();
	for (s=idrefs; *s; s++) {
	    /* is this IDREF attr set? */
	    if ((atval = FindAttValByName(e, *s))) {
		ntok = 0;
		tok = Split(atval, &ntok, S_STRDUP);
		/* we'll follow the first one... */
		if ((ep = FindElemByID(tok[0]))) {
		    TranTByAction(ep, tok[1], fp);
		    return;
		}
		else fprintf(stderr, "Error: Can not find elem for ID: %s.\n",
			tok[0]);
	    }
	}
	fprintf(stderr, "Error: Element does not have IDREF attribute set:\n");
	PrintLocation(e, stderr);
	return;
    }

    /* Starting at this element, decend tree (in-order), finding GI.
     * Do the action if it matches.
     * Format: _find args ... */
    else if (StrEq(tok[0], "find")) {
	Find(e, ntok, tok, fp);
    }

    /* Starting at this element's parent, decend tree (in-order), finding GI.
     * Do the action if it matches.
     * Format: _pfind args ... */
    else if (StrEq(tok[0], "pfind")) {
	Find(e->parent ? e->parent : e, ntok, tok, fp);
    }

    /* Content is supposed to be a list of IDREFs.  Follow each, doing action.
     * If 2 actions are specified, use 1st for the 1st ID, 2nd for the rest.
     * Format: _namelist action [action2] */
    else if (StrEq(tok[0], "namelist")) {
	int id;
	action1 = tok[1];
	if (ntok > 2) action = tok[2];
	else action = action1;
	for (i=0; i<e->ndcont; i++) {
	    n = 0;
	    tok = Split(e->dcont[i], &n, S_STRDUP);
	    for (id=0; id<n; id++) {
		if (fold_case)
		    for (cp=tok[id]; *cp; cp++)
			if (islower(*cp)) *cp = toupper(*cp);
		if ((e = FindElemByID(tok[id]))) {
		    if (id) TranTByAction(e, action, fp);
		    else TranTByAction(e, action1, fp);	/* first one */
		}
		else fprintf(stderr, "Error: Can not find ID: %s.\n", tok[id]);
	    }
	}
    }

    /* For each word in the element's content, do action.
     * Format: _eachcon action [action] */
    else if (StrEq(tok[0], "eachcon")) {
	int id;
	action1 = tok[1];
	if (ntok > 3) action = tok[2];
	else action = action1;
	for (i=0; i<e->ndcont; i++) {
	    n = 0;
	    tok = Split(e->dcont[i], &n, S_STRDUP|S_ALVEC);
	    for (id=0; id<n; id++) {
		each_C = tok[id];
		TranTByAction(e, action, fp);
	    }
	    free(*tok);
	}
    }
    /* For each word in the given attribute's value, do action.
     * Format: _eachatt attname action [action] */
    else if (StrEq(tok[0], "eachatt")) {
	int id;
	action1 = tok[2];
	if (ntok > 3) action = tok[3];
	else action = action1;
	if ((atval = FindAttValByName(e, tok[1]))) {
	    n = 0;
	    tok = Split(atval, &n, S_STRDUP|S_ALVEC);
	    for (id=0; id<n; id++) {
		each_A = tok[id];
		if (id) TranTByAction(e, action, fp);
		else TranTByAction(e, action1, fp);	/* first one */
	    }
	    free(*tok);
	}
    }

    /* Do action on this element if element has [relationship] with gi.
     * Format: _relation relationship gi action [action] */
    else if (StrEq(tok[0], "relation")) {
	if (ntok >= 4) {
	    if (!CheckRelation(e, tok[1], tok[2], tok[3], fp, RA_Current)) {
		/* action not done, see if alt action specified */
		if (ntok >= 5)
		    TranTByAction(e, tok[4], fp);
	    }
	}
    }

    /* Do action on followed element if element has [relationship] with gi.
     * Format: _followrel relationship gi action */
    else if (StrEq(tok[0], "followrel")) {
	if (ntok >= 4)
	    (void)CheckRelation(e, tok[1], tok[2], tok[3], fp, RA_Related);
    }

    /* Find element with matching ID and do action.  If action not specified,
     * choose the right one appropriate for its context.
     * Format: _id id [action] */
    else if (StrEq(tok[0], "id")) {
	if ((ep = FindElemByID(tok[1]))) {
	    if (ntok > 2) TranTByAction(ep, tok[2], fp);
	    else {
		t = FindTrans(ep, 0);
		TransElement(ep, fp, t);
	    }
	}
    }

    /* Set variable to value.
     * Format: _set name value */
    else if (StrEq(tok[0], "set")) {
	SetMappingNV(Variables, tok[1], tok[2]);
    }

    /* Do action if variable is set, optionally to value.
     * If not set, do nothing.
     * Format: _isset varname [value] action 
     * Format: _issete varname [value] action  --  expands value */
    else if (StrEq(tok[0], "isset") || StrEq(tok[0], "issete")) {
	if ((cp = FindMappingVal(Variables, tok[1]))) {
	    if (ntok == 3) TranTByAction(e, tok[2], fp);
	    else
	    if (ntok > 3)	{
	    	if ( StrEq(tok[0], "issete") )	{
			ExpandVariables(tok[2], buf, e);
			cp2 = buf;
		} else
			cp2 = tok[2];
	    	if ( !strcmp(cp, cp2))
			TranTByAction(e, tok[3], fp);
	    }
	}
    }

    /* Insert a node into the tree at start/end, pointing to action to perform.
     * Format: _insertnode S|E action */
    else if (StrEq(tok[0], "insertnode")) {
	actioni = atoi(tok[2]);
	if (*tok[1] == 'S') e->gen_trans[0] = actioni;
	else if (*tok[1] == 'E') e->gen_trans[1] = actioni;
    }

    /* Do an CALS DTD table spec for TeX or troff.  Looks through attributes
     * and determines what to output. "check" means to check consistency,
     * and print error messages.
     * This is (hopefully) the only hard-coded part of instant.
     *
     * This was originally written for the OSF DTDs and recoded by FLD for
     * CALS tables (since no one will ever use the OSF tables).  Although
     * TeX was addressed first, it seems that a fresh approach was required,
     * and so, tbl is the first to be really *fixed*.  Once tbl is stable,
     * and there is a need for TeX again, that part will be recoded.
     *
     * *Obsolete* form (viz, for TeX):
     *    Format: _calstable [clear|check|tex]
     *			  [cellstart|cellend|rowstart|rowend|top|bottom]
     *
     * New, good form:
     *
     *    Format: _calstable [tbl]
     *			  [tablestart|tableend|tablegroup|tablefoot|rowstart|
     *			   rowend|entrystart|entryend]
     */

    else if (StrEq(tok[0], "calstable")) {
	CALStable(e, fp, tok, ntok);
    }

    /* Do action if element's attr is set, optionally to value.
     * If not set, do nothing.
     * Format: _attval att [value] action */
    else if (StrEq(tok[0], "attval")) {
	if ((atval = FindAttValByName(e, tok[1]))) {
	    if (ntok == 3) TranTByAction(e, tok[2], fp);
	    else if (ntok > 3 && !strcmp(atval, tok[2]))
		TranTByAction(e, tok[3], fp);
	}
    }
    /* Same thing, but look at parent */
    else if (StrEq(tok[0], "pattval")) {
	if ((atval = FindAttValByName(e->parent, tok[1]))) {
	    if (ntok == 3) {
		TranTByAction(e, tok[2], fp);
	    }
	    if (ntok > 3 && !strcmp(atval, tok[2]))
		TranTByAction(e, tok[3], fp);
	}
    }

    /* Print each attribute and value for the current element, hopefully
     * in a legal sgml form: <elem-name att1="value1" att2="value2:> .
     * Format: _allatts */
    else if (StrEq(tok[0], "allatts")) {
	for (i=0; i<e->natts; i++) {
	    if (i != 0) putc(' ', fp);
	    fputs(e->atts[i].name, fp);
	    fputs("=\"", fp);
	    fputs(e->atts[i].sval, fp);
	    putc('"', fp);
	}
    }

    /* Print the element's input filename, and optionally, the line number.
     * Format: _infile [line] */
    else if (StrEq(tok[0], "infile")) {
	if (e->infile) {
	    if (ntok > 1 && !strcmp(tok[1], "root")) {
		strcpy(buf, e->infile);
		if ((cp = strrchr(buf, '.'))) *cp = EOS;
		fputs(buf, fp);
	    }
	    else {
		fputs(e->infile, fp);
		if (ntok > 1 && !strcmp(tok[1], "line"))
		    fprintf(fp, " %d", e->lineno);
	    }
	    return;
	}
	else fputs("input-file??", fp);
    }

    /* Get value of an environement variable */
    else if (StrEq(tok[0], "env")) {
	if (ntok > 1 && (cp = getenv(tok[1]))) {
	    OutputString(cp, fp, track_pos);
	}
    }

    /* Something unknown */
    else {
	fprintf(stderr, "Unknown special variable: %s\n", tok[0]);
	tt = e->trans;
	if (tt && tt->lineno)
	    fprintf(stderr, "Used in transpec, line %d\n", tt->lineno);
    }
    return;
}
Example #27
0
int main(int argc,                     /* number of arguments */
       char *argv[])                     /* list of arguments */
{
       ATTRIBUTES opt;
       int c;
        CSF_VS valueScale = VS_UNDEFINED;
       enum MODE { CLONE, EDIT, COPY, PRINT, SET } mode = CLONE;

       /* install application */
       if(InstallArgs(argc, argv, "(ecps)dR#C#i#P*x$y$l$a$(BLNOSDV)", 
          "mapattr", __DATE__))
              goto failure;
         OptNotSetAttr(&opt);

       while((c = GetOpt()) != 0)
       {
        switch(c)
        {
         case 'd': printDataType = TRUE; mode = PRINT; break;
         case 'e': mode = EDIT; break;
         case 'c': mode = COPY; break;
         case 'p': mode = PRINT; break;
         case 's': mode = SET; break;
         case 'R': 
            if (*((const int *)OptArg) <= 0)
            { Error("-R number of rows must be greater than 0 (not '%d)",
                     *((const int *)OptArg));
              goto failure;
            }
            opt.nrRows = *((const int *)OptArg); 
            break;
         case 'C': 
            if (*((const int *)OptArg) <= 0)
            { Error("-R number of columns must be greater than 0 (not '%d)",
                     *((const int *)OptArg));
              goto failure;
            }
            opt.nrCols = *((const int *)OptArg); 
            break;
         case 'i': 
            if (*((const int *)OptArg) < 0)
            { Error("-i file id must be >= 0 (not '%d)",
                     *((const int *)OptArg));
              goto failure;
            }
            opt.gisFileId = *((const int *)OptArg); 
            break;
         case 'P':
             if (StrEq("yt2b", (const char *)OptArg))
             {
                    opt.projection = PT_YINCT2B;
                    break;
             }
             if (StrEq("yb2t", (const char *)OptArg))
             {
                    opt.projection = PT_YDECT2B;
                    break;
             }
            Error("-P unknown projection '%s'",(const char *)OptArg);
            goto failure;
         case 'x': opt.xUL = *((const double *)OptArg); break;
         case 'y': opt.yUL = *((const double *)OptArg); break;
         case 'l': 
            if (*((const double *)OptArg) <= 0)
            { Error("-l cell length must be greater than 0 (not '%g)",
                     *((const double *)OptArg));
              goto failure;
            }
            opt.cellSize = *((const double *)OptArg); break;
         case 'a': 
            if ( (*((const double *)OptArg) < -90 )
                || (*((const double *)OptArg) > 90 ) )
            { Error("-a angle must be between -90 and 90 (not '%g)",
                     *((const double *)OptArg));
              goto failure;
            }
            opt.angle = *((const double *)OptArg); break;
#         include "case_vs.h"
       } /* eoswitch */
       } /* eowhile */
       if (valueScale != VS_UNDEFINED)
       {
         opt.valueScale = valueScale;
               opt.cellRepr = AppDefaultCellRepr(valueScale);
       }

       if ( (argv = ArgArguments(&argc)) == NULL)
              goto failure;

       if (AppArgCountCheck(argc,2,-1,USAGE))
              goto failure;

       switch(mode) {
        case PRINT: 
                    if (PrintOption((const char **)argv+1,argc-1))
                           goto failure;
                    break;
        case CLONE: if (argc != 2)
                    {
                     Error("Too many arguments, only one map allowed");
                     goto failure;
                    }
                    if (CloneOption(argv[1]))
                           goto failure;
                    break;
        case EDIT:  if (argc != 2)
                    {
                     Error("-e: Too many arguments, only one map allowed");
                     goto failure;
                    }
                    if (EditOption(argv[1]))
                           goto failure;
                    break;
       case COPY:
                    if (argc <= 2)
                    {
                     Error("-c: requires more than one map");
                     goto failure;
                    }
                    if (CopyOption((const char **)argv+1,argc-1))
                           goto failure;
                    break;
        case SET:
                    if (SetOption((const char **)argv+1,argc-1,&opt))
                           goto failure;
                    break;
       }

       AppEnd();
       exit(0);
       return 0;

failure:
       AppEnd();
       exit(1);
       return 1;
} /* main */
Example #28
0
static int
UpdateCfgStr(char *FileName,char *SectionName,char *VarWanted, char *NewData)
/*
** This will update a variable in a specific section in your .ini file.
** It will do so safely by copying it to a new file, and when finished,
** will delete the old one and rename the new one to the correct name.
** If any fatal error occurs, it will return a FALSE to indicate failure
** and TRUE to indicate success.  I generally don't care why it failed,
** just knowing that it failed is usually enough.
*/
{
 FILE *CfgFile,*NewCfgFile;
 char SectionWanted[LINE_INPUT_MAX];
 char line[LINE_INPUT_MAX];
 char var[LINE_INPUT_MAX];
 char data[LINE_INPUT_MAX];
 char TempFileName[MAX_FILENAME+1];
 int Status=TRUE;
 int Updated=FALSE;
 int InSection=FALSE;
 int BlankLines=0;

if (!CreateTempFileName(TempFileName))
  {
   DumpDebug("Unable to create a temporary filename to update %s\n",FileName);
   return FALSE;
  }

NewCfgFile=fopen(TempFileName,"w");
if (NewCfgFile==NULL)
  {
   DumpDebug("Unable to open a temporary file to update %s\n",TempFileName);
   return FALSE;
  }

sprintf(SectionWanted,"[%s]",SectionName);

CfgFile=fopen(FileName,"r");
if (CfgFile)
  {
   while (ReadLine(CfgFile,line))
      {
       if (StrEq(line,SectionWanted)) InSection=TRUE;
       else if (InSection && (line[0]=='['))
         {/* leaving our section */
           InSection=FALSE;
           if (!Updated) /* Variable wasn't found, we have to add it */
             {
              fprintf(NewCfgFile,"%s = %s\n",VarWanted,NewData);
              while (BlankLines) {fprintf(NewCfgFile,"\n");BlankLines--;}
              Updated=TRUE;
             }
         }
       if (line[0]=='\0') BlankLines++;
       else
         {
          while (BlankLines) {fprintf(NewCfgFile,"\n");BlankLines--;}
          ParseLine(line,var,data);
          if (InSection && StrEq(var,VarWanted) && !Updated)
            {
             fprintf(NewCfgFile,"%s = %s\n",var,NewData);
             Updated=TRUE;
            }
          else fprintf(NewCfgFile,"%s\n",line);
         }
      }
  }

/*
** Our section may not have even been there (or there wasn't already
** a config file) in which case we have to add both the variable and
** the section itself.
*/
if (!Updated)
  {  /* We may have hit EOF while still in our section. */
     /* If so, we don't need to add the section header. */
   if (!InSection)
     {
      if (BlankLines!=0) fprintf(NewCfgFile,"\n");
      fprintf(NewCfgFile,"%s\n",SectionWanted);
     }
   fprintf(NewCfgFile,"%s = %s\n",VarWanted,NewData);
  }

fprintf(NewCfgFile,"\n");

if (CfgFile && ferror(CfgFile))    Status=FALSE;
if (ferror(NewCfgFile)) Status=FALSE;
if (CfgFile) fclose(CfgFile);
fclose(NewCfgFile);

if (!Status) remove(TempFileName);
else
  {/*if (remove(FileName)) return FALSE;*/
   remove(FileName);
   if (rename(TempFileName,FileName)) return FALSE;
  }

return Status;
}
Example #29
0
int main(int argc, char *argv[])
{
    char fileName[256], oldwd[256], *command, *dimensions, *stringPtr;
    char prompt[512];
    char *inputText;
    NXname dataName;
    int status;

#if HAVE_LIBREADLINE
    rl_readline_name = "NXbrowse";
    rl_attempted_completion_function = nxbrowse_complete;
#if READLINE_VERSION >= 0x500
    rl_catch_signals = 0;
#else
#define rl_crlf() fprintf(rl_outstream, "\r\n");
#define rl_on_new_line() 1
#endif
    using_history();
#else
#define rl_crlf()
#define rl_on_new_line()
#define add_history(a)
#endif

    printf("NXBrowse %s Copyright (C) 2009-2014 NeXus Data Format\n",
           NEXUS_VERSION);
#if HAVE_LIBREADLINE
    printf
    ("Built with readline support - use <TAB> to complete commands and paths\n");
#endif				/* HAVE_LIBREADLINE */

    /* if there is a filename given on the command line use that,
          else ask for a filename */
    if (argc < 2) {
        printf("Give name of NeXus file : ");
        if (fgets(fileName, sizeof(fileName), stdin) == NULL) {
            printf("Failed to open %s\n", fileName);
            return NX_ERROR;
        }
        if ((stringPtr = strchr(fileName, '\n')) != NULL)
            *stringPtr = '\0';
    } else {
        strcpy(fileName, argv[1]);
    }
    strcpy(nxFile, fileName);

    /* Open input file and output global attributes */
    if (NXopen(fileName, NXACC_READ, &the_fileId) != NX_OK) {
        printf("NX_ERROR: Can't open %s\n", fileName);
        return NX_ERROR;
    }
    PrintAttributes(the_fileId);
    iByteAsChar = 0;	/* Display remaining NX_INT8 and NX_UINT8 variables as integers by default */
    /* Input commands until the EXIT command is given */
    strcpy(oldwd, "/");
    strcpy(path, "/");
    do {
        sprintf(prompt, "NX%s> ", path);
        if (getenv("NO_READLINE") != NULL) {
            inputText = my_readline(prompt);
        } else {
            inputText = readline(prompt);
        }
        if (inputText == NULL) {
            inputText = strdup("EXIT");
        }
        if (*inputText) {
            add_history(inputText);
        }
        command = strtok(inputText, " ");
        /* Check if a command has been given */
        if (command == NULL)
            command = " ";
        /* Convert it to upper case characters */
        ConvertUpperCase(command);

        if (StrEq(command, "PWD")) {
            fprintf(rl_outstream, "%s\n", path);
        }

        if (StrEq(command, "TEST")) {
            char a[256], b[256];
            stringPtr = strtok(NULL, " ");
            if (stringPtr != NULL) {
                parsepath(stringPtr, a, b);
                fprintf(rl_outstream," you entered >%s< - i think the full path is >%s< and the final component looks like this >%s<.\n", stringPtr, a, b);
            } else {
                fprintf(rl_outstream," you entered nothing\n");
            }
        }

        /* Command is to print a directory of the current group */
        if (StrEq(command, "DIR") || StrEq(command, "LS")) {
            stringPtr = strtok(NULL, " ");
            if (stringPtr != NULL) {
                char a[256], b[256];
                parsepath(stringPtr, a, b);
                strcat(a, "/");
                strcat(a, b);
                NXopengrouppath(the_fileId, a);
                NXBdir(the_fileId);
                NXopengrouppath(the_fileId, path);
            } else {
                NXBdir(the_fileId);
            }
        }

        /* Command is to open the specified group */
        if (StrEq(command, "OPEN") || StrEq(command, "CD")) {
            stringPtr = strtok(NULL, " ");
            if (stringPtr != NULL) {
                char a[256], b[256];

                if (StrEq(stringPtr, "-")) {
                    stringPtr = oldwd;
                }

                parsepath(stringPtr, a, b);
                strcat(a, "/");
                strcat(a, b);

                status = NXopengrouppath(the_fileId, a);

                if (status == NX_OK) {
                    strcpy(oldwd, path);
                    strcpy(path, a);
                } else {
                    fprintf(rl_outstream, "NX_ERROR: cannot change into %s\n", stringPtr);
                    NXopengrouppath(the_fileId, path); /* to be sure */
                }

            } else {
                fprintf(rl_outstream, "NX_ERROR: Specify a group\n");
            }
        }

        /* Command is to dump data values to a file */
        if (StrEq(command, "DUMP")) {
            stringPtr = strtok(NULL, " ");
            if (stringPtr != NULL) {
                strcpy(dataName, stringPtr);
                stringPtr = strtok(NULL, " ");
                if (stringPtr != NULL) {
                    strcpy(fileName, stringPtr);
                    status = NXBdump(the_fileId, dataName, fileName);
                } else {
                    fprintf(rl_outstream, "NX_ERROR: Specify a dump file name \n");
                }
            } else {
                fprintf(rl_outstream, "NX_ERROR: Specify a data item\n");
            }
        }
        /* Command is to print the values of the data */
        if (StrEq(command, "READ") || StrEq(command, "CAT")) {
            stringPtr = strtok(NULL, " [");
            if (stringPtr != NULL) {
                strcpy(dataName, stringPtr);
                dimensions = strtok(NULL, "[]");
                status =
                    NXBread(the_fileId, dataName, dimensions);
            } else {
                fprintf(rl_outstream,
                        "NX_ERROR: Specify a data item\n");
            }
        }
        /* Command is to close the current group */
        if (StrEq(command, "CLOSE")) {
            if (strlen(path) > 1) {
                if (NXclosegroup(the_fileId) == NX_OK) {
                    /* Remove the group from the prompt string */
                    strcpy(oldwd, path);
                    stringPtr = strrchr(path, '/');	/* position of last group delimiter */
                    if (stringPtr != NULL)
                        *stringPtr = '\0';	/* terminate the string there */
                }
            } else {
                fprintf(rl_outstream,
                        "NX_WARNING: Already at root level of file\n");
            }
        }
        /* Command is to print help information */
        if (StrEq(command, "HELP") || StrEq(command, "INFO")) {
            printf("NXbrowse commands : DIR\n");
            printf("                    LS\n");
            printf("                    OPEN <groupName>\n");
            printf("                    CD <groupName>\n");
            printf("                    READ <dataName>\n");
            printf("                    READ <dataName>[<dimension indices...>]\n");
            printf("                    DUMP <dataName> <fileName> \n");
            printf("                    CLOSE\n");
            printf("                    BYTEASCHAR\n");
            printf("                    HELP\n");
            printf("                    EXIT\n");
            printf("\n");
#if HAVE_LIBREADLINE
            printf("Pressing <TAB> after a command or partial nexus object name will complete\n");
            printf("possible names. For example:\n");
            printf("\n");
            printf("    cd ent<TAB KEY PRESSED>     # all items starting with ent are listed\n");
            printf("\n");
#endif
        }
        /* Command is to print byte as char information */
        if (StrEq(command, "BYTEASCHAR")) {
            if (iByteAsChar == 1)
                iByteAsChar = 0;
            else
                iByteAsChar = 1;
        }
        /* Command is to exit the program */
        if (StrEq(command, "EXIT") || StrEq(command, "QUIT")) {
            /* for (i = groupLevel; i > 0; i--) NXclosegroup (the_fileId); */
            NXclose(&the_fileId);
            return NX_OK;
        }
        status = NX_OK;
        free(inputText);
    } while (status == NX_OK);
    return NX_OK;
}
Example #30
0
static int
m_server_estab(aClient *cptr)
{
    aConnect *aconn;
    aClient *acptr;

    char       *inpath, *host, *s, *encr;

    inpath = get_client_name(cptr, HIDEME);  /* "refresh" inpath with host  */
    host = cptr->name;

    if (!(aconn = cptr->serv->aconn))
    {
        ircstp->is_ref++;
        sendto_one(cptr, "ERROR :Lost Connect block");
        sendto_ops_lev(ADMIN_LEV, "Lost Connect block for server %s",
                           get_client_name(cptr, TRUE));
        return exit_client(cptr, cptr, cptr, "Lost Connect block");
    }

    encr = cptr->passwd;
    if (*aconn->apasswd && !StrEq(aconn->apasswd, encr))
    {
        ircstp->is_ref++;
        sendto_one(cptr, "ERROR :Wrong link password");
        sendto_ops("Link %s dropped, wrong password", inpath);
        return exit_client(cptr, cptr, cptr, "Bad Password");
    }
    memset(cptr->passwd, '\0', sizeof(cptr->passwd));

    if ((acptr = find_client(host, NULL)))
    {
        /* Don't complain about juped servers */
        if(!IsULine(acptr) || find_aUserver(acptr->name))
        {
            sendto_gnotice("from %s: Link %s dropped, server already exists",
                           me.name, inpath);
            sendto_serv_butone(cptr, ":%s GNOTICE :Link %s dropped, server already"
                               " exists", me.name, inpath);
        }
        return exit_client(cptr, cptr, cptr, "Server Exists");
    }

    if(!(confopts & FLAGS_HUB))
    {
        int i;
        for (i = 0; i <= highest_fd; i++)
            if (local[i] && IsServer(local[i]))
            {
                ircstp->is_ref++;
                sendto_one(cptr, "ERROR :I'm a leaf not a hub");
                return exit_client(cptr, cptr, cptr, "I'm a leaf");
            }
    }

    /* aconf->port is a CAPAB field, kind-of. kludge. mm, mm. */
    /* no longer! this should still get better though */
    if((aconn->flags & CONN_ZIP))
        SetZipCapable(cptr);
    if((aconn->flags & CONN_DKEY))
        SetWantDKEY(cptr);
    if (IsUnknown(cptr))
    {
        if (aconn->cpasswd[0])
            sendto_one(cptr, "PASS %s :TS", aconn->cpasswd);

        /* Pass my info to the new server */

#ifdef HAVE_ENCRYPTION_ON
        if(!WantDKEY(cptr))
            sendto_one(cptr, "CAPAB SSJOIN NOQUIT BURST UNCONNECT ZIP "
                       "NICKIP NICKIPSTR TSMODE");
        else
            sendto_one(cptr, "CAPAB SSJOIN NOQUIT BURST UNCONNECT DKEY "
                       "ZIP NICKIP NICKIPSTR TSMODE");
#else
        sendto_one(cptr, "CAPAB SSJOIN NOQUIT BURST UNCONNECT ZIP NICKIP NICKIPSTR TSMODE");
#endif

        sendto_one(cptr, "SERVER %s 1 :%s",
                   my_name_for_link(me.name, aconn),
                   (me.info[0]) ? (me.info) : "IRCers United");
    }
    else 
    {
        s = (char *) strchr(aconn->host, '@');
        *s = '\0';      /* should never be NULL -- wanna bet? -Dianora */

        Debug((DEBUG_INFO, "Check Usernames [%s]vs[%s]", aconn->host,
               cptr->username));
        if (match(aconn->host, cptr->username))
        {
            *s = '@';
            ircstp->is_ref++;
            sendto_ops("Username mismatch [%s]v[%s] : %s",
                       aconn->host, cptr->username,
                       get_client_name(cptr, HIDEME));
            sendto_one(cptr, "ERROR :No Username Match");
            return exit_client(cptr, cptr, cptr, "Bad User");
        }
        *s = '@';
    }

    /* send routing notice, this should never happen anymore */
    if (!DoesTS(cptr))
    {
        sendto_gnotice("from %s: Warning: %s linked, non-TS server",
                       me.name, get_client_name(cptr, HIDEME));
        sendto_serv_butone(cptr,
                           ":%s GNOTICE :Warning: %s linked, non-TS server",
                           me.name, get_client_name(cptr, HIDEME));
    }

    sendto_one(cptr, "SVINFO %d %d 0 :%ld", TS_CURRENT, TS_MIN,
               (ts_val) timeofday);

    /* sendto one(cptr, "CAPAB ...."); moved to after PASS but before SERVER
     * now in two places.. up above and in s_bsd.c. - lucas
     * This is to make sure we pass on our capabilities before we establish
     * a server connection
     */

    /*
     * *WARNING*
     *   In the following code in place of plain
     * server's name we send what is returned by
     * get_client_name which may add the "sockhost" after the name.
     * It's *very* *important* that there is a SPACE between
     * the name and sockhost (if present). The receiving server
     * will start the information field from this first blank and
     * thus puts the sockhost into info. ...a bit tricky, but
     * you have been warned, besides code is more neat this way...
     * --msa
     */

    cptr->serv->up = me.name;
    cptr->serv->aconn = aconn;

    throttle_remove(cipntoa(cptr));

#ifdef HAVE_ENCRYPTION_ON
    if(!CanDoDKEY(cptr) || !WantDKEY(cptr))
        return do_server_estab(cptr);
    else
    {
        SetNegoServer(cptr); /* VERY IMPORTANT THAT THIS IS HERE */
        sendto_one(cptr, "DKEY START");
    }
#else
    return do_server_estab(cptr);
#endif

    return 0;
}