Ejemplo n.º 1
0
/*
 * Our "expect" function.
 */
int expect(char *text)
{
  char *s, *w;
  struct line **volatile seq;
  struct line oneline;
  struct line *dflseq[2];
  char *volatile toact = "exit 1";
  volatile int found = 0;
  int f, val, c;
  char *action = NULL;

  if (inexpect) {
    fprintf(stderr, _("script \"%s\" line %d: nested expect%s\n"),
            curenv->scriptname, thisline->lineno, "\r");
    exit(1);
  }
  etimeout = 120;
  inexpect = 1;

  s = getword(&text);
  if (!strcmp(s, "{")) {
    if (*text)
      syntaxerr(_("(garbage after {)"));
    thisline = thisline->next;
    seq = buildexpect();
  } else {
    oneline.line = s;
    oneline.next = NULL;
    dflseq[0] = &oneline;
    dflseq[1] = NULL;
    seq = dflseq;
  }
  /* Seek a timeout command */
  for (f = 0; seq[f]; f++) {
    if (!strncmp(seq[f]->line, "timeout", 7)) {
      c = seq[f]->line[7];
      if (c == 0 || (c != ' ' && c != '\t'))
        continue;
      s = seq[f]->line + 7;
      /* seq[f] = NULL; */
      skipspace(&s);
      w = getword(&s);
      if (w == NULL)
        syntaxerr(_("(argument expected)"));
      val = getnum(w);
      if (val == 0)
        syntaxerr(_("(invalid argument)"));
      etimeout = val;
      skipspace(&s);
      if (*s != 0)
        toact = s;
      break;
    }
  }
  if (sigsetjmp(ejmp, 1) != 0) {
    f = s_exec(toact);
    inexpect = 0;
    return f;
  }

  /* Allright. Now do the expect. */
  c = OK;
  while (!found) {
    action = NULL;
    readchar();
    for (f = 0; seq[f]; f++) {
      s = seq[f]->line;
      w = getword(&s);
      if (expfound(w)) {
        action = s;
        found = 1;
        break;
      }
    }
    if (action != NULL && *action) {
      found = 0;
      /* Maybe BREAK or RETURN */
      if ((c = s_exec(action)) != OK)
        found = 1;
    }
  }
  inexpect = 0;
  etimeout = 0;
  return c;
}
Ejemplo n.º 2
0
/*
 * parse the next request line
 * returns:
 *	1 ok
 *	0 eof
 *	-1 error
 */
int
hparsereq(HConnect *c, int timeout)
{
	Strings ss;
	char *vs, *v, *search, *uri, *origuri, *extra;

	if(c->bin != nil){
		hfail(c, HInternal);
		return -1;
	}

	/*
	 * serve requests until a magic request.
	 * later requests have to come quickly.
	 * only works for http/1.1 or later.
	 */
	if(timeout)
		alarm(timeout);
	if(hgethead(c, 0) < 0)
		return -1;
	if(timeout)
		alarm(0);
	c->reqtime = time(nil);
	c->req.meth = getword(c);
	if(c->req.meth == nil){
		hfail(c, HSyntax);
		return -1;
	}
	uri = getword(c);
	if(uri == nil || strlen(uri) == 0){
		hfail(c, HSyntax);
		return -1;
	}
	v = getword(c);
	if(v == nil){
		if(strcmp(c->req.meth, "GET") != 0){
			hfail(c, HUnimp, c->req.meth);
			return -1;
		}
		c->req.vermaj = 0;
		c->req.vermin = 9;
	}else{
		vs = v;
		if(strncmp(vs, "HTTP/", 5) != 0){
			hfail(c, HUnkVers, vs);
			return -1;
		}
		vs += 5;
		c->req.vermaj = strtoul(vs, &vs, 10);
		if(*vs != '.' || c->req.vermaj != 1){
			hfail(c, HUnkVers, vs);
			return -1;
		}
		vs++;
		c->req.vermin = strtoul(vs, &vs, 10);
		if(*vs != '\0'){
			hfail(c, HUnkVers, vs);
			return -1;
		}

		extra = getword(c);
		if(extra != nil){
			hfail(c, HSyntax);
			return -1;
		}
	}

	/*
	 * the fragment is not supposed to be sent
	 * strip it 'cause some clients send it
	 */
	origuri = uri;
	uri = strchr(origuri, '#');
	if(uri != nil)
		*uri = 0;

	/*
	 * http/1.1 requires the server to accept absolute
	 * or relative uri's.  convert to relative with an absolute path
	 */
	if(http11(c)){
		ss = parseuri(c, origuri);
		uri = ss.s1;
		c->req.urihost = ss.s2;
		if(uri == nil){
			hfail(c, HBadReq, uri);
			return -1;
		}
		origuri = uri;
	}

	/*
	 * munge uri for search, protection, and magic
	 */
	ss = stripsearch(origuri);
	origuri = ss.s1;
	search = ss.s2;
	uri = hurlunesc(c, origuri);
	uri = abspath(c, uri, "/");
	if(uri == nil || uri[0] == '\0'){
		hfail(c, HNotFound, "no object specified");
		return -1;
	}

	c->req.uri = uri;
	c->req.search = search;
	if(search)
		c->req.searchpairs = hparsequery(c, hstrdup(c, search));

	return 1;
}
Ejemplo n.º 3
0
int getEntries( inStruct Sentries ) {
    register int x;
    char *stquery, *tmpq, *tmpStr, *tmpStr1, *tmpPtr;
    char reqMethod[100];
    int msgLength;
    char contentType[100];
    char boundary[MAX_TOKEN];
    int i;


    putenv( "HOME=/" );


    if ( getenv( "CONTENT_TYPE" ) != NULL ) {
        strcpy( contentType, getenv( "CONTENT_TYPE" ) );
    }
    else {
        strcpy( contentType, "" );
    }
    if ( getenv( "REQUEST_METHOD" ) != NULL ) {
        strcpy( reqMethod, getenv( "REQUEST_METHOD" ) );
    }
    else {
        strcpy( reqMethod, "" );
    }
    if ( getenv( "HTTP_COOKIE" ) != NULL ) {
        strcpy( Sentries->cookieStr, getenv( "HTTP_COOKIE" ) );
    }

    else {
        strcpy( Sentries->cookieStr, "" );
    }
    if ( strstr( Sentries->cookieStr, "*" ) != NULL ||
            strstr( Sentries->cookieStr, ".." ) != NULL ||
            strstr( Sentries->cookieStr, "?" ) != NULL ||
            strstr( Sentries->cookieStr, "/" ) != NULL ||
            strstr( Sentries->cookieStr, "\\" ) != NULL ) {

        Sentries->op = -1;
        return 1;


    }


    if ( !strcmp( reqMethod, "POST" ) || !strcmp( reqMethod, "post" ) ) {
        msgLength = atoi( getenv( "CONTENT_LENGTH" ) ) + 10;
        stquery =  malloc( msgLength );
        if ( fread( stquery, 1, msgLength, stdin ) != ( msgLength - 10 ) ) {
            webErrorExit( "short fread", 0 );
        }
        stquery[msgLength] = '\0';
    }
    else {
        stquery =  malloc( QSIZE );
        if ( getenv( "QUERY_STRING" ) != NULL ) {
            strcpy( stquery, getenv( "QUERY_STRING" ) );
        }
        else {
            strcpy( stquery, "" );
        }
    }

    if ( strstr( contentType, "multipart/form-data" ) != NULL ) {

        i = msgLength - 10;
        getBoundary( &stquery, boundary );
        /***     printf("Boundary:**%s**<BR>\n",boundary);fflush(stdout); ***/
        for ( x = 0;  *stquery != '\0'; x++ ) {
            if ( x == MAX_ENTRIES ) {
                webErrorExit( "MaxEntries Exceeded", x );
            }
            Sentries->m = x;
            /***     printf("GettingX:%i....\n",x);fflush(stdout); ***/
            tmpPtr = stquery;
            if ( getmultipartword( &Sentries->entries[x], &stquery, boundary, i ) != 0 ) {
                break;
            }
            i -= stquery - tmpPtr;
            /***     printf("%i:%s=%s<BR>\n",entries[x].size,entries[x].name,entries[x].val);fflush(stdout);***/
        }
        Sentries->m--;
    }
    else {

        /**  the following is to take care of the
         home col. name bad length pb Linux on RedHat7  *******/
        fixstr1 = malloc( 10 );
        free( fixstr1 );
        /******************************************************/

        for ( x = 0;  stquery[0] != '\0'; x++ ) {
            if ( x == MAX_ENTRIES ) {
                webErrorExit( "MaxEntries Exceeded", x );
            }
            Sentries->m = x;
            Sentries->entries[x].val =  malloc( HUGE_STRING );
            getword( Sentries->entries[x].val, stquery, '&' );
            plustospace( Sentries->entries[x].val );
            unescape_url( Sentries->entries[x].val );
            char* wd = ( char * ) makeword( Sentries->entries[x].val, '=' ); // JMC cppcheck - leak
            sprintf( Sentries->entries[x].name, wd );
            free( wd ); // JMC cppcheck - leak
        }
    }

    return 0;

}
Ejemplo n.º 4
0
int
fight(int enemy, int strength)
{
	int lifeline;
	int hurt;
	char auxbuf[LINELENGTH];
	char *next;
	int i;
	int exhaustion;

	exhaustion = lifeline = 0;
fighton:
	gtime++;
	snooze -= 5;
	if (snooze > gtime)
		exhaustion = CYCLE / (snooze - gtime);
	else {
		puts("You collapse exhausted, and he pulverizes your skull.");
		die(0);
	}
	if (snooze - gtime < 20)
		puts("You look tired! I hope you're able to fight.");
	next = getcom(auxbuf, LINELENGTH, "<fight!>-: ", 0);
	for (i = 0; next && i < 10; i++)
		next = getword(next, words[i], -1);
	parse();
	switch (wordvalue[wordnumber]) {
	case KILL:
	case SMITE:
		if (testbit(inven, TWO_HANDED))
			hurt = rnd(70) - 2 * card(injuries, NUMOFINJURIES) -
			    ucard(wear) - exhaustion;
		else if (testbit(inven, SWORD) || testbit(inven, BROAD))
			hurt = rnd(50) % (WEIGHT - carrying) -
			    card(injuries, NUMOFINJURIES) - encumber -
			    exhaustion;
		else if (testbit(inven, KNIFE) || testbit(inven, MALLET) ||
		    testbit(inven, CHAIN) || testbit(inven, MACE) ||
		    testbit(inven, HALBERD))
			hurt = rnd(15) - card(injuries, NUMOFINJURIES) -
			    exhaustion;
		else
			hurt = rnd(7) - encumber;
		if (hurt < 5)
			switch (rnd(3)) {
			case 0:
				puts("You swung wide and missed.");
				break;
			case 1:
				puts("He checked your blow. CLASH! CLANG!");
				break;
			case 2:
				puts("His filthy tunic hangs by one less thread.");
				break;
			}
		else if (hurt < 10) {
			switch (rnd(3)) {
			case 0:
				puts("He's bleeding.");
				break;
			case 1:
				puts("A trickle of blood runs down his face.");
				break;
			case 2:
				puts("A huge purple bruise is forming on the side of his face.");
				break;
			}
			lifeline++;
		} else if (hurt < 20) {
			switch (rnd(3)) {
			case 0:
				puts("He staggers back quavering.");
				break;
			case 1:
				puts("He jumps back with his hand over the wound.");
				break;
			case 2:
				puts("His shirt falls open with a swath across the chest.");
				break;
			}
			lifeline += 5;
		} else if (hurt < 30) {
			switch (rnd(3)) {
			case 0:
				printf("A bloody gash opens up on his %s side.\n",
				    (rnd(2) ? "left" : "right"));
				break;
			case 1:
				puts("The steel bites home and scrapes along his ribs.");
				break;
			case 2:
				puts("You pierce him, and his breath hisses through clenched teeth.");
				break;
			}
			lifeline += 10;
		} else if (hurt < 40) {
			switch (rnd(3)) {
			case 0:
				puts("You smite him to the ground.");
				if (strength - lifeline > 20)
					puts("But in a flurry of steel he regains his feet!");
				break;
			case 1:
				puts("The force of your blow sends him to his knees.");
				puts("His arm swings lifeless at his side.");
				break;
			case 2:
				puts("Clutching his blood drenched shirt, he collapses stunned.");
				break;
			}
			lifeline += 20;
		} else {
			switch (rnd(3)) {
			case 0:
				puts("His ribs crack under your powerful swing, flooding his lungs with blood.");
				break;
			case 1:
				puts("You shatter his upheld arm in a spray of blood.  The blade continues deep");
				puts("into his back, severing the spinal cord.");
				lifeline += 25;
				break;
			case 2:
				puts("With a mighty lunge the steel slides in, and gasping, he falls to the ground.");
				lifeline += 25;
				break;
			}
			lifeline += 30;
		}
		break;

	case BACK:
		if (enemy == DARK && lifeline > strength * 0.33) {
			puts("He throws you back against the rock and pummels your face.");
			if (testbit(inven, AMULET) || testbit(wear, AMULET)) {
				printf("Lifting the amulet from you, ");
				if (testbit(inven, MEDALION) ||
				    testbit(wear, MEDALION)) {
					puts("his power grows and the walls of\nthe earth tremble.");
					puts("When he touches the medallion, your chest explodes and the foundations of the\nearth collapse.");
					puts("The planet is consumed by darkness.");
					die(0);
				}
				if (testbit(inven, AMULET)) {
					clearbit(inven, AMULET);
					carrying -= objwt[AMULET];
					encumber -= objcumber[AMULET];
				} else
					clearbit(wear, AMULET);
				puts("he flees down the dark caverns.");
				clearbit(location[position].objects, DARK);
				injuries[SKULL] = 1;
				followfight = gtime;
				return (0);
			} else {
				puts("I'm afraid you have been killed.");
				die(0);
			}
		} else {
			puts("You escape stunned and disoriented from the fight.");
			puts("A victorious bellow echoes from the battlescene.");
			if (back && position != back)
				battlestar_move(back, BACK);
			else if (ahead && position != ahead)
				battlestar_move(ahead, AHEAD);
			else if (left && position != left)
				battlestar_move(left, LEFT);
			else if (right && position != right)
				battlestar_move(right, RIGHT);
			else
				battlestar_move(location[position].down, AHEAD);
			return (0);
		}

	case SHOOT:
		if (testbit(inven, LASER)) {
			if (strength - lifeline <= 50) {
				printf("The %s took a direct hit!\n",
				    objsht[enemy]);
				lifeline += 50;
			} else {
				puts("With his bare hand he deflects the laser blast and whips the pistol from you!");
				clearbit(inven, LASER);
				setbit(location[position].objects, LASER);
				carrying -= objwt[LASER];
				encumber -= objcumber[LASER];
			}
		} else
			puts("Unfortunately, you don't have a blaster handy.");
		break;

	case DROP:
	case DRAW:
		cypher();
		gtime--;
		break;

	default:
		puts("You don't have a chance, he is too quick.");
		break;
	}
	if (lifeline >= strength) {
		printf("You have killed the %s.\n", objsht[enemy]);
		if (enemy == ELF || enemy == DARK)
			puts("A watery black smoke consumes his body and then vanishes with a peal of thunder!");
		clearbit(location[position].objects, enemy);
		power += 2;
		notes[JINXED]++;
		return (0);
	}
	puts("He attacks...");
	/* Some embellishments. */
	hurt = rnd(NUMOFINJURIES) - (testbit(inven, SHIELD) != 0) -
	    (testbit(wear, MAIL) != 0) - (testbit(wear, HELM) != 0);
	hurt += (testbit(wear, AMULET) != 0) +
	    (testbit(wear, MEDALION) != 0) + (testbit(wear, TALISMAN) != 0);
	hurt = hurt < 0 ? 0 : hurt;
	hurt = hurt >= NUMOFINJURIES ? NUMOFINJURIES - 1 : hurt;
	if (!injuries[hurt]) {
		injuries[hurt] = 1;
		printf("I'm afraid you have suffered %s.\n", ouch[hurt]);
	} else
		puts("You emerge unscathed.");
	if (injuries[SKULL] && injuries[INCISE] && injuries[NECK]) {
		puts("I'm afraid you have suffered fatal injuries.");
		die(0);
	}
	goto fighton;
}
Ejemplo n.º 5
0
static void
interpretXpm3ColorTableLine(char line[], int const seqNum, 
                            int const chars_per_pixel,
                            pixel * const colors, int * const ptab,
                            int * const transparentP) {
/*----------------------------------------------------------------------------
   Interpret one line of the color table in the XPM header.  'line' is
   the line from the XPM file.  It is the seqNum'th color table entry in
   the file.  The file uses 'chars_per_pixel' characters per pixel.

   Add the information from this color table entry to the color table
   'colors' and, if it isn't NULL, the corresponding lookup shadow table
   'ptab' (see readXpm3ColorTable for a description of these data 
   structures).

   The line may include values for multiple kinds of color (grayscale,
   color, etc.).  We take the highest of these (e.g. color over grayscale).

   If a color table entry indicates transparency, set *transparentP
   to the colormap index that corresponds to the indicated color.
-----------------------------------------------------------------------------*/
    /* Note: this code seems to allow for multi-word color specifications,
       but I'm not aware that such are legal.  Ultimately, ppm_parsecolor()
       interprets the name, and I believe it only takes single word 
       color specifications.  -Bryan 2001.05.06.
    */
    char str2[MAX_LINE+1];    
    char *t1;
    char *t2;
    int endOfEntry;   /* boolean */
    
    unsigned int curkey, key, highkey;	/* current color key */
    unsigned int lastwaskey;	
        /* The last token we processes was a key, and we have processed
           at least one token.
        */
    char curbuf[BUFSIZ];		/* current buffer */
    int isTransparent;
    
    int colorNumber;
        /* A color number that appears in the raster */
    /* read the chars */
    t1 = strchr(line, '"');
    if (t1 == NULL)
        pm_error("A line that is supposed to be an entry in the color "
                 "table does not start with a quote.  The line is '%s'.  "
                 "It is the %dth entry in the color table.", 
                 line, seqNum);
    else
        t1++;  /* Points now to first color number character */

    colorNumber = getNumber(t1, chars_per_pixel);
    t1 += chars_per_pixel;

    /*
     * read color keys and values 
     */
    curkey = 0; 
    highkey = 1;
    lastwaskey = FALSE;
    t2 = t1;
    endOfEntry = FALSE;
    while ( !endOfEntry ) {
        int isKey;   /* boolean */
        getword(str2, &t2);
        if (strlen(str2) == 0)
            endOfEntry = TRUE;
        else {
            /* See if the word we got is a valid key (and get its key
               number if so)
            */
            for (key = 1; 
                 key <= NKEYS && !STREQ(xpmColorKeys[key - 1], str2); 
                 key++);
            isKey = (key <= NKEYS);

            if (lastwaskey || !isKey) {
                /* This word is a color specification (or "none" for
                   transparent).
                */
                if (!curkey) 
                    pm_error("Missing color key token in color table line "
                             "'%s' before '%s'.", line, str2);
                if (!lastwaskey) 
                    strcat(curbuf, " ");		/* append space */
                if ( (strncmp(str2, "None", 4) == 0) 
                     || (strncmp(str2, "none", 4) == 0) ) {
                    /* This entry identifies the transparent color number */
                    strcat(curbuf, "#000000");  /* Make it black */
                    isTransparent = TRUE;
                } else 
                    strcat(curbuf, str2);		/* append buf */
                lastwaskey = 0;
            } else { 
                /* This word is a key.  So we've seen the last of the 
                   info for the previous key, and we must either put it
                   in the color map or ignore it if we already have a higher
                   color form in the colormap for this colormap entry.
                */
                if (curkey > highkey) {	/* flush string */
                    addToColorMap(seqNum, colorNumber, colors, ptab, curbuf,
                                  isTransparent, transparentP);
                    highkey = curkey;
                }
                curkey = key;			/* set new key  */
                curbuf[0] = '\0';		/* reset curbuf */
                isTransparent = FALSE;
                lastwaskey = 1;
            }
            if (*t2 == '"') break;
        }
    }
    /* Put the info for the last key in the line into the colormap (or
       ignore it if there's already a higher color form for this colormap
       entry in it)
    */
    if (curkey > highkey) {
        addToColorMap(seqNum, colorNumber, colors, ptab, curbuf,
                      isTransparent, transparentP);
        highkey = curkey;
    }
    if (highkey == 1) 
        pm_error("C error scanning color table");
}
Ejemplo n.º 6
0
INT32 GisLexAwkt::GetToken()
{
    // Save start position of the previous symbol
    m_cprev = m_cc;

    // Save previous token
    m_lastToken = m_token;

    // Get next not blank character
    m_ch = find_nonblank();

    // Stream is over
    if (m_ch == '\0')
    {
        m_token = GisToken_End;
        m_prevToken = m_token;
        return m_token;
    }

    // Is it keyword ?
    if (iswalpha(m_ch))
    {
        wchar_t     word[maxCharLength];

        // Get keyword
        getword(word, sizeof(word)/sizeof(wchar_t));

        // Is it a valid keyword for this grammar?
        INT32   tktmp;
        if ((tktmp = FindKeyWord(word, g_aAwktWords, AWKTKEYWORDCOUNT)) != GisToken_Undefined)
        {
            m_token = tktmp;
        }
        else
        {
            m_token = GisToken_Undefined;
        }
    }

    // Is it a numeric constant?
    else if (iswdigit(m_ch))
    {
        // m_token is real or integer number
        getnumber(false);
    }

    // negative values
    else if (m_ch == '-')
    {
        m_ch = if_getch();
        m_ch = find_nonblank();
        getnumber(true);
    }

    // comma
    else if (m_ch == ',')
    {
        m_token = GisToken_Comma;
        m_ch = if_getch();

    }
    // left parenthesis
    else if (m_ch == '(')
    {
        m_token = GisToken_LeftParenthesis;
        m_ch = if_getch();

    }
    // right parenthesis
    else if (m_ch == ')')
    {
        m_token = GisToken_RightParenthesis;
        m_ch = if_getch();
    }

    // something bad
    else
    {
        m_token = GisToken_Error;
        m_ch = if_getch();
    }

    m_prevToken = m_token;
    return m_token;
}
Ejemplo n.º 7
0
main(int argc, char *argv[]) {
    register int x,m=0;
    char *cl;
    char w[256];
    char tfile[L_tmpnam];
    int subs,slims,sides,drinks,allow;
    char name[32];
    char phone[10];
    char address[64];
    FILE *tfp,*order;

    printf("Content-type: text/html%c%c",LF,LF);

    cl=getenv("QUERY_STRING");
    if((!cl) || (!cl[0]))
        dump_form();

    tmpnam(tfile);
    if(!(tfp=fopen(tfile,"w"))) {
        printf("<TITLE>Server Error</TITLE>%c",LF);
        printf("<H1>Server Error</H1>%c",LF);
        printf("Server unable to get a temporary file. Please try again later.<P>%c",LF);
        exit(1);
    }

    subs=0;slims=0;sides=0;drinks=0;allow=0;
    name[0]='\0';
    phone[0]='\0';
    address[0]='\0';

    for(x=0;cl[0] != '\0'; x++) {
        m=x;
        getword(w,cl,'=');
        plustospace(w);
        unescape_url(w);
        if(!strcmp(w,"pwd")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            allow=(strcmp(w,PASSWORD) ? 0 : 1);
        }
        if(!strcmp(w,"sub")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            subs |= (1 << atoi(w));
        }
        else if(!strcmp(w,"slj")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            slims |= (1 << atoi(w));
        }
        else if(!strcmp(w,"sde")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            sides |= (1 << atoi(w));
        }
        else if(!strcmp(w,"pop")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            drinks |= (1 << atoi(w));
        }
        else if(!strcmp(w,"name")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            strcpy(name,w);
        }
        else if(!strcmp(w,"phone")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            strcpy(phone,w);
        }
        else if(!strcmp(w,"adr")) {
            getword(w,cl,'&');
            plustospace(w);
            unescape_url(w);
            strcpy(address,w);
        }
    }

    if(!name[0]) print_error("you didn't give your name");
    if(!address[0]) print_error("you didn't give your address");
    if(!phone[0]) print_error("you didn't give your phone number");
    if((!subs) && (!slims) && (!sides) && (!drinks)) print_error("you didn't order anything");

    if(allow) {
        char t[256];
        sprintf(t,"/bin/mail %s",JJ_FAX);
        if(!(order=popen(t,"w")))
            print_error("the server was unable to open a pipe to mail");
        printf("<TITLE>Order Sent</TITLE>%c",LF);
        printf("<H1>Order Sent</H1>%c",LF);
        printf("Your order has been sent to the UIUC e-mail to FAX gateway.<P>%c",LF);
    } else {
        printf("<TITLE>Your Order</TITLE>%c",LF);
        printf("<H1>Your Order</H1>%c",LF);
        printf("This is how your order would have looked if it had been sent.<P><PLAINTEXT>%c",LF);
        order=stdout;
    }

    fprintf(order,"My name is %s, and I would like to have the following%c",
            name,LF);
    fprintf(order,"order delivered to %s:%c%c",address,LF,LF);
    for(x=0;x<12;x++)
        if(subs & (1 << x))
            fprintf(order,"\t(1) %s%c",sublist[x],LF);
    for(x=0;x<6;x++)
        if(slims & (1 << x))
            fprintf(order,"\t(1) %s Slim Jim%c",slimlist[x],LF);
    for(x=0;x<2;x++)
        if(sides & (1 << x))
            fprintf(order,"\t(1) %s%c",sidelist[x],LF);
    for(x=0;x<4;x++)
        if(drinks & (1 << x))
            fprintf(order,"\t(1) %s%c",poplist[x],LF);
    fprintf(order,"%cPlease feel free to call me at %s if there is any%c",LF,
            phone,LF);
    fprintf(order,"problem. Thank you.%c%c.%c",LF,LF,LF);
    fclose(order);
    exit(0);
}
Ejemplo n.º 8
0
Archivo: n7.c Proyecto: 99years/plan9
void text(void)
{
	Tchar i;
	static int spcnt;

	nflush++;
	numtabp[HP].val = 0;
	if ((dip == d) && (numtabp[NL].val == -1)) {
		newline(1); 
		return;
	}
	setnel();
	if (ce || !fi) {
		nofill();
		return;
	}
	if (pendw)
		goto t4;
	if (pendt)
		if (spcnt)
			goto t2; 
		else 
			goto t3;
	pendt++;
	if (spcnt)
		goto t2;
	while ((cbits(i = GETCH())) == ' ') {
		spcnt++;
		numtabp[HP].val += sps;
		widthp = sps;
	}
	if (nlflg) {
t1:
		nflush = pendt = ch = spcnt = 0;
		callsp();
		return;
	}
	ch = i;
	if (spcnt) {
t2:
		tbreak();
		if (nc || wch)
			goto rtn;
		un += spcnt * sps;
		spcnt = 0;
		setnel();
		if (trap)
			goto rtn;
		if (nlflg)
			goto t1;
	}
t3:
	if (spread)
		goto t5;
	if (pendw || !wch)
t4:
		if (getword(0))
			goto t6;
	if (!movword())
		goto t3;
t5:
	if (nlflg)
		pendt = 0;
	adsp = adrem = 0;
	if (ad) {
		if (nwd == 1)
			adsp = nel; 
		else 
			adsp = nel / (nwd - 1);
		adsp = (adsp / HOR) * HOR;
		adrem = nel - adsp*(nwd-1);
	}
	brflg = 1;
	tbreak();
	spread = 0;
	if (!trap)
		goto t3;
	if (!nlflg)
		goto rtn;
t6:
	pendt = 0;
	ckul();
rtn:
	nflush = 0;
}
Ejemplo n.º 9
0
Archivo: n7.c Proyecto: 99years/plan9
void tbreak(void)
{
	int pad, k;
	Tchar *i, j;
	int resol;
	int un0 = un;

	trap = 0;
	if (nb)
		return;
	if (dip == d && numtabp[NL].val == -1) {
		newline(1);
		return;
	}
	if (!nc) {
		setnel();
		if (!wch)
			return;
		if (pendw)
			getword(1);
		movword();
	} else if (pendw && !brflg) {
		getword(1);
		movword();
	}
	*linep = dip->nls = 0;
	if (NROFF && dip == d)
		horiz(po);
	if (lnmod)
		donum();
	lastl = ne;
	if (brflg != 1) {
		totout = 0;
	} else if (ad) {
		if ((lastl = ll - un) < ne)
			lastl = ne;
	}
	if (admod && ad && (brflg != 2)) {
		lastl = ne;
		adsp = adrem = 0;
		if (admod == 1)
			un +=  quant(nel / 2, HOR);
		else if (admod == 2)
			un += nel;
	}
	totout++;
	brflg = 0;
	if (lastl + un > dip->maxl)
		dip->maxl = lastl + un;
	horiz(un);
	if (NROFF) {
		if (adrem % t.Adj)
			resol = t.Hor; 
		else 
			resol = t.Adj;
	} else
		resol = HOR;

	lastl = ne + (nwd-1) * adsp + adrem;
	for (i = line; nc > 0; ) {
		if ((cbits(j = *i++)) == ' ') {
			pad = 0;
			do {
				pad += width(j);
				nc--;
			} while ((cbits(j = *i++)) == ' ');
			i--;
			pad += adsp;
			--nwd;
			if (adrem) {
				if (adrem < 0) {
					pad -= resol;
					adrem += resol;
				} else if ((totout & 01) || adrem / resol >= nwd) {
					pad += resol;
					adrem -= resol;
				}
			}
			pchar((Tchar) WORDSP);
			horiz(pad);
		} else {
			pchar(j);
			nc--;
		}
	}
	if (ic) {
		if ((k = ll - un0 - lastl + ics) > 0)
			horiz(k);
		pchar(ic);
	}
	if (icf)
		icf++;
	else 
		ic = 0;
	ne = nwd = 0;
	un = in;
	setnel();
	newline(0);
	if (dip != d) {
		if (dip->dnl > dip->hnl)
			dip->hnl = dip->dnl;
	} else {
		if (numtabp[NL].val > dip->hnl)
			dip->hnl = numtabp[NL].val;
	}
	for (k = ls - 1; k > 0 && !trap; k--)
		newline(0);
	spread = 0;
}
Ejemplo n.º 10
0
static int do_wordexp(const char *s, wordexp_t *we, int flags)
{
	size_t i, l;
	int sq=0, dq=0;
	size_t np=0;
	char *w, **tmp;
	char *redir = (flags & WRDE_SHOWERR) ? "" : "2>/dev/null";
	int err = 0;
	FILE *f;
	size_t wc = 0;
	char **wv = 0;
	int p[2];
	pid_t pid;
	sigset_t set;

	if (flags & WRDE_REUSE) wordfree(we);

	if (flags & WRDE_NOCMD) for (i=0; s[i]; i++) switch (s[i]) {
	case '\\':
		if (!sq) i++;
		break;
	case '\'':
		if (!dq) sq^=1;
		break;
	case '"':
		if (!sq) dq^=1;
		break;
	case '(':
		if (np) {
			np++;
			break;
		}
	case ')':
		if (np) {
			np--;
			break;
		}
	case '\n':
	case '|':
	case '&':
	case ';':
	case '<':
	case '>':
	case '{':
	case '}':
		if (!(sq|dq|np)) return WRDE_BADCHAR;
		break;
	case '$':
		if (s[i+1]=='(' && s[i+2]=='(') {
			i += 2;
			np += 2;
			break;
		} else if (s[i+1] != '(') break;
	case '`':
		if (sq) break;
		return WRDE_CMDSUB;
	}

	if (flags & WRDE_APPEND) {
		wc = we->we_wordc;
		wv = we->we_wordv;
	}

	i = wc;
	if (flags & WRDE_DOOFFS) {
		if (we->we_offs > SIZE_MAX/sizeof(void *)/4)
			goto nospace;
		i += we->we_offs;
	} else {
		we->we_offs = 0;
	}

	if (pipe2(p, O_CLOEXEC) < 0) goto nospace;
	__block_all_sigs(&set);
	pid = fork();
	__restore_sigs(&set);
	if (pid < 0) {
		close(p[0]);
		close(p[1]);
		goto nospace;
	}
	if (!pid) {
		if (p[1] == 1) fcntl(1, F_SETFD, 0);
		else dup2(p[1], 1);
		execl("/bin/sh", "sh", "-c",
			"eval \"printf %s\\\\\\\\0 x $1 $2\"",
			"sh", s, redir, (char *)0);
		_exit(1);
	}
	close(p[1]);
	
	f = fdopen(p[0], "r");
	if (!f) {
		close(p[0]);
		kill(pid, SIGKILL);
		reap(pid);
		goto nospace;
	}

	l = wv ? i+1 : 0;

	free(getword(f));
	if (feof(f)) {
		fclose(f);
		reap(pid);
		return WRDE_SYNTAX;
	}

	while ((w = getword(f))) {
		if (i+1 >= l) {
			l += l/2+10;
			tmp = realloc(wv, l*sizeof(char *));
			if (!tmp) break;
			wv = tmp;
		}
		wv[i++] = w;
		wv[i] = 0;
	}
	if (!feof(f)) err = WRDE_NOSPACE;

	fclose(f);
	reap(pid);

	if (!wv) wv = calloc(i+1, sizeof *wv);

	we->we_wordv = wv;
	we->we_wordc = i;

	if (flags & WRDE_DOOFFS) {
		if (wv) for (i=we->we_offs; i; i--)
			we->we_wordv[i-1] = 0;
		we->we_wordc -= we->we_offs;
	}
	return err;

nospace:
	if (!(flags & WRDE_APPEND)) {
		we->we_wordc = 0;
		we->we_wordv = 0;
	}
	return WRDE_NOSPACE;
}
Ejemplo n.º 11
0
/**
 * main programme will be excuted.
 * By default, words are read from stdin and
 * added to hashtable before being printed out
 * alongside their frequencies to stdout.
 * @param argc an integer saying how many arguments
 *  there are argc for “argument count”
 * @param argv an array of strings in which the arguments
 *  are stored (argv for “argument vector ”).
 * @return integer 1 to indicate if the programme excuted successfully or not.
 */
int main(int argc, char *argv[]) {
    const char *optstring = "ht:c:deps:";
    char option;
    char word[256];
    int capacity = 113;

    FILE *infile = NULL;
    clock_t start, end;

    hashing_t method = LINEAR_P;

    double fillTime;
    double searchTime;

    int unknownWords = 0;
    int numOfSnapshot = 0;

    htable  h;
    char *fileToBeChecked = NULL;
    int withC = 0;
    int withE = 0;
    int withP = 0;
    int withS = 0;
    /*
     * Begin processing the argument from the command line
     */
    while ((option = getopt(argc, argv, optstring)) != EOF) {
        switch (option) {
            case 't':
                if (atoi(optarg) <= 0){
                    capacity = 113;
                }else {
                    capacity = primegt(atoi(optarg));
                }
                break;
            case 'd':
                method = DOUBLE_H;
                break;
            case 'c':
                withC = 1;
                fileToBeChecked = optarg;
                break;
            case 'e':
                withE = 1;
                break;
            case 's':
                numOfSnapshot = atoi(optarg);
                if (numOfSnapshot <= 0) {
                    numOfSnapshot = 10;
                }
                withS = 1;
                break;
            case 'p':
                withP = 1;
                break;
            case 'h':
                printHelpInfo();
                return EXIT_SUCCESS;
            default:
                printHelpInfo();
                return EXIT_FAILURE;
        }

    }

    h = htable_new(capacity, method);
    start = clock();

    while (getword(word, sizeof word, stdin) != EOF) {
        htable_insert(h, word);
    }

    end = clock();
    fillTime = (end-start)/(double)CLOCKS_PER_SEC;

    /* prints all the details of the table (-e argument)*/
    if (withE == 1) {
        htable_print_entire_table(h, stderr);
    }

    /* Checks the input file against a dictionary (-c <filename> argument)*/
    if (withC == 1) {
        /*open file and check if it is valid*/
        if (NULL == (infile = fopen(fileToBeChecked, "r"))) {
            fprintf(stderr, "Can't open file '%s' using mode r\n",
                    fileToBeChecked);
            htable_free(h);
            return EXIT_FAILURE;
        }
        start = clock();
        /*Get words from input file, and search for them in the dictionary*/
        while (getword(word, sizeof word, infile) != EOF) {
            /*If the word isn't in the dictionary*/
            if (htable_search(h, word) == 0) {
                printf("%s\n", word);
                unknownWords += 1;
            }
        }
        end = clock();
        fclose(infile);
        searchTime = (end-start)/(double)CLOCKS_PER_SEC;
        fprintf(stderr, "Fill time\t:%f\n", fillTime);
        fprintf(stderr, "Search time\t:%f\n", searchTime);
        fprintf(stderr, "Unknown words = %d\n", unknownWords);

        htable_free(h);
        return EXIT_SUCCESS;
    }


    /*Prints table stats (-p -s arguments)*/
    if (withP == 1 && withS == 0) {
        htable_print_stats(h, stdout, 10);
    } else if (withP == 1 && withS == 1) {
        htable_print_stats(h, stdout, numOfSnapshot);
    } else {
        htable_print(h, print_info);
    }

    htable_free(h);

    return EXIT_SUCCESS;
}
Ejemplo n.º 12
0
/*
 * scan_authfile - Scan an authorization file for a secret suitable
 * for authenticating `client' on `server'.  The return value is -1
 * if no secret is found, otherwise >= 0.  The return value has
 * NONWILD_CLIENT set if the secret didn't have "*" for the client, and
 * NONWILD_SERVER set if the secret didn't have "*" for the server.
 * Any following words on the line (i.e. address authorization
 * info) are placed in a wordlist and returned in *addrs.  
 */
static int
scan_authfile(FILE *f, char *client, char *server, u_int32_t ipaddr,
	      char *secret, struct wordlist **addrs, char *filename)
{
    int newline, xxx;
    int got_flag, best_flag;
    FILE *sf;
    struct wordlist *ap, *addr_list, *alist, *alast;
    char word[MAXWORDLEN];
    char atfile[MAXWORDLEN];
    char lsecret[MAXWORDLEN];

    if (addrs != NULL)
	*addrs = NULL;
    addr_list = NULL;
    if (!getword(f, word, &newline, filename))
	return -1;		/* file is empty??? */
    newline = 1;
    best_flag = -1;
    for (;;) {
	/*
	 * Skip until we find a word at the start of a line.
	 */
	while (!newline && getword(f, word, &newline, filename))
	    ;
	if (!newline)
	    break;		/* got to end of file */

	/*
	 * Got a client - check if it's a match or a wildcard.
	 */
	got_flag = 0;
	if (client != NULL && strcmp(word, client) != 0 && !ISWILD(word)) {
	    newline = 0;
	    continue;
	}
	if (!ISWILD(word))
	    got_flag = NONWILD_CLIENT;

	/*
	 * Now get a server and check if it matches.
	 */
	if (!getword(f, word, &newline, filename))
	    break;
	if (newline)
	    continue;
	if (server != NULL && strcmp(word, server) != 0 && !ISWILD(word))
	    continue;
	if (!ISWILD(word))
	    got_flag |= NONWILD_SERVER;

	/*
	 * Got some sort of a match - see if it's better than what
	 * we have already.
	 */
	if (got_flag <= best_flag)
	    continue;

	/*
	 * Get the secret.
	 */
	if (!getword(f, word, &newline, filename))
	    break;
	if (newline)
	    continue;

	/*
	 * Special syntax: @filename means read secret from file.
	 */
	if (word[0] == '@') {
	    strcpy(atfile, word+1);
	    if ((sf = fopen(atfile, "r")) == NULL) {
		syslog(LOG_WARNING, "can't open indirect secret file %s",
		       atfile);
		continue;
	    }
	    check_access(sf, atfile);
	    if (!getword(sf, word, &xxx, atfile)) {
		syslog(LOG_WARNING, "no secret in indirect secret file %s",
		       atfile);
		fclose(sf);
		continue;
	    }
	    fclose(sf);
	}
	if (secret != NULL)
	    strcpy(lsecret, word);

	/*
	 * Now read address authorization info and make a wordlist.
	 */
	alist = alast = NULL;
	for (;;) {
	    if (!getword(f, word, &newline, filename) || newline)
		break;
	    ap = (struct wordlist *) malloc(sizeof(struct wordlist)
					    + strlen(word));
	    if (ap == NULL)
		novm("authorized addresses");
	    ap->next = NULL;
	    strcpy(ap->word, word);
	    if (alist == NULL)
		alist = ap;
	    else
		alast->next = ap;
	    alast = ap;
	}

	/*
	 * Check if the given IP address is allowed by the wordlist.
	 */
	if (ipaddr != 0 && !ip_addr_check(ipaddr, alist)) {
	    free_wordlist(alist);
	    continue;
	}

	/*
	 * This is the best so far; remember it.
	 */
	best_flag = got_flag;
	if (addr_list)
	    free_wordlist(addr_list);
	addr_list = alist;
	if (secret != NULL)
	    strcpy(secret, lsecret);

	if (!newline)
	    break;
    }

    if (addrs != NULL)
	*addrs = addr_list;
    else if (addr_list != NULL)
	free_wordlist(addr_list);

    non_wildclient = (best_flag & NONWILD_CLIENT) && client != NULL &&
      *client != '\0';
    return best_flag;
}
Ejemplo n.º 13
0
int Parse_Matrix(FILE *ctlfile)
{
  int x,y;

  char temp[MAX_LINE],  /* Contains entire line */
       temp2[MAX_LINE], /* Temporary holding tank */
       p[MAX_LINE],     /* First word on line */
       *s2;

  linenum++;

  while (fgets(line,MAX_LINE,ctlfile))
  {
    Strip_Comment(line);

    if (*line)
    {
      strcpy(temp,line);

      getword(line,p,ctl_delim,1);

      if (! *p)
        ;
      else if (eqstri(p,"end"))
        break;
      else if (eqstri(p,"address"))
      {
        if (alias_count==ALIAS_CNT)
        {
          printf("\n\aToo many network addresses on line %d of CTL file!\n",
                 linenum);
          Compiling(-1,NULL,NULL);
        }
        else
        {
          getword(line,p,ctl_delim,2);

          prm.address[alias_count].zone=1;
          prm.address[alias_count].net=-1;
          prm.address[alias_count].node=-1;
          prm.address[alias_count].point=0;

          Parse_NetNode(p,&prm.address[alias_count].zone,
                        &prm.address[alias_count].net,
                        &prm.address[alias_count].node,
                        &prm.address[alias_count].point);

          alias_count++;
        }
      }
      else if (eqstri(p,"gate"))
        prm.flags2 |= FLAG2_gate;
      else if (eqstri(p,"path"))
      {
        getword(line,p,ctl_delim,2);

        if (eqstri(p,"netinfo"))
        {
          s2=fchar(line,ctl_delim,3);
          Make_Path(prm.net_info,s2);

          if (! direxist(strings+prm.net_info))
            makedir(strings+prm.net_info);
        }
        else Unknown_Ctl(linenum,p);
      }
      else if (eqstri(p,"fidouser"))
      {
        Make_Filename(prm.fidouser,fchar(line,ctl_delim,2));
      }
      else if (eqstri(p,"nodelist"))
      {
        getword(line,p,ctl_delim,2);

        if (eqstri(p,"version"))
        {
          getword(line,p,ctl_delim,3);

          if (eqstri(p, "5"))
            prm.nlver=NLVER_5;
          else if (eqstri(p, "6"))
            prm.nlver=NLVER_6;
          else if (eqstri(p, "7"))
            prm.nlver=NLVER_7;
          else if (eqstri(p, "fd"))
            prm.nlver=NLVER_FD;
          else Unknown_Ctl(linenum,p);
        }
        else Unknown_Ctl(linenum,p);
      }
      else if (eqstri(p,"log"))
      {
        getword(line,p,ctl_delim,2);

        if (eqstri(p,"echomail"))
        {
          prm.flags |= FLAG_log_echo;

          getword(line,p,ctl_delim,3);

          if (! *p)
          {
            printf("\n\aError!  No EchoToss filename specified on line %d of control file!\n",linenum);
            exit(1);
          }

          Make_Filename(prm.echotoss_name,p);
        }
        else Unknown_Ctl(linenum,p);
      }
      else if (eqstri(p,"after"))
      {
        getword(line,p,ctl_delim,2);

        if (eqstri(p,"edit"))
        {
          getword(line,p,ctl_delim,4);
          prm.edit_exit=(char)atoi(p);
        }
        else if (eqstri(p,"echomail"))
        {
          getword(line,p,ctl_delim,4);
          prm.echo_exit=(char)atoi(p);
        }
        else if (eqstri(p,"local"))
        {
          getword(line,p,ctl_delim,4);
          prm.local_exit=(char)atoi(p);
        }
        else Unknown_Ctl(linenum,p);
      }
      else if (eqstri(p,"message"))
      {
        getword(line,p,ctl_delim,2);

        if (eqstri(p,"show"))
        {
          getword(line,p,ctl_delim,3);
          getword(line,temp2,ctl_delim,5);

          if (eqstri(p,"ctl_a"))
            prm.ctla_priv=Deduce_Priv(temp2);
          else if (eqstri(p,"seenby"))
            prm.seenby_priv=Deduce_Priv(temp2);
          else if (eqstri(p,"private"))
            prm.pvt_priv=Deduce_Priv(temp2);
          else Unknown_Ctl(linenum,p);
        }
        else if (eqstri(p,"send"))
        {
          getword(line,p,ctl_delim,3);

          if (eqstri(p,"unlisted"))
          {
            getword(line,p,ctl_delim,4);
            prm.unlisted_priv=Deduce_Priv(p);

            getword(line,p,ctl_delim,5);
            prm.unlisted_cost=atoi(p);
          }
          else Unknown_Ctl(linenum,p);
        }
        else if (eqstri(p,"edit"))
        {
          getword(line,p,ctl_delim,3);

          if ((x=1,eqstri(p,"ask")) || (x=2,eqstri(p,"assume")))
          {
            getword(line,p,ctl_delim,4);

            if (x==1)   /* ASK */
            {
              x=Deduce_Attribute(p);
              getword(line,p,ctl_delim,5);
              if (x==-20 && (!p || !*p))
                prm.msg_localattach=0;
              else
              {
                y=Deduce_Priv(p);

                if (x==-22)      /* fromfile */
                  prm.msg_fromfile=y;
                else if (x==-20)
                  prm.msg_localattach=y;
                else
                  prm.msg_ask[x]=y;
              }
            }
            else        /* ASSUME */
            {
              x=Deduce_Attribute(p);

              getword(line,p,ctl_delim,5);
              if (x==-20 && (!p || !*p))
                prm.msg_localattach=0;
              else
              {
                y=Deduce_Priv(p);

                if (x==-22)     /* fromfile */
                  prm.msg_fromfile=y;
                else if (x==-20)
                  prm.msg_localattach=y;
                else
                  prm.msg_assume[x]=y;
              }
            }
          }
          else Unknown_Ctl(linenum,p);
        }
        else Unknown_Ctl(linenum,p);
      }
      else if (eqstri(p,"app") || eqstri(p,"application"))
        ;
      else Unknown_Ctl(linenum,p);
    }

    linenum++;
  }

  linenum++;

  return 0;
}
Ejemplo n.º 14
0
int main(int argc, char** argv) {
    int one = 1, client_fd;
    int rdlen;
    struct sockaddr_in svr_addr, cli_addr;
    socklen_t sin_len = sizeof (cli_addr);
    struct tm *u;
    char *f;
    time_t timer;
// Init DAC and SPI
    int ret = bcm2835_init();
    if (ret != 1) {
        fprintf(stderr, "Error in bcm2835_init()\n");
    

        return -1;
    }
    fprintf(stderr, "bcm2835_init()\n");

    ret = bcm2835_spi_begin();
    if (ret != 1) {
        fprintf(stderr, "Error in spi begin! ret code = %d\n", ret);

        return -1;
    }

    //setting SPI and CS
    bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_LSBFIRST);
    bcm2835_spi_setDataMode(BCM2835_SPI_MODE1);
    bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_1024);
    bcm2835_gpio_fsel(GPIO12, BCM2835_GPIO_FSEL_OUTP);
    bcm2835_gpio_write(GPIO12, HIGH);

    if ((argc >1) && (strncmp(argv[1], "init", 4) == 0)) {
        fprintf(stderr, "init 5790\n" );
        init_DAC();

    } else {
        fprintf(stderr, "start without init  5790\n" );

    }



    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
        err(1, "can't open socket");

    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof (int));


    svr_addr.sin_family = AF_INET;
    svr_addr.sin_addr.s_addr = INADDR_ANY;
    svr_addr.sin_port = htons(port);

    if (bind(sock, (struct sockaddr *) &svr_addr, sizeof (svr_addr)) == -1) {
        close(sock);
        err(1, "Can't bind");
	return 0;
    }
    double setval;
    uint16_t dsetval;

    listen(sock, 5);
    while (1) {
        client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);

//           printf("got connection\n");

        if (client_fd == -1) {
//            perror("Can't accept");
            continue;
        }

        timer = time(NULL);
        u = localtime(&timer);
        f = settime(u);
        printf("\n####################################\n %s",  f);
        rdlen = read(client_fd, answer, 2000);
                printf(" request: %s \n", answer);
        strstart = 0;
        strpos = 0;
        /*    nword = "";
         */
        getword();
        strcpy(metod, nword);
        getword();
        strcpy(uri, nword);
        getword();
        strcpy(protocol, nword);
        printf("metod='%s' uri='%s' protocol='%s'\n", metod, uri, protocol);
        memset(resp1, 0, 1100);
        strcpy(resp1, response);
        if (strncmp(uri, "/get", 4) == 0) {
            val = 123.876;
            sprintf(nword, "%f}", val);
            strcat(resp1, nword);
            printf("get=%s\n", nword);
        }

        if (strncmp(uri, "/setabs=", 7) == 0) {
            memset(nword, 0, 100);
            strncpy(nword, uri + 8, 20);
            strcat(resp1, nword);
            printf("setabs=%s\n", nword);
            long int  dsetval;
            dsetval=0;
            sscanf(nword,"%d",&dsetval);
            printf("setabs u = %d \n", dsetval);

//            double Vout = atof(argv[1]) - 1e-6;
//            printf("1 u =  \n");
//            long int DAC_code = 1048576.0*(Vout + VREFN) / (VREFP - VREFN);
//            printf("2 u = %d \n", DAC_code);
            long int DAC_code = dsetval;
            printf("3 dac code = %d \n", DAC_code);
            char msb[3] = {0};
            printf("4 u = %d \n", DAC_code);
            msb[0] = DAC_code / (256*256);
            msb[1] = (DAC_code - 256*256*msb[0])/256;
            msb[2] = (DAC_code - 256*256*msb[0] - 256*msb[1]);
            printf("5 u = %d \n", DAC_code);

            printf("msb = {%d %d %d}\n", msb[0], msb[1], msb[2]);

            set_V(msb);
        }

        write(client_fd, resp1, sizeof (resp1) - 1); /*-1:'\0'*/
        close(client_fd);
    }
}
Ejemplo n.º 15
0
int main(int argc, char *argv[]) {
	FILE *tfp,*f;
	char user[MAX_STRING_LEN];
	char line[MAX_STRING_LEN];
	char l[MAX_STRING_LEN];
	char w[MAX_STRING_LEN];
	char command[MAX_STRING_LEN];
	int found;

	tfd = -1;
	signal(SIGINT,(void (*)(int))interrupted);
	if(argc == 5) {
		if(strcmp(argv[1],"-c"))
			usage();
		if(!(tfp = fopen(argv[2],"w"))) {
			fprintf(stderr,"Could not open passwd file %s for writing.\n",
					argv[2]);
			perror("fopen");
			exit(1);
		}
	//	printf("Adding password for %s.\n",argv[3]);
		add_password(argv[3],tfp,argv[4]);
		fclose(tfp);
		exit(0);
	} else if(argc != 3) usage();

	tfd = mkstemp(temp_template);
	if(!(tfp = fdopen(tfd,"w"))) {
		fprintf(stderr,"Could not open temp file.\n");
		exit(1);
	}

	if(!(f = fopen(argv[1],"r"))) {
		fprintf(stderr,
				"Could not open passwd file %s for reading.\n",argv[1]);
		fprintf(stderr,"Use -c option to create new one.\n");
		exit(1);
	}
	strcpy(user,argv[2]);

	found = 0;
	while(!(getline(line,MAX_STRING_LEN,f))) {
		if(found || (line[0] == '#') || (!line[0])) {
			putline(tfp,line);
			continue;
		}
		strcpy(l,line);
		getword(w,l,':');
		if(strcmp(user,w)) {
			putline(tfp,line);
			continue;
		}
		else {
			printf("Changing password for user %s\n",user);
			add_password(user,tfp,argv[4]);
			found = 1;
		}
	}
	if(!found) {
		printf("Adding user %s\n",user);
		add_password(user,tfp,argv[4]);
	}
	fclose(f);
	fclose(tfp);
	sprintf(command,"cp %s %s",temp_template,argv[1]);
	system(command);
	unlink(temp_template);
	exit(0);
}
Ejemplo n.º 16
0
SAPI_API SAPI_POST_HANDLER_FUNC(suhosin_rfc1867_post_handler) /* {{{ */
{
	char *boundary, *s = NULL, *boundary_end = NULL, *start_arr = NULL, *array_index = NULL;
	char *lbuf = NULL, *abuf = NULL;
	zend_string *temp_filename = NULL;
	int boundary_len = 0, cancel_upload = 0, is_arr_upload = 0, array_len = 0;
	int64_t total_bytes = 0, max_file_size = 0;
	int skip_upload = 0, anonindex = 0, is_anonymous;
	HashTable *uploaded_files = NULL;
	multipart_buffer *mbuff;
	zval *array_ptr = (zval *) arg;
	int fd = -1;
	zend_llist header;
	void *event_extra_data = NULL;
	unsigned int llen = 0;
	int upload_cnt = INI_INT("max_file_uploads");
	const zend_encoding *internal_encoding = zend_multibyte_get_internal_encoding();
	php_rfc1867_getword_t getword;
	php_rfc1867_getword_conf_t getword_conf;
	php_rfc1867_basename_t _basename;
	zend_long count = 0;

	if (php_rfc1867_encoding_translation() && internal_encoding) {
		getword = php_rfc1867_getword;
		getword_conf = php_rfc1867_getword_conf;
		_basename = php_rfc1867_basename;
	} else {
		getword = php_ap_getword;
		getword_conf = php_ap_getword_conf;
		_basename = php_ap_basename;
	}

	if (SG(post_max_size) > 0 && SG(request_info).content_length > SG(post_max_size)) {
		sapi_module.sapi_error(E_WARNING, "POST Content-Length of " ZEND_LONG_FMT " bytes exceeds the limit of " ZEND_LONG_FMT " bytes", SG(request_info).content_length, SG(post_max_size));
		return;
	}

	/* Get the boundary */
	boundary = strstr(content_type_dup, "boundary");
	if (!boundary) {
		int content_type_len = (int)strlen(content_type_dup);
		char *content_type_lcase = estrndup(content_type_dup, content_type_len);

		php_strtolower(content_type_lcase, content_type_len);
		boundary = strstr(content_type_lcase, "boundary");
		if (boundary) {
			boundary = content_type_dup + (boundary - content_type_lcase);
		}
		efree(content_type_lcase);
	}

	if (!boundary || !(boundary = strchr(boundary, '='))) {
		sapi_module.sapi_error(E_WARNING, "Missing boundary in multipart/form-data POST data");
		return;
	}

	boundary++;
	boundary_len = (int)strlen(boundary);

	if (boundary[0] == '"') {
		boundary++;
		boundary_end = strchr(boundary, '"');
		if (!boundary_end) {
			sapi_module.sapi_error(E_WARNING, "Invalid boundary in multipart/form-data POST data");
			return;
		}
	} else {
		/* search for the end of the boundary */
		boundary_end = strpbrk(boundary, ",;");
	}
	if (boundary_end) {
		boundary_end[0] = '\0';
		boundary_len = boundary_end-boundary;
	}

	/* Initialize the buffer */
	if (!(mbuff = multipart_buffer_new(boundary, boundary_len))) {
		sapi_module.sapi_error(E_WARNING, "Unable to initialize the input buffer");
		return;
	}

	/* Initialize $_FILES[] */
	zend_hash_init(&PG(rfc1867_protected_variables), 8, NULL, NULL, 0);

	ALLOC_HASHTABLE(uploaded_files);
	zend_hash_init(uploaded_files, 8, NULL, free_filename, 0);
	SG(rfc1867_uploaded_files) = uploaded_files;

	if (Z_TYPE(PG(http_globals)[TRACK_VARS_FILES]) != IS_ARRAY) {
		/* php_auto_globals_create_files() might have already done that */
		array_init(&PG(http_globals)[TRACK_VARS_FILES]);
	}

	zend_llist_init(&header, sizeof(mime_header_entry), (llist_dtor_func_t) php_free_hdr_entry, 0);

	if (php_rfc1867_callback != NULL) {
		multipart_event_start event_start;

		event_start.content_length = SG(request_info).content_length;
		if (php_rfc1867_callback(MULTIPART_EVENT_START, &event_start, &event_extra_data) == FAILURE) {
			goto fileupload_done;
		}
	}

	while (!multipart_buffer_eof(mbuff))
	{
		char buff[FILLUNIT];
		char *cd = NULL, *param = NULL, *filename = NULL, *tmp = NULL;
		size_t blen = 0, wlen = 0;
		zend_off_t offset;

		zend_llist_clean(&header);

		if (!multipart_buffer_headers(mbuff, &header)) {
			goto fileupload_done;
		}

		if ((cd = php_mime_get_hdr_value(header, "Content-Disposition"))) {
			char *pair = NULL;
			int end = 0;

			while (isspace(*cd)) {
				++cd;
			}

			while (*cd && (pair = getword(mbuff->input_encoding, &cd, ';')))
			{
				char *key = NULL, *word = pair;

				while (isspace(*cd)) {
					++cd;
				}

				if (strchr(pair, '=')) {
					key = getword(mbuff->input_encoding, &pair, '=');

					if (!strcasecmp(key, "name")) {
						if (param) {
							efree(param);
						}
						param = getword_conf(mbuff->input_encoding, pair);
						if (mbuff->input_encoding && internal_encoding) {
							unsigned char *new_param;
							size_t new_param_len;
							if ((size_t)-1 != zend_multibyte_encoding_converter(&new_param, &new_param_len, (unsigned char *)param, strlen(param), internal_encoding, mbuff->input_encoding)) {
								efree(param);
								param = (char *)new_param;
							}
						}
					} else if (!strcasecmp(key, "filename")) {
						if (filename) {
							efree(filename);
						}
						filename = getword_conf(mbuff->input_encoding, pair);
						if (mbuff->input_encoding && internal_encoding) {
							unsigned char *new_filename;
							size_t new_filename_len;
							if ((size_t)-1 != zend_multibyte_encoding_converter(&new_filename, &new_filename_len, (unsigned char *)filename, strlen(filename), internal_encoding, mbuff->input_encoding)) {
								efree(filename);
								filename = (char *)new_filename;
							}
						}
					}
				}
				if (key) {
					efree(key);
				}
				efree(word);
			}

			/* Normal form variable, safe to read all data into memory */
			if (!filename && param) {
				size_t value_len;
				char *value = multipart_buffer_read_body(mbuff, &value_len);
				size_t new_val_len; /* Dummy variable */

				if (!value) {
					value = estrdup("");
					value_len = 0;
				}

				if (mbuff->input_encoding && internal_encoding) {
					unsigned char *new_value;
					size_t new_value_len;
					if ((size_t)-1 != zend_multibyte_encoding_converter(&new_value, &new_value_len, (unsigned char *)value, value_len, internal_encoding, mbuff->input_encoding)) {
						efree(value);
						value = (char *)new_value;
						value_len = new_value_len;
					}
				}

				if (++count <= PG(max_input_vars) && sapi_module.input_filter(PARSE_POST, param, &value, value_len, &new_val_len)) {
					if (php_rfc1867_callback != NULL) {
						multipart_event_formdata event_formdata;
						size_t newlength = new_val_len;

						event_formdata.post_bytes_processed = SG(read_post_bytes);
						event_formdata.name = param;
						event_formdata.value = &value;
						event_formdata.length = new_val_len;
						event_formdata.newlength = &newlength;
						if (php_rfc1867_callback(MULTIPART_EVENT_FORMDATA, &event_formdata, &event_extra_data) == FAILURE) {
							efree(param);
							efree(value);
							continue;
						}
						new_val_len = newlength;
					}
					safe_php_register_variable(param, value, new_val_len, array_ptr, 0);
				} else {
					if (count == PG(max_input_vars) + 1) {
						php_error_docref(NULL, E_WARNING, "Input variables exceeded " ZEND_LONG_FMT ". To increase the limit change max_input_vars in php.ini.", PG(max_input_vars));
					}

					if (php_rfc1867_callback != NULL) {
						multipart_event_formdata event_formdata;

						event_formdata.post_bytes_processed = SG(read_post_bytes);
						event_formdata.name = param;
						event_formdata.value = &value;
						event_formdata.length = value_len;
						event_formdata.newlength = NULL;
						php_rfc1867_callback(MULTIPART_EVENT_FORMDATA, &event_formdata, &event_extra_data);
					}
				}

				if (!strcasecmp(param, "MAX_FILE_SIZE")) {
#ifdef HAVE_ATOLL
					max_file_size = atoll(value);
#else
					max_file_size = strtoll(value, NULL, 10);
#endif
				}

				efree(param);
				efree(value);
				continue;
			}

			/* If file_uploads=off, skip the file part */
			if (!PG(file_uploads)) {
				skip_upload = 1;
			} else if (upload_cnt <= 0) {
				skip_upload = 1;
				sapi_module.sapi_error(E_WARNING, "Maximum number of allowable file uploads has been exceeded");
			}

			/* Return with an error if the posted data is garbled */
			if (!param && !filename) {
				sapi_module.sapi_error(E_WARNING, "File Upload Mime headers garbled");
				goto fileupload_done;
			}

			if (!param) {
				is_anonymous = 1;
				param = emalloc(MAX_SIZE_ANONNAME);
				snprintf(param, MAX_SIZE_ANONNAME, "%u", anonindex++);
			} else {
				is_anonymous = 0;
			}

			/* New Rule: never repair potential malicious user input */
			if (!skip_upload) {
				long c = 0;
				tmp = param;

				while (*tmp) {
					if (*tmp == '[') {
						c++;
					} else if (*tmp == ']') {
						c--;
						if (tmp[1] && tmp[1] != '[') {
							skip_upload = 1;
							break;
						}
					}
					if (c < 0) {
						skip_upload = 1;
						break;
					}
					tmp++;
				}
				/* Brackets should always be closed */
				if(c != 0) {
					skip_upload = 1;
				}
			}

			total_bytes = cancel_upload = 0;
			temp_filename = NULL;
			fd = -1;

			if (!skip_upload && php_rfc1867_callback != NULL) {
				multipart_event_file_start event_file_start;

				event_file_start.post_bytes_processed = SG(read_post_bytes);
				event_file_start.name = param;
				event_file_start.filename = &filename;
				if (php_rfc1867_callback(MULTIPART_EVENT_FILE_START, &event_file_start, &event_extra_data) == FAILURE) {
					temp_filename = NULL;
					efree(param);
					efree(filename);
					continue;
				}
			}

			if (skip_upload) {
				efree(param);
				efree(filename);
				continue;
			}

			if (filename[0] == '\0') {
#if DEBUG_FILE_UPLOAD
				sapi_module.sapi_error(E_NOTICE, "No file uploaded");
#endif
				cancel_upload = UPLOAD_ERROR_D;
			}

			offset = 0;
			end = 0;

			if (!cancel_upload) {
				/* only bother to open temp file if we have data */
				blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end);
#if DEBUG_FILE_UPLOAD
				if (blen > 0) {
#else
				/* in non-debug mode we have no problem with 0-length files */
				{
#endif
					fd = php_open_temporary_fd_ex(PG(upload_tmp_dir), "php", &temp_filename, 1);
					upload_cnt--;
					if (fd == -1) {
						sapi_module.sapi_error(E_WARNING, "File upload error - unable to create a temporary file");
						cancel_upload = UPLOAD_ERROR_E;
					}
				}
			}

			while (!cancel_upload && (blen > 0))
			{
				if (php_rfc1867_callback != NULL) {
					multipart_event_file_data event_file_data;

					event_file_data.post_bytes_processed = SG(read_post_bytes);
					event_file_data.offset = offset;
					event_file_data.data = buff;
					event_file_data.length = blen;
					event_file_data.newlength = &blen;
					if (php_rfc1867_callback(MULTIPART_EVENT_FILE_DATA, &event_file_data, &event_extra_data) == FAILURE) {
						cancel_upload = UPLOAD_ERROR_X;
						continue;
					}
				}

				if (PG(upload_max_filesize) > 0 && (zend_long)(total_bytes+blen) > PG(upload_max_filesize)) {
#if DEBUG_FILE_UPLOAD
					sapi_module.sapi_error(E_NOTICE, "upload_max_filesize of " ZEND_LONG_FMT " bytes exceeded - file [%s=%s] not saved", PG(upload_max_filesize), param, filename);
#endif
					cancel_upload = UPLOAD_ERROR_A;
				} else if (max_file_size && ((zend_long)(total_bytes+blen) > max_file_size)) {
#if DEBUG_FILE_UPLOAD
					sapi_module.sapi_error(E_NOTICE, "MAX_FILE_SIZE of " ZEND_LONG_FMT " bytes exceeded - file [%s=%s] not saved", max_file_size, param, filename);
#endif
					cancel_upload = UPLOAD_ERROR_B;
				} else if (blen > 0) {
#ifdef PHP_WIN32
					wlen = write(fd, buff, (unsigned int)blen);
#else
					wlen = write(fd, buff, blen);
#endif

					if (wlen == -1) {
						/* write failed */
#if DEBUG_FILE_UPLOAD
						sapi_module.sapi_error(E_NOTICE, "write() failed - %s", strerror(errno));
#endif
						cancel_upload = UPLOAD_ERROR_F;
					} else if (wlen < blen) {
#if DEBUG_FILE_UPLOAD
						sapi_module.sapi_error(E_NOTICE, "Only %d bytes were written, expected to write %d", wlen, blen);
#endif
						cancel_upload = UPLOAD_ERROR_F;
					} else {
						total_bytes += wlen;
					}
					offset += wlen;
				}

				/* read data for next iteration */
				blen = multipart_buffer_read(mbuff, buff, sizeof(buff), &end);
			}

			if (fd != -1) { /* may not be initialized if file could not be created */
				close(fd);
			}

			if (!cancel_upload && !end) {
#if DEBUG_FILE_UPLOAD
				sapi_module.sapi_error(E_NOTICE, "Missing mime boundary at the end of the data for file %s", filename[0] != '\0' ? filename : "");
#endif
				cancel_upload = UPLOAD_ERROR_C;
			}
#if DEBUG_FILE_UPLOAD
			if (filename[0] != '\0' && total_bytes == 0 && !cancel_upload) {
				sapi_module.sapi_error(E_WARNING, "Uploaded file size 0 - file [%s=%s] not saved", param, filename);
				cancel_upload = 5;
			}
#endif
			if (php_rfc1867_callback != NULL) {
				multipart_event_file_end event_file_end;

				event_file_end.post_bytes_processed = SG(read_post_bytes);
				event_file_end.temp_filename = ZSTR_VAL(temp_filename);
				event_file_end.cancel_upload = cancel_upload;
				if (php_rfc1867_callback(MULTIPART_EVENT_FILE_END, &event_file_end, &event_extra_data) == FAILURE) {
					cancel_upload = UPLOAD_ERROR_X;
				}
			}

			if (cancel_upload) {
				if (temp_filename) {
					if (cancel_upload != UPLOAD_ERROR_E) { /* file creation failed */
						unlink(ZSTR_VAL(temp_filename));
					}
					zend_string_release(temp_filename);
				}
				temp_filename = NULL;
			} else {
				zend_hash_add_ptr(SG(rfc1867_uploaded_files), temp_filename, temp_filename);
			}

			/* is_arr_upload is true when name of file upload field
			 * ends in [.*]
			 * start_arr is set to point to 1st [ */
			is_arr_upload =	(start_arr = strchr(param,'[')) && (param[strlen(param)-1] == ']');

			if (is_arr_upload) {
				array_len = (int)strlen(start_arr);
				if (array_index) {
					efree(array_index);
				}
				array_index = estrndup(start_arr + 1, array_len - 2);
			}

			/* Add $foo_name */
			if (llen < strlen(param) + MAX_SIZE_OF_INDEX + 1) {
				llen = (int)strlen(param);
				lbuf = (char *) safe_erealloc(lbuf, llen, 1, MAX_SIZE_OF_INDEX + 1);
				llen += MAX_SIZE_OF_INDEX + 1;
			}

			if (is_arr_upload) {
				if (abuf) efree(abuf);
				abuf = estrndup(param, strlen(param)-array_len);
				snprintf(lbuf, llen, "%s_name[%s]", abuf, array_index);
			} else {
				snprintf(lbuf, llen, "%s_name", param);
			}

			/* The \ check should technically be needed for win32 systems only where
			 * it is a valid path separator. However, IE in all it's wisdom always sends
			 * the full path of the file on the user's filesystem, which means that unless
			 * the user does basename() they get a bogus file name. Until IE's user base drops
			 * to nill or problem is fixed this code must remain enabled for all systems. */
			s = _basename(internal_encoding, filename);
			if (!s) {
				s = filename;
			}

			if (!is_anonymous) {
				safe_php_register_variable(lbuf, s, strlen(s), NULL, 0);
			}

			/* Add $foo[name] */
			if (is_arr_upload) {
				snprintf(lbuf, llen, "%s[name][%s]", abuf, array_index);
			} else {
				snprintf(lbuf, llen, "%s[name]", param);
			}
			register_http_post_files_variable(lbuf, s, &PG(http_globals)[TRACK_VARS_FILES], 0);
			efree(filename);
			s = NULL;

			/* Possible Content-Type: */
			if (cancel_upload || !(cd = php_mime_get_hdr_value(header, "Content-Type"))) {
				cd = "";
			} else {
				/* fix for Opera 6.01 */
				s = strchr(cd, ';');
				if (s != NULL) {
					*s = '\0';
				}
			}

			/* Add $foo_type */
			if (is_arr_upload) {
				snprintf(lbuf, llen, "%s_type[%s]", abuf, array_index);
			} else {
				snprintf(lbuf, llen, "%s_type", param);
			}
			if (!is_anonymous) {
				safe_php_register_variable(lbuf, cd, strlen(cd), NULL, 0);
			}

			/* Add $foo[type] */
			if (is_arr_upload) {
				snprintf(lbuf, llen, "%s[type][%s]", abuf, array_index);
			} else {
				snprintf(lbuf, llen, "%s[type]", param);
			}
			register_http_post_files_variable(lbuf, cd, &PG(http_globals)[TRACK_VARS_FILES], 0);

			/* Restore Content-Type Header */
			if (s != NULL) {
				*s = ';';
			}
			s = "";

			{
				/* store temp_filename as-is (in case upload_tmp_dir
				 * contains escapeable characters. escape only the variable name.) */
				zval zfilename;

				/* Initialize variables */
				add_protected_variable(param);

				/* if param is of form xxx[.*] this will cut it to xxx */
				if (!is_anonymous) {
					if (temp_filename) {
						ZVAL_STR_COPY(&zfilename, temp_filename);
					} else {
						ZVAL_EMPTY_STRING(&zfilename);
					}
					safe_php_register_variable_ex(param, &zfilename, NULL, 1);
				}

				/* Add $foo[tmp_name] */
				if (is_arr_upload) {
					snprintf(lbuf, llen, "%s[tmp_name][%s]", abuf, array_index);
				} else {
					snprintf(lbuf, llen, "%s[tmp_name]", param);
				}
				add_protected_variable(lbuf);
				if (temp_filename) {
					ZVAL_STR_COPY(&zfilename, temp_filename);
				} else {
					ZVAL_EMPTY_STRING(&zfilename);
				}
				register_http_post_files_variable_ex(lbuf, &zfilename, &PG(http_globals)[TRACK_VARS_FILES], 1);
			}

			{
				zval file_size, error_type;
				int size_overflow = 0;
				char file_size_buf[65];

				ZVAL_LONG(&error_type, cancel_upload);

				/* Add $foo[error] */
				if (cancel_upload) {
					ZVAL_LONG(&file_size, 0);
				} else {
					if (total_bytes > ZEND_LONG_MAX) {
#ifdef PHP_WIN32
						if (_i64toa_s(total_bytes, file_size_buf, 65, 10)) {
							file_size_buf[0] = '0';
							file_size_buf[1] = '\0';
						}
#else
						{
							int __len = snprintf(file_size_buf, 65, "%lld", total_bytes);
							file_size_buf[__len] = '\0';
						}
#endif
						size_overflow = 1;

					} else {
						ZVAL_LONG(&file_size, total_bytes);
					}
				}

				if (is_arr_upload) {
					snprintf(lbuf, llen, "%s[error][%s]", abuf, array_index);
				} else {
					snprintf(lbuf, llen, "%s[error]", param);
				}
				register_http_post_files_variable_ex(lbuf, &error_type, &PG(http_globals)[TRACK_VARS_FILES], 0);

				/* Add $foo_size */
				if (is_arr_upload) {
					snprintf(lbuf, llen, "%s_size[%s]", abuf, array_index);
				} else {
					snprintf(lbuf, llen, "%s_size", param);
				}
				if (!is_anonymous) {
					if (size_overflow) {
						ZVAL_STRING(&file_size, file_size_buf);
					}
					safe_php_register_variable_ex(lbuf, &file_size, NULL, size_overflow);
				}

				/* Add $foo[size] */
				if (is_arr_upload) {
					snprintf(lbuf, llen, "%s[size][%s]", abuf, array_index);
				} else {
					snprintf(lbuf, llen, "%s[size]", param);
				}
				if (size_overflow) {
					ZVAL_STRING(&file_size, file_size_buf);
				}
				register_http_post_files_variable_ex(lbuf, &file_size, &PG(http_globals)[TRACK_VARS_FILES], size_overflow);
			}
			efree(param);
		}
	}

fileupload_done:
	if (php_rfc1867_callback != NULL) {
		multipart_event_end event_end;

		event_end.post_bytes_processed = SG(read_post_bytes);
		php_rfc1867_callback(MULTIPART_EVENT_END, &event_end, &event_extra_data);
	}

	if (lbuf) efree(lbuf);
	if (abuf) efree(abuf);
	if (array_index) efree(array_index);
	zend_hash_destroy(&PG(rfc1867_protected_variables));
	zend_llist_destroy(&header);
	if (mbuff->boundary_next) efree(mbuff->boundary_next);
	if (mbuff->boundary) efree(mbuff->boundary);
	if (mbuff->buffer) efree(mbuff->buffer);
	if (mbuff) efree(mbuff);
}
Ejemplo n.º 17
0
int main(int argc, char * argv[]) {
    nameOfFile = argv[1];
    data = fopen(nameOfFile, "a+");
    if (data == NULL)
        perror("Error");
    phBook.size = 0;
    phBook.contact = malloc(phBook.size * sizeof(Note));
    freeInd.top = 0;
    freeInd.size = 1;
    freeInd.num = (int *)malloc(freeInd.size * sizeof(int));
    rewind(data);
    int id;
    while (fscanf(data, "%d ", &id) == 1) {
        phBook.size++;
        phBook.contact = realloc(phBook.contact, phBook.size * sizeof(Note));
        phBook.contact[phBook.size - 1].id = id;
        phBook.contact[phBook.size - 1].name = getword(data);
        phBook.contact[phBook.size - 1].nmbr = getword(data);
    }
    if (phBook.size == 0)
        currentID = 1;
    else
        currentID = phBook.contact[phBook.size - 1].id + 1;
    char *cmd, *name, *number, *input;
    while (42) {
        cmd = getword(stdin);
        if (!strcmp(cmd, "find")) {
            input = getword(stdin);
            if (inputIsCorrect(input))
                find(input);
            free(input);
        }
        else if (!strcmp(cmd, "create")) {
            name = getword(stdin);
            number = getword(stdin);
            if (inputIsCorrect(name) && inputIsCorrect(number))
                create(name, number);
        }
        else if (!strcmp(cmd, "delete")) {
            scanf("%d\n", &id);
            del(id);
        }
        else if (!strcmp(cmd, "change")) {
            scanf("%d ", &id);
            cmd = getword(stdin);
            input = getword(stdin);
            if (inputIsCorrect(input))
                change(id, cmd, input);
            free(input);
        }
        else if (!strcmp(cmd, "exit")) {
            fclose(data);
            free(phBook.contact);
            free(freeInd.num);
            return 0;
        }
        else {
            printf("Unknown command.\n");
        }
        free(cmd);
        fflush(stdout);
    }
}
Ejemplo n.º 18
0
/*read jpeg tables (huffman and quantization)
* args: 
*      till: Marker (frame - SOF0   scan - SOS)
*      isDHT: flag indicating the presence of huffman tables (if 0 must use default ones - MJPG frame)
*/
static int readtables(struct ctx* ctx,int till, int *isDHT)
{
	int m, l, i, j, lq, pq, tq;
	int tc, th, tt;

	for (;;) 
	{
		if (getbyte(ctx)!= 0xff)
			return -1;
		if ((m = getbyte(ctx)) == till)
			break;

		switch (m) 
		{
			case 0xc2:
				return 0;
			/*read quantization tables (Lqt and Cqt)*/
			case M_DQT:
				lq = getword(ctx);
				while (lq > 2) 
				{
					pq = getbyte(ctx);
					/*Lqt=0x00   Cqt=0x01*/
					tq = pq & 15;
					if (tq > 3)
					return -1;
					pq >>= 4;
					if (pq != 0)
					return -1;
					for (i = 0; i < 64; i++)
						ctx->quant[tq][i] = getbyte(ctx);
					lq -= 64 + 1;
				}
				break;
			/*read huffman table*/
			case M_DHT:
				l = getword(ctx);
				while (l > 2) 
				{
					int hufflen[16], k;
					uint8_t huffvals[256];

					tc = getbyte(ctx);
					th = tc & 15;
					tc >>= 4;
					tt = tc * 2 + th;
					if (tc > 1 || th > 1)
					return -1;
					
					for (i = 0; i < 16; i++)
						hufflen[i] = getbyte(ctx);
					l -= 1 + 16;
					k = 0;
					for (i = 0; i < 16; i++) 
					{
						for (j = 0; j < hufflen[i]; j++)
							huffvals[k++] = getbyte(ctx);
						l -= hufflen[i];
					}
					dec_makehuff(ctx->dhuff + tt, hufflen, huffvals);
				}
				/* has huffman tables defined (JPEG)*/
				*isDHT= 1;
				break;
			/*restart interval*/
			case M_DRI:
				l = getword(ctx);
				ctx->info.dri = getword(ctx);
				break;

			default:
				l = getword(ctx);
				while (l-- > 2)
					getbyte(ctx);
				break;
		}
	}
	return 0;
}
Ejemplo n.º 19
0
Archivo: melody.c Proyecto: rdebath/sgt
static void read_stream_control (MelodyLine *ml) {
    MelodyEvent *me = mmalloc (sizeof(MelodyEvent));
    StreamControl *sc = &me->u.s;      /* for ease of access */
    int c;
    char *p, *str = NULL;

    me->type = EV_STREAM;
    me->line = line_no;
    me->col = col_no;
    sc->text = NULL;

    switch (c = nd_gc()) {
      case 'Z':	
	gc();
	sc->type = SC_ZERONOTE;
	break;
      case '[':
	gc();
	sc->type = SC_BEAMSTART;
	break;
      case ']':
	gc();
	sc->type = SC_BEAMSTOP;
	if (nd_gc() == '-') {
	    gc();
	    if (nd_gc() != '[') {
		error (me->line, me->col, "syntax error in melody line:"
		       " expected `[' after `]-'");
		return;
	    }
	    sc->type = SC_BEAMBREAK;
	    gc();
	}
	break;
      case '/':
	gc();
	sc->type = SC_SLURSTART;
	break;
      case '\\':
	gc();
	sc->type = SC_SLURSTOP;
	break;
      case '(':
	gc();
	sc->type = SC_NTUPLET;
	sc->ntuplet_denom = 0;
	while ( (c=gc()) >= '0' && c <= '9')
	    sc->ntuplet_denom = (10*sc->ntuplet_denom) + c-'0';
	if (c != '/') {
	    error (me->line, me->col,
		   "expected `/' after numerator of n-tuplet");
	    return;
	}
	sc->ntuplet_num = 0;
	while ( (c=gc()) >= '0' && c <= '9')
	    sc->ntuplet_num = (10*sc->ntuplet_num) + c-'0';
	if (c != ':') {
	    error (me->line, me->col,
		   "expected `:' after denominator of n-tuplet");
	    return;
	}
	wrk.factor = lcm (wrk.factor, sc->ntuplet_denom);
	break;
      case ')':
	gc();
	sc->type = SC_NTUPLET_END;
	break;
      case '<':
	gc();
	/* Could be <p>, <d>, <8va>, <8vb>, <,>, </>, <~> */
	switch (c = gc()) {
	  case 'P':
	    sc->type = SC_FORCE_DOWN;
	    break;
	  case 'D':
	    sc->type = SC_FORCE_UP;
	    break;
	  case '8':
	    if (gc() != 'V') {
		error (me->line, me->col, "syntax error in melody line:"
		       " expected `v' after `<8'");
		return;
	    }
	    c = gc();
	    if (c == 'A')
		sc->type = SC_8VA;
	    else if (c == 'B')
		sc->type = SC_8VB;
	    else {
		error (me->line, me->col, "syntax error in melody line:"
		       " expected `a' or `b' after `<8v'");
		return;
	    }
	    break;
	  case ',':
	    sc->type = SC_BREATH;
	    break;
	  case '/':
	    sc->type = SC_GENPAUSE;
	    break;
	  case 'U':
	    if (nd_gc() == '!') {
		sc->type = SC_INVTURN;
		gc();
	    } else
		sc->type = SC_TURN;
	    break;
	  default:
	    error (me->line, me->col, "syntax error in melody line:"
		   " expected `p', `d', `8', `,', `/' or `u' after `<'");
	    return;
	}
	if (gc() != '>') {
	    error (me->line, me->col, "syntax error in melody line:"
		   " expected `>' to end `<...>' control");
	    return;
	}
	break;
      case '"':
	/* It's some kind of quoted string; get it into memory first. */
	getword (&str);
	/* Check if the string is actually empty. */
	if (!str[0] || !str[1] || str[1] == '"') {
	    error (me->line, me->col, "quoted string is empty");
	    return;
	}
	/* Check the second character, because it's general. */
	if (str[1] != '<' && str[1] != '>' && str[2] != ' ') {
	    error (me->line, me->col,
		   "expected space in quoted string after `%c'", str[1]);
	    return;
	}
	/* Remove the trailing quote. */
	str[strlen(str)-1] = '\0';
	/* Could be dynamics, lyrics, above or below text, cresc or dim. */
	switch (str[1]) {
	  case '<': case '>':
	    /* cresc or dim */
	    if (str[2]) {
		error (me->line, me->col,
		       "unexpected text after `%c' in quoted string", str[0]);
		return;
	    }
	    sc->type = (str[1] == '<' ? SC_CRESC : SC_DIM);
	    break;
	  case 'D': case 'd':
	    /* dynamics */
	    p = str+3;
	    while (*p && !isspace(*p)) {
		static const char *const dynamic_str = "fmpsz";
		char *q = strchr(dynamic_str, *p);
		if (!q) {
		    error (me->line, me->col,
			   "character `%c' not a valid dynamic", *p);
		    return;
		}
		*p++ = q - dynamic_str + '\xD1';
	    }
	    sc->type = SC_DYNAMIC;
	    sc->text = dupstr (str+3);
	    break;
	  case 'L': case 'l': case 'A': case 'a': case 'B': case 'b':
	    sc->text = dupstr (str+3);
	    sc->type = (str[1]=='L' || str[1]=='l' ? SC_LYRICS :
			str[1]=='A' || str[1]=='a' ? SC_TEXT_ABOVE :
			str[1]=='B' || str[1]=='b' ? SC_TEXT_BELOW : -1);
	    break;
	}
	break;
      default:			       /* should never happen */
	gc();
	fatal(me->line, me->col, "internal fault: reached `default'"
	      " clause in `read_stream_control': char %d", c);
	break;			       /* *certainly* shouldn't reach this! */
    }
    add_event (ml, me);
    mfree (str);
}
Ejemplo n.º 20
0
/*jpeg decode
* args: 
*      pic:  pointer to picture data ( decoded image - yuyv format)
*      buf:  pointer to input data ( compressed jpeg )
*      with: picture width 
*      height: picture height
*/
int jpeg_decode(uint8_t *pic, int stride, uint8_t *buf, int width, int height)
{
	struct ctx ctx;
	struct jpeg_decdata *decdata;
	int i=0, j=0, m=0, tac=0, tdc=0;
	int intwidth=0, intheight=0;
	int mcusx=0, mcusy=0, mx=0, my=0;
	int ypitch=0 ,xpitch=0,x=0,y=0;
	int mb=0;
	int max[6];
	ftopict convert;
	int err = 0;
	int isInitHuffman = 0;
	decdata = (struct jpeg_decdata*) calloc(1, sizeof(struct jpeg_decdata));
	
	for(i=0;i<6;i++) 
		max[i]=0;
	
	if (!decdata) 
	{
		err = -1;
		goto error;
	}
	if (buf == NULL) 
	{
		err = -1;
		goto error;
	}
	ctx.datap = buf;
	/*check SOI (0xFFD8)*/
	if (getbyte(&ctx) != 0xff) 
	{
		err = ERR_NO_SOI;
		goto error;
	}
	if (getbyte(&ctx) != M_SOI) 
	{
		err = ERR_NO_SOI;
		goto error;
	}
	/*read tables - if exist, up to start frame marker (0xFFC0)*/
	if (readtables(&ctx,M_SOF0, &isInitHuffman)) 
	{
		err = ERR_BAD_TABLES;
		goto error;
	}
	getword(&ctx);     /*header lenght*/
	i = getbyte(&ctx); /*precision (8 bit)*/
	if (i != 8) 
	{
		err = ERR_NOT_8BIT;
		goto error;
	}
	intheight = getword(&ctx); /*height*/
	intwidth = getword(&ctx);  /*width */

	if ((intheight & 7) || (intwidth & 7)) /*must be even*/
	{
		err = ERR_BAD_WIDTH_OR_HEIGHT;
		goto error;
	}
	ctx.info.nc = getbyte(&ctx); /*number of components*/
	if (ctx.info.nc > MAXCOMP) 
	{
		err = ERR_TOO_MANY_COMPPS;
		goto error;
	}
	/*for each component*/
	for (i = 0; i < ctx.info.nc; i++) 
	{
		int h, v;
		ctx.comps[i].cid = getbyte(&ctx); /*component id*/
		ctx.comps[i].hv = getbyte(&ctx);
		v = ctx.comps[i].hv & 15; /*vertical sampling   */
		h = ctx.comps[i].hv >> 4; /*horizontal sampling */
		ctx.comps[i].tq = getbyte(&ctx); /*quantization table used*/
		if (h > 3 || v > 3) 
		{
			err = ERR_ILLEGAL_HV;
			goto error;
		}
		if (ctx.comps[i].tq > 3) 
		{
			err = ERR_QUANT_TABLE_SELECTOR;
			goto error;
		}
	}
	/*read tables - if exist, up to start of scan marker (0xFFDA)*/ 
	if (readtables(&ctx,M_SOS,&isInitHuffman)) 
	{
		err = ERR_BAD_TABLES;
		goto error;
	}
	getword(&ctx); /* header lenght */
	ctx.info.ns = getbyte(&ctx); /* number of scans */
	if (!ctx.info.ns)
	{
	ALOGE("info ns %d/n",ctx.info.ns);
		err = ERR_NOT_YCBCR_221111;
		goto error;
	}
	/*for each scan*/
	for (i = 0; i < ctx.info.ns; i++) 
	{
		ctx.dscans[i].cid = getbyte(&ctx); /*component id*/
		tdc = getbyte(&ctx);
		tac = tdc & 15; /*ac table*/
		tdc >>= 4;      /*dc table*/
		if (tdc > 1 || tac > 1) 
		{
			err = ERR_QUANT_TABLE_SELECTOR;
			goto error;
		}
		for (j = 0; j < ctx.info.nc; j++)
			if (ctx.comps[j].cid == ctx.dscans[i].cid)
				break;
		if (j == ctx.info.nc) 
		{
			err = ERR_UNKNOWN_CID_IN_SCAN;
			goto error;
		}
		ctx.dscans[i].hv = ctx.comps[j].hv;
		ctx.dscans[i].tq = ctx.comps[j].tq;
		ctx.dscans[i].hudc.dhuff = dec_huffdc + tdc;
		ctx.dscans[i].huac.dhuff = dec_huffac + tac;
	}

	i = getbyte(&ctx); /*0 */
	j = getbyte(&ctx); /*63*/
	m = getbyte(&ctx); /*0 */

	if (i != 0 || j != 63 || m != 0) 
	{
		ALOGE("hmm FW error,not seq DCT ??\n");
	}
	
	/*build huffman tables*/
	if(!isInitHuffman) 
	{
		if(huffman_init(&ctx) < 0)
			return -ERR_BAD_TABLES;
	}
	/*
	if (ctx->dscans[0].cid != 1 || ctx->dscans[1].cid != 2 || ctx->dscans[2].cid != 3) 
	{
		err = ERR_NOT_YCBCR_221111;
		goto error;
	}

	if (ctx->dscans[1].hv != 0x11 || ctx->dscans[2].hv != 0x11) 
	{
		err = ERR_NOT_YCBCR_221111;
		goto error;
	}
	*/
	/* if internal width and external are not the same or heigth too 
	and pic not allocated realloc the good size and mark the change 
	need 1 macroblock line more ?? */
	if (intwidth > width || intheight > height) 
	{
		return -ERR_BAD_WIDTH_OR_HEIGHT;
#if 0		
		width = intwidth;
		height = intheight;
		// BytesperPixel 2 yuyv , 3 rgb24 
		*pic = (uint8_t*) realloc( *pic, intwidth * (intheight + 8) * 2);
#endif
	}

	switch (ctx.dscans[0].hv) 
	{
		case 0x22: // 411
			mb=6;
			mcusx = width >> 4;
			mcusy = height >> 4;

			xpitch = 16 * 2;

			ypitch = 16 * stride;
			convert = yuv420pto422; //choose the right conversion function
			break;
		case 0x21: //422
			mb=4;
			mcusx = width >> 4;
			mcusy = height >> 3;

			xpitch = 16 * 2;

			ypitch = 8 * stride;
			convert = yuv422pto422; //choose the right conversion function
			break;
		case 0x11: //444
			mcusx = width >> 3;
			mcusy = height >> 3;

			xpitch = 8 * 2;

			ypitch = 8 * stride;
			if (ctx.info.ns==1) 
			{
				mb = 1;
				convert = yuv400pto422; //choose the right conversion function
			}
			else 
			{
				mb=3;
				convert = yuv444pto422; //choose the right conversion function
			}
			break;
		default:
			err = ERR_NOT_YCBCR_221111;
			goto error;
			break;
	}

	idctqtab(ctx.quant[ctx.dscans[0].tq], decdata->dquant[0]);
	idctqtab(ctx.quant[ctx.dscans[1].tq], decdata->dquant[1]);
	idctqtab(ctx.quant[ctx.dscans[2].tq], decdata->dquant[2]);
	setinput(&ctx.in, ctx.datap);
	dec_initscans(&ctx);

	ctx.dscans[0].next = 2;
	ctx.dscans[1].next = 1;
	ctx.dscans[2].next = 0;	/* 4xx encoding */
	for (my = 0,y=0; my < mcusy; my++,y+=ypitch) 
	{
		for (mx = 0,x=0; mx < mcusx; mx++,x+=xpitch) 
		{
			if (ctx.info.dri && !--ctx.info.nm)
				if (dec_checkmarker(&ctx)) 
				{
					err = ERR_WRONG_MARKER;
					goto error;
				}
			switch (mb)
			{
				case 6: 
					decode_mcus(&ctx.in, decdata->dcts, mb, ctx.dscans, max);
					idct(decdata->dcts, decdata->out, decdata->dquant[0],
						IFIX(128.5), max[0]);
					idct(decdata->dcts + 64, decdata->out + 64,
						decdata->dquant[0], IFIX(128.5), max[1]);
					idct(decdata->dcts + 128, decdata->out + 128,
						decdata->dquant[0], IFIX(128.5), max[2]);
					idct(decdata->dcts + 192, decdata->out + 192,
						decdata->dquant[0], IFIX(128.5), max[3]);
					idct(decdata->dcts + 256, decdata->out + 256,
						decdata->dquant[1], IFIX(0.5), max[4]);
					idct(decdata->dcts + 320, decdata->out + 320,
						decdata->dquant[2], IFIX(0.5), max[5]);
					break;
					
				case 4:
					decode_mcus(&ctx.in, decdata->dcts, mb, ctx.dscans, max);
					idct(decdata->dcts, decdata->out, decdata->dquant[0],
						IFIX(128.5), max[0]);
					idct(decdata->dcts + 64, decdata->out + 64,
						decdata->dquant[0], IFIX(128.5), max[1]);
					idct(decdata->dcts + 128, decdata->out + 256,
							decdata->dquant[1], IFIX(0.5), max[4]);
					idct(decdata->dcts + 192, decdata->out + 320,
						decdata->dquant[2], IFIX(0.5), max[5]);
					break;
					
				case 3:
					decode_mcus(&ctx.in, decdata->dcts, mb, ctx.dscans, max);
					idct(decdata->dcts, decdata->out, decdata->dquant[0],
						IFIX(128.5), max[0]);    
					idct(decdata->dcts + 64, decdata->out + 256,
						decdata->dquant[1], IFIX(0.5), max[4]);
					idct(decdata->dcts + 128, decdata->out + 320,
						decdata->dquant[2], IFIX(0.5), max[5]);
					break;
					
				case 1:
					decode_mcus(&ctx.in, decdata->dcts, mb, ctx.dscans, max);
					idct(decdata->dcts, decdata->out, decdata->dquant[0],
						IFIX(128.5), max[0]);
					break;
			} // switch enc411
			convert(decdata->out,pic+y+x,stride); //convert to 422
		}
	}

	m = dec_readmarker(&ctx.in);
	if (m != M_EOI) 
	{
		err = ERR_NO_EOI;
		goto error;
	}
	free(decdata);
	return 0;
error:
	free(decdata);
	return err;
}
Ejemplo n.º 21
0
static int
parse_config(gnc_t gnc, void *closure)
{
    int c;
    char *token;

    c = gnc(closure);
    if(c < 2)
        return -1;

    while(c >= 0) {
        c = skip_whitespace(c, gnc, closure);
        if(c == '\n' || c == '#') {
            c = skip_to_eol(c, gnc, closure);
            continue;
        }
        if(c < 0)
            break;
        c = getword(c, &token, gnc, closure);
        if(c < -1)
            return -1;

        if(strcmp(token, "mode") == 0) {
            char *mtoken;

            c = getword(c, &mtoken, gnc, closure);
            if(c < -1)
                return -1;

            if(strcmp(mtoken, "server") == 0) {
#ifndef NO_SERVER
                client_config = 0;
                if(!server_config)
                    server_config = calloc(1, sizeof(struct server_config));
                if(!server_config)
                    return -1;
#else
                return -1;
#endif
            } else if(strcmp(mtoken, "client") == 0) {
                if(server_config)
                    return -1;
                client_config = 1;
            } else if(strcmp(mtoken, "forwarder") == 0) {
                if(server_config)
                    return -1;
                client_config = 0;
            } else {
                return -1;
            }

            free(mtoken);

            c = skip_eol(c, gnc, closure);
            if(c < -1)
                return -1;
        } else if(strcmp(token, "lease-dir") == 0) {
            char *dir;

            if(!server_config)
                return -1;

            c = getstring(c, &dir, gnc, closure);
            if(c < -1)
                return -1;

            if(dir[0] != '/')
                return -1;

            server_config->lease_dir = dir;
            c = skip_eol(c, gnc, closure);
            if(c < -1)
                return -1;
        } else if(strcmp(token, "prefix") == 0) {
            char *ptoken;
            struct prefix_list *prefix;

            if(!server_config)
                return -1;

            c = getword(c, &ptoken, gnc, closure);
            if(c < -1)
                return -1;

            prefix = parse_prefix(ptoken, PREFIX);

            if(prefix == NULL || prefix->n != 1)
                return -1;

            if(prefix_list_v4(prefix)) {
                unsigned const char zeroes[4] = {0};
                unsigned mask, first, last;
                if(memcmp(server_config->lease_first, zeroes, 4) != 0)
                    return -1;
                mask = 0xFFFFFFFF << (128 - prefix->l[0].plen);
                first =
                    (prefix->l[0].p[12] << 24 |
                     prefix->l[0].p[13] << 16 |
                     prefix->l[0].p[14] << 8 |
                     prefix->l[0].p[15] ) & mask;
                last = first | (~ mask);
                first = htonl(first + 1);
                last = htonl(last - 1);
                memcpy(server_config->lease_first, &first, 4);
                memcpy(server_config->lease_last, &last, 4);
                free(prefix);
            } else {
                server_config->ipv6_prefix =
                    cat_prefix_list(server_config->ipv6_prefix,
                                    prefix);
            }
            free(ptoken);
            c = skip_eol(c, gnc, closure);
            if(c < -1)
                return -1;
        } else if(strcmp(token, "name-server") == 0 ||
                  strcmp(token, "ntp-server") == 0) {
            char *ptoken;
            struct prefix_list *prefix;

            if(!server_config)
                return -1;

            c = getword(c, &ptoken, gnc, closure);
            if(c < -1)
                return -1;

            prefix = parse_prefix(ptoken, ADDRESS);

            if(prefix == NULL)
                return -1;

            if(strcmp(token, "name-server") == 0)
                server_config->name_server =
                    cat_prefix_list(server_config->name_server,
                                    prefix);
            else
                server_config->ntp_server =
                    cat_prefix_list(server_config->ntp_server,
                                    prefix);
            free(ptoken);
        } else {
            return -1;
        }
        free(token);
    }
    return 1;
}
Ejemplo n.º 22
0
word MaxReadLog(struct _proto *pro, word doing_ul)
{
  FILE *log;

  #define LOGLEN 255
  char fname[PATHLEN];
  char line[LOGLEN];
  word gotfile=FALSE;
  char tempname[PATHLEN];

  FENTRY fent;

  /* Handle the "%" translation characters */

  Parse_Outside_Cmd(pro->log, fname);
  
  if ((log=fopen(fname, fopen_read))==NULL)
  {
    cant_open(fname);
    return FALSE;
  }

  while (fgets(line, LOGLEN, log))
  {
    char *ulstr, *dlstr, *got, *desc;
    word ul;
    word fn;
    
    /* Find the positions of the upload and download strings */

    dlstr=strstr(line, pro->dlkey);
    ulstr=strstr(line, pro->ulkey);

    if (ulstr==NULL && dlstr==NULL)
      continue;

    if (pro->flag & P_BI)
    {
      /* Use whichever token comes FIRST in the log line, since we might    *
       * see either.                                                        */
      
      ul=(ulstr && (dlstr==NULL || ulstr < dlstr));
      got=(ul ? ulstr : dlstr);
    }
    else
    {
      /* Otherwise, just get the one that was requested */

      ul=doing_ul;
      
      got=(ul ? ulstr : dlstr);

      if (!got)
        continue;
    }

    /* Now copy the filename, based on the word# we're supposed to get. */

    getword(got, fname, ctl_delim, pro->fnamword+1);

    /* Skip it if we didn't get anything */

    if (*fname=='\0')
      continue;
    
    /* Now figure out if we requested this file or not... */
    
    for (fn=0; GetFileEntry(fn, &fent); fn++)
      if (eqstri(No_Path(fent.szName), No_Path(fname)))
        break;

    if (fn==FileEntries())
      memset(&fent, 0, sizeof fent);
      
    /* Grab the description, if any */

    desc=pro->descword ? firstchar(got, ctl_delim, pro->descword) : NULL;

    if (desc)
      fent.szDesc=desc;

    /* If we're doing an upload, strip the path specification */

    if (ul)
    {
      strcpy(tempname, No_Path(fname));
      fent.szName=tempname;

      /* Now figure out the fully-qualified path/name of the file so
       * that we can get the correct size.
       */

      sprintf(fname, ss, FAS(fah, uppath), fent.szName);
    }
    else
    {
      fent.szName=fname;
    }

    /* Now get the size of this file */
    
    fent.ulSize = fsize(fent.szName);

    if (ul)
    {
      logit(log_ul, *pro->desc, FAS(fah, uppath), fent.szName);
      fent.fFlags |= FFLAG_GOT;
    }
    else
    {
      fent.fFlags |= FFLAG_SENT;
    }

    UpdFileEntry(fn, &fent);
    gotfile=TRUE;
  }

  fclose(log);

  /* If the transfer was successful, delete both the .CTL and .LOG files */

  if (gotfile)
  {
    Parse_Outside_Cmd(pro->log, fname);
    unlink(fname);

    Parse_Outside_Cmd(pro->ctl, fname);
    unlink(fname);
  }
  
  return gotfile;
}
Ejemplo n.º 23
0
int
print_insn_sparc (bfd_vma memaddr, disassemble_info *info)
{
  FILE *stream = info->stream;
  bfd_byte buffer[4];
  unsigned long insn;
  sparc_opcode_hash *op;
  /* Nonzero of opcode table has been initialized.  */
  static int opcodes_initialized = 0;
  /* bfd mach number of last call.  */
  static unsigned long current_mach = 0;
  bfd_vma (*getword) (const void *);

  if (!opcodes_initialized
      || info->mach != current_mach)
    {
      int i;

      current_arch_mask = compute_arch_mask (info->mach);

      if (!opcodes_initialized)
	sorted_opcodes =
	  xmalloc (sparc_num_opcodes * sizeof (sparc_opcode *));
      /* Reset the sorted table so we can resort it.  */
      for (i = 0; i < sparc_num_opcodes; ++i)
	sorted_opcodes[i] = &sparc_opcodes[i];
      qsort ((char *) sorted_opcodes, sparc_num_opcodes,
	     sizeof (sorted_opcodes[0]), compare_opcodes);

      build_hash_table (sorted_opcodes, opcode_hash_table, sparc_num_opcodes);
      current_mach = info->mach;
      opcodes_initialized = 1;
    }

  {
    int status =
      (*info->read_memory_func) (memaddr, buffer, sizeof (buffer), info);

    if (status != 0)
      {
	(*info->memory_error_func) (status, memaddr, info);
	return -1;
      }
  }

  /* On SPARClite variants such as DANlite (sparc86x), instructions
     are always big-endian even when the machine is in little-endian mode.  */
  if (info->endian == BFD_ENDIAN_BIG || info->mach == bfd_mach_sparc_sparclite)
    getword = bfd_getb32;
  else
    getword = bfd_getl32;

  insn = getword (buffer);

  info->insn_info_valid = 1;			/* We do return this info.  */
  info->insn_type = dis_nonbranch;		/* Assume non branch insn.  */
  info->branch_delay_insns = 0;			/* Assume no delay.  */
  info->target = 0;				/* Assume no target known.  */

  for (op = opcode_hash_table[HASH_INSN (insn)]; op; op = op->next)
    {
      const sparc_opcode *opcode = op->opcode;

      /* If the insn isn't supported by the current architecture, skip it.  */
      if (! (opcode->architecture & current_arch_mask))
	continue;

      if ((opcode->match & insn) == opcode->match
	  && (opcode->lose & insn) == 0)
	{
	  /* Nonzero means that we have found an instruction which has
	     the effect of adding or or'ing the imm13 field to rs1.  */
	  int imm_added_to_rs1 = 0;
	  int imm_ored_to_rs1 = 0;

	  /* Nonzero means that we have found a plus sign in the args
	     field of the opcode table.  */
	  int found_plus = 0;

	  /* Nonzero means we have an annulled branch.  */
	  int is_annulled = 0;

	  /* Do we have an `add' or `or' instruction combining an
             immediate with rs1?  */
	  if (opcode->match == 0x80102000) /* or */
	    imm_ored_to_rs1 = 1;
	  if (opcode->match == 0x80002000) /* add */
	    imm_added_to_rs1 = 1;

	  if (X_RS1 (insn) != X_RD (insn)
	      && strchr (opcode->args, 'r') != 0)
	      /* Can't do simple format if source and dest are different.  */
	      continue;
	  if (X_RS2 (insn) != X_RD (insn)
	      && strchr (opcode->args, 'O') != 0)
	      /* Can't do simple format if source and dest are different.  */
	      continue;

	  (*info->fprintf_func) (stream, "%s", opcode->name);

	  {
	    const char *s;

	    if (opcode->args[0] != ',')
	      (*info->fprintf_func) (stream, " ");

	    for (s = opcode->args; *s != '\0'; ++s)
	      {
		while (*s == ',')
		  {
		    (*info->fprintf_func) (stream, ",");
		    ++s;
		    switch (*s)
		      {
		      case 'a':
			(*info->fprintf_func) (stream, "a");
			is_annulled = 1;
			++s;
			continue;
		      case 'N':
			(*info->fprintf_func) (stream, "pn");
			++s;
			continue;

		      case 'T':
			(*info->fprintf_func) (stream, "pt");
			++s;
			continue;

		      default:
			break;
		      }
		  }

		(*info->fprintf_func) (stream, " ");

		switch (*s)
		  {
		  case '+':
		    found_plus = 1;
		    /* Fall through.  */

		  default:
		    (*info->fprintf_func) (stream, "%c", *s);
		    break;

		  case '#':
		    (*info->fprintf_func) (stream, "0");
		    break;

#define	reg(n)	(*info->fprintf_func) (stream, "%%%s", reg_names[n])
		  case '1':
		  case 'r':
		    reg (X_RS1 (insn));
		    break;

		  case '2':
		  case 'O':
		    reg (X_RS2 (insn));
		    break;

		  case 'd':
		    reg (X_RD (insn));
		    break;
#undef	reg

#define	freg(n)		(*info->fprintf_func) (stream, "%%%s", freg_names[n])
#define	fregx(n)	(*info->fprintf_func) (stream, "%%%s", freg_names[((n) & ~1) | (((n) & 1) << 5)])
		  case 'e':
		    freg (X_RS1 (insn));
		    break;
		  case 'v':	/* Double/even.  */
		  case 'V':	/* Quad/multiple of 4.  */
		    fregx (X_RS1 (insn));
		    break;

		  case 'f':
		    freg (X_RS2 (insn));
		    break;
		  case 'B':	/* Double/even.  */
		  case 'R':	/* Quad/multiple of 4.  */
		    fregx (X_RS2 (insn));
		    break;

		  case '4':
		    freg (X_RS3 (insn));
		    break;
		  case '5':	/* Double/even.  */
		    fregx (X_RS3 (insn));
		    break;

		  case 'g':
		    freg (X_RD (insn));
		    break;
		  case 'H':	/* Double/even.  */
		  case 'J':	/* Quad/multiple of 4.  */
		  case '}':     /* Double/even.  */
		    fregx (X_RD (insn));
		    break;
#undef	freg
#undef	fregx

#define	creg(n)	(*info->fprintf_func) (stream, "%%c%u", (unsigned int) (n))
		  case 'b':
		    creg (X_RS1 (insn));
		    break;

		  case 'c':
		    creg (X_RS2 (insn));
		    break;

		  case 'D':
		    creg (X_RD (insn));
		    break;
#undef	creg

		  case 'h':
		    (*info->fprintf_func) (stream, "%%hi(%#x)",
					   ((unsigned) 0xFFFFFFFF
					    & ((int) X_IMM22 (insn) << 10)));
		    break;

		  case 'i':	/* 13 bit immediate.  */
		  case 'I':	/* 11 bit immediate.  */
		  case 'j':	/* 10 bit immediate.  */
		    {
		      int imm;

		      if (*s == 'i')
		        imm = X_SIMM (insn, 13);
		      else if (*s == 'I')
			imm = X_SIMM (insn, 11);
		      else
			imm = X_SIMM (insn, 10);

		      /* Check to see whether we have a 1+i, and take
			 note of that fact.

			 Note: because of the way we sort the table,
			 we will be matching 1+i rather than i+1,
			 so it is OK to assume that i is after +,
			 not before it.  */
		      if (found_plus)
			imm_added_to_rs1 = 1;

		      if (imm <= 9)
			(*info->fprintf_func) (stream, "%d", imm);
		      else
			(*info->fprintf_func) (stream, "%#x", imm);
		    }
		    break;

		  case ')':	/* 5 bit unsigned immediate from RS3.  */
		    (info->fprintf_func) (stream, "%#x", (unsigned int) X_RS3 (insn));
		    break;

		  case 'X':	/* 5 bit unsigned immediate.  */
		  case 'Y':	/* 6 bit unsigned immediate.  */
		    {
		      int imm = X_IMM (insn, *s == 'X' ? 5 : 6);

		      if (imm <= 9)
			(info->fprintf_func) (stream, "%d", imm);
		      else
			(info->fprintf_func) (stream, "%#x", (unsigned) imm);
		    }
		    break;

		  case '3':
		    (info->fprintf_func) (stream, "%ld", X_IMM (insn, 3));
		    break;

		  case 'K':
		    {
		      int mask = X_MEMBAR (insn);
		      int bit = 0x40, printed_one = 0;
		      const char *name;

		      if (mask == 0)
			(info->fprintf_func) (stream, "0");
		      else
			while (bit)
			  {
			    if (mask & bit)
			      {
				if (printed_one)
				  (info->fprintf_func) (stream, "|");
				name = sparc_decode_membar (bit);
				(info->fprintf_func) (stream, "%s", name);
				printed_one = 1;
			      }
			    bit >>= 1;
			  }
		      break;
		    }

		  case '=':
		    info->target = memaddr + SEX (X_DISP10 (insn), 10) * 4;
		    (*info->print_address_func) (info->target, info);
		    break;

		  case 'k':
		    info->target = memaddr + SEX (X_DISP16 (insn), 16) * 4;
		    (*info->print_address_func) (info->target, info);
		    break;

		  case 'G':
		    info->target = memaddr + SEX (X_DISP19 (insn), 19) * 4;
		    (*info->print_address_func) (info->target, info);
		    break;

		  case '6':
		  case '7':
		  case '8':
		  case '9':
		    (*info->fprintf_func) (stream, "%%fcc%c", *s - '6' + '0');
		    break;

		  case 'z':
		    (*info->fprintf_func) (stream, "%%icc");
		    break;

		  case 'Z':
		    (*info->fprintf_func) (stream, "%%xcc");
		    break;

		  case 'E':
		    (*info->fprintf_func) (stream, "%%ccr");
		    break;

		  case 's':
		    (*info->fprintf_func) (stream, "%%fprs");
		    break;

		  case '{':
		    (*info->fprintf_func) (stream, "%%mcdper");
		    break;

		  case 'o':
		    (*info->fprintf_func) (stream, "%%asi");
		    break;

		  case 'W':
		    (*info->fprintf_func) (stream, "%%tick");
		    break;

		  case 'P':
		    (*info->fprintf_func) (stream, "%%pc");
		    break;

		  case '?':
		    if (X_RS1 (insn) == 31)
		      (*info->fprintf_func) (stream, "%%ver");
		    else if (X_RS1 (insn) == 23)
		      (*info->fprintf_func) (stream, "%%pmcdper");
		    else if ((unsigned) X_RS1 (insn) < 17)
		      (*info->fprintf_func) (stream, "%%%s",
					     v9_priv_reg_names[X_RS1 (insn)]);
		    else
		      (*info->fprintf_func) (stream, "%%reserved");
		    break;

		  case '!':
                    if (X_RD (insn) == 31)
                      (*info->fprintf_func) (stream, "%%ver");
		    else if (X_RD (insn) == 23)
		      (*info->fprintf_func) (stream, "%%pmcdper");
		    else if ((unsigned) X_RD (insn) < 17)
		      (*info->fprintf_func) (stream, "%%%s",
					     v9_priv_reg_names[X_RD (insn)]);
		    else
		      (*info->fprintf_func) (stream, "%%reserved");
		    break;

		  case '$':
		    if ((unsigned) X_RS1 (insn) < 32)
		      (*info->fprintf_func) (stream, "%%%s",
					     v9_hpriv_reg_names[X_RS1 (insn)]);
		    else
		      (*info->fprintf_func) (stream, "%%reserved");
		    break;

		  case '%':
		    if ((unsigned) X_RD (insn) < 32)
		      (*info->fprintf_func) (stream, "%%%s",
					     v9_hpriv_reg_names[X_RD (insn)]);
		    else
		      (*info->fprintf_func) (stream, "%%reserved");
		    break;

		  case '/':
		    if (X_RS1 (insn) < 16 || X_RS1 (insn) > 28)
		      (*info->fprintf_func) (stream, "%%reserved");
		    else
		      (*info->fprintf_func) (stream, "%%%s",
					     v9a_asr_reg_names[X_RS1 (insn)-16]);
		    break;

		  case '_':
		    if (X_RD (insn) < 16 || X_RD (insn) > 28)
		      (*info->fprintf_func) (stream, "%%reserved");
		    else
		      (*info->fprintf_func) (stream, "%%%s",
					     v9a_asr_reg_names[X_RD (insn)-16]);
		    break;

		  case '*':
		    {
		      const char *name = sparc_decode_prefetch (X_RD (insn));

		      if (name)
			(*info->fprintf_func) (stream, "%s", name);
		      else
			(*info->fprintf_func) (stream, "%ld", X_RD (insn));
		      break;
		    }

		  case 'M':
		    (*info->fprintf_func) (stream, "%%asr%ld", X_RS1 (insn));
		    break;

		  case 'm':
		    (*info->fprintf_func) (stream, "%%asr%ld", X_RD (insn));
		    break;

		  case 'L':
		    info->target = memaddr + SEX (X_DISP30 (insn), 30) * 4;
		    (*info->print_address_func) (info->target, info);
		    break;

		  case 'n':
		    (*info->fprintf_func)
		      (stream, "%#x", SEX (X_DISP22 (insn), 22));
		    break;

		  case 'l':
		    info->target = memaddr + SEX (X_DISP22 (insn), 22) * 4;
		    (*info->print_address_func) (info->target, info);
		    break;

		  case 'A':
		    {
		      const char *name = sparc_decode_asi (X_ASI (insn));

		      if (name)
			(*info->fprintf_func) (stream, "%s", name);
		      else
			(*info->fprintf_func) (stream, "(%ld)", X_ASI (insn));
		      break;
		    }

		  case 'C':
		    (*info->fprintf_func) (stream, "%%csr");
		    break;

		  case 'F':
		    (*info->fprintf_func) (stream, "%%fsr");
		    break;

		  case '(':
		    (*info->fprintf_func) (stream, "%%efsr");
		    break;

		  case 'p':
		    (*info->fprintf_func) (stream, "%%psr");
		    break;

		  case 'q':
		    (*info->fprintf_func) (stream, "%%fq");
		    break;

		  case 'Q':
		    (*info->fprintf_func) (stream, "%%cq");
		    break;

		  case 't':
		    (*info->fprintf_func) (stream, "%%tbr");
		    break;

		  case 'w':
		    (*info->fprintf_func) (stream, "%%wim");
		    break;

		  case 'x':
		    (*info->fprintf_func) (stream, "%ld",
					   ((X_LDST_I (insn) << 8)
					    + X_ASI (insn)));
		    break;

		  case 'y':
		    (*info->fprintf_func) (stream, "%%y");
		    break;

		  case 'u':
		  case 'U':
		    {
		      int val = *s == 'U' ? X_RS1 (insn) : X_RD (insn);
		      const char *name = sparc_decode_sparclet_cpreg (val);

		      if (name)
			(*info->fprintf_func) (stream, "%s", name);
		      else
			(*info->fprintf_func) (stream, "%%cpreg(%d)", val);
		      break;
		    }
		  }
	      }
	  }

	  /* If we are adding or or'ing something to rs1, then
	     check to see whether the previous instruction was
	     a sethi to the same register as in the sethi.
	     If so, attempt to print the result of the add or
	     or (in this context add and or do the same thing)
	     and its symbolic value.  */
	  if (imm_ored_to_rs1 || imm_added_to_rs1)
	    {
	      unsigned long prev_insn;
	      int errcode;

	      if (memaddr >= 4)
		errcode =
		  (*info->read_memory_func)
		  (memaddr - 4, buffer, sizeof (buffer), info);
	      else
		errcode = 1;

	      prev_insn = getword (buffer);

	      if (errcode == 0)
		{
		  /* If it is a delayed branch, we need to look at the
		     instruction before the delayed branch.  This handles
		     sequences such as:

		     sethi %o1, %hi(_foo), %o1
		     call _printf
		     or %o1, %lo(_foo), %o1  */

		  if (is_delayed_branch (prev_insn))
		    {
		      if (memaddr >= 8)
			errcode = (*info->read_memory_func)
			  (memaddr - 8, buffer, sizeof (buffer), info);
		      else
			errcode = 1;

		      prev_insn = getword (buffer);
		    }
		}

	      /* If there was a problem reading memory, then assume
		 the previous instruction was not sethi.  */
	      if (errcode == 0)
		{
		  /* Is it sethi to the same register?  */
		  if ((prev_insn & 0xc1c00000) == 0x01000000
		      && X_RD (prev_insn) == X_RS1 (insn))
		    {
		      (*info->fprintf_func) (stream, "\t! ");
		      info->target =
			((unsigned) 0xFFFFFFFF
			 & ((int) X_IMM22 (prev_insn) << 10));
		      if (imm_added_to_rs1)
			info->target += X_SIMM (insn, 13);
		      else
			info->target |= X_SIMM (insn, 13);
		      (*info->print_address_func) (info->target, info);
		      info->insn_type = dis_dref;
		      info->data_size = 4;  /* FIXME!!! */
		    }
		}
	    }

	  if (opcode->flags & (F_UNBR|F_CONDBR|F_JSR))
	    {
	      /* FIXME -- check is_annulled flag.  */
	      (void) is_annulled;
	      if (opcode->flags & F_UNBR)
		info->insn_type = dis_branch;
	      if (opcode->flags & F_CONDBR)
		info->insn_type = dis_condbranch;
	      if (opcode->flags & F_JSR)
		info->insn_type = dis_jsr;
	      if (opcode->flags & F_DELAYED)
		info->branch_delay_insns = 1;
	    }

	  return sizeof (buffer);
	}
    }
Ejemplo n.º 24
0
int main(int argc, char *argv[])
{
    FILE *tfp, *f;
    char user[MAX_STRING_LEN];
    char realm[MAX_STRING_LEN];
    char line[MAX_STRING_LEN];
    char l[MAX_STRING_LEN];
    char w[MAX_STRING_LEN];
    char x[MAX_STRING_LEN];
    char command[MAX_STRING_LEN];
    int found;

    tn = NULL;
    signal(SIGINT, (void (*)(int)) interrupted);
    if (argc == 5) {
	if (strcmp(argv[1], "-c"))
	    usage();
#ifdef NETWARE
    UnAugmentAsterisk(TRUE);
    SetCurrentNameSpace(NW_NS_LONG);
    SetTargetNameSpace(NW_NS_LONG);
#endif
	if (!(tfp = fopen(argv[2], "w"))) {
	    fprintf(stderr, "Could not open passwd file %s for writing.\n",
		    argv[2]);
	    perror("fopen");
	    exit(1);
	}
	printf("Adding password for %s in realm %s.\n", argv[4], argv[3]);
	add_password(argv[4], argv[3], tfp);
	fclose(tfp);
	exit(0);
    }
    else if (argc != 4)
	usage();

    tn = tmpnam(NULL);
    if (!(tfp = fopen(tn, "w"))) {
	fprintf(stderr, "Could not open temp file.\n");
	exit(1);
    }

    if (!(f = fopen(argv[1], "r"))) {
	fprintf(stderr,
		"Could not open passwd file %s for reading.\n", argv[1]);
	fprintf(stderr, "Use -c option to create new one.\n");
	exit(1);
    }
    ap_cpystrn(user, argv[3], sizeof(user));
    ap_cpystrn(realm, argv[2], sizeof(realm));

    found = 0;
    while (!(getline(line, MAX_STRING_LEN, f))) {
	if (found || (line[0] == '#') || (!line[0])) {
	    putline(tfp, line);
	    continue;
	}
	strcpy(l, line);
	getword(w, l, ':');
	getword(x, l, ':');
	if (strcmp(user, w) || strcmp(realm, x)) {
	    putline(tfp, line);
	    continue;
	}
	else {
	    printf("Changing password for user %s in realm %s\n", user, realm);
	    add_password(user, realm, tfp);
	    found = 1;
	}
    }
    if (!found) {
	printf("Adding user %s in realm %s\n", user, realm);
	add_password(user, realm, tfp);
    }   
    fclose(f);
    fclose(tfp);
#ifndef NETWARE
#if defined(OS2) || defined(WIN32)
    sprintf(command, "copy \"%s\" \"%s\"", tn, argv[1]);
#else
    sprintf(command, "cp %s %s", tn, argv[1]);
#endif
    system(command);
#else
    if (!(tfp = fopen(tn, "r"))) {
    fprintf(stderr, "Could not open temp file.\n");
    exit(1);
    }
    
    if (!(f = fopen(argv[1], "w"))) {
    fprintf(stderr, "Could not open %s.\n", argv[1]);    
    exit(1);    
    }
    
    copy_file(f, tfp);
#endif
    unlink(tn);
    return 0;
}
Ejemplo n.º 25
0
static int tl_lex(int *cnt, size_t hasuform, char *uform, Miscellaneous *miscell, int *tl_yychar)
{	
	int c,ii;

	do {
		c = tl_Getchar(cnt, hasuform, uform);
		miscell->yytext[0] = (char ) c;
		miscell->yytext[1] = '\0';
		if (c <= 0)
		{	Token(';');
		}
	} while (c == ' ');	/* '\t' is removed in tl_main.c */

	/* get the truth constants true and false and predicates */
	if (islower(c))
	{	getword(c, isalnum_,cnt, hasuform, uform, miscell);
		if (strcmp("true", miscell->yytext) == 0)
		{	Token(TRUE);
		}
		if (strcmp("false", miscell->yytext) == 0)
		{	Token(FALSE);
		}
		miscell->tl_yylval = tl_nn(PREDICATE,ZN,ZN,miscell);
		miscell->type_temp = PREDICATE;
		miscell->tl_yylval->sym = tl_lookup(miscell->yytext, miscell);

		/* match predicate index*/
		for(ii = 0; ii < miscell->dp_taliro_param.nPred; ii++)
		{
			if(miscell->predMap[ii].str != NULL)
			{
				if(strcmp(miscell->tl_yylval->sym->name, miscell->predMap[ii].str)==0)
				{
					if(miscell->parMap[ii].str == NULL){
                        miscell->pList.pindex[ii] = PRED;
                    }else{
                        miscell->pList.pindex[ii] = PREDPAR;
                    }
				}
			}
		}

		return PREDICATE;
	}
	/* get temporal operators */
	if (c == '<')
	{	
		c = tl_Getchar(cnt, hasuform, uform);
		if (c == '>') 
		{
			miscell->tl_yylval = tl_nn(EVENTUALLY,ZN,ZN,miscell);
			miscell->type_temp = EVENTUALLY;
			mtl_con(cnt, hasuform, uform, miscell,tl_yychar);
			return EVENTUALLY;
		}
		if (c != '-')
		{	
			tl_UnGetchar(cnt);
			tl_yyerror("expected '<>' or '<->'", cnt, uform, tl_yychar, miscell);
		}
		c = tl_Getchar(cnt, hasuform, uform);
		if (c == '>')
		{	
			Token(EQUIV);
		}
		tl_UnGetchar(cnt);
		tl_yyerror("expected '<->'", cnt, uform, tl_yychar, miscell);
	}

	switch (c) 
	{
		case '/' : 
			c = follow('\\', AND, '/', cnt, hasuform, uform, tl_yychar, miscell); 
			break;
		case '\\': 
			c = follow('/', OR, '\\', cnt, hasuform, uform, tl_yychar, miscell); 
			break;
		case '&' : 
			c = follow('&', AND, '&', cnt, hasuform, uform, tl_yychar, miscell); 
			break;
		case '|' : 
			c = follow('|', OR, '|', cnt, hasuform, uform, tl_yychar, miscell); 
			break;
		case '[' : 
			c = mtl_follow(']', ALWAYS, '[', cnt, hasuform, uform, miscell, tl_yychar); 
			break;
		case '-' : 
			c = follow('>', IMPLIES, '-', cnt, hasuform, uform, tl_yychar, miscell); 
			break;
		case '!' : 
			c = NOT; 
			break;
		case 'U' : 
			miscell->type_temp = U_OPER;
			mtl_con(cnt, hasuform, uform, miscell,tl_yychar);
			c = U_OPER;
			break;
		case 'R' : 
			miscell->type_temp = V_OPER;
			mtl_con(cnt, hasuform, uform, miscell,tl_yychar);
			c = V_OPER;
			break;
		case 'X' : 
			miscell->type_temp = NEXT;
			mtl_con(cnt, hasuform, uform, miscell,tl_yychar);
			c = NEXT;
			break;
		case 'W' : 
			miscell->type_temp = WEAKNEXT;
			mtl_con(cnt, hasuform, uform, miscell, tl_yychar);
			c = WEAKNEXT;
			break;
		default  : break;
	}
	Token(c);
}
/*% parses a file and fills in the data structure. */
isc_result_t
irs_resconf_load(isc_mem_t *mctx, const char *filename, irs_resconf_t **confp)
{
	FILE *fp = NULL;
	char word[256];
	isc_result_t rval, ret = ISC_R_SUCCESS;
	irs_resconf_t *conf;
	int i, stopchar;

	REQUIRE(mctx != NULL);
	REQUIRE(filename != NULL);
	REQUIRE(strlen(filename) > 0U);
	REQUIRE(confp != NULL && *confp == NULL);

	conf = isc_mem_get(mctx, sizeof(*conf));
	if (conf == NULL)
		return (ISC_R_NOMEMORY);

	conf->mctx = mctx;
	ISC_LIST_INIT(conf->nameservers);
	conf->numns = 0;
	conf->domainname = NULL;
	conf->searchnxt = 0;
	conf->resdebug = 0;
	conf->ndots = 1;
	for (i = 0; i < RESCONFMAXSEARCH; i++)
		conf->search[i] = NULL;

	errno = 0;
	if ((fp = fopen(filename, "r")) != NULL) {
		do {
			stopchar = getword(fp, word, sizeof(word));
			if (stopchar == EOF) {
				rval = ISC_R_SUCCESS;
				POST(rval);
				break;
			}

			if (strlen(word) == 0U)
				rval = ISC_R_SUCCESS;
			else if (strcmp(word, "nameserver") == 0)
				rval = resconf_parsenameserver(conf, fp);
			else if (strcmp(word, "domain") == 0)
				rval = resconf_parsedomain(conf, fp);
			else if (strcmp(word, "search") == 0)
				rval = resconf_parsesearch(conf, fp);
			else if (strcmp(word, "sortlist") == 0)
				rval = resconf_parsesortlist(conf, fp);
			else if (strcmp(word, "options") == 0)
				rval = resconf_parseoption(conf, fp);
			else {
				/* unrecognised word. Ignore entire line */
				rval = ISC_R_SUCCESS;
				stopchar = eatline(fp);
				if (stopchar == EOF) {
					break;
				}
			}
			if (ret == ISC_R_SUCCESS && rval != ISC_R_SUCCESS)
				ret = rval;
		} while (1);

		fclose(fp);
	} else {
		switch (errno) {
		case ENOENT:
			break;
		default:
			isc_mem_put(mctx, conf, sizeof(*conf));
			return (ISC_R_INVALIDFILE);
		}
	}

	/* If we don't find a nameserver fall back to localhost */
	if (conf->numns == 0) {
		INSIST(ISC_LIST_EMPTY(conf->nameservers));

		/* XXX: should we catch errors? */
		(void)add_server(conf->mctx, "127.0.0.1", &conf->nameservers);
		(void)add_server(conf->mctx, "::1", &conf->nameservers);
	}

	/*
	 * Construct unified search list from domain or configured
	 * search list
	 */
	ISC_LIST_INIT(conf->searchlist);
	if (conf->domainname != NULL) {
		ret = add_search(conf, conf->domainname);
	} else if (conf->searchnxt > 0) {
		for (i = 0; i < conf->searchnxt; i++) {
			ret = add_search(conf, conf->search[i]);
			if (ret != ISC_R_SUCCESS)
				break;
		}
	}

	conf->magic = IRS_RESCONF_MAGIC;

	if (ret != ISC_R_SUCCESS)
		irs_resconf_destroy(&conf);
	else {
		if (fp == NULL)
			ret = ISC_R_FILENOTFOUND;
		*confp = conf;
	}

	return (ret);
}
Ejemplo n.º 27
0
/*
 *	Read the users, huntgroups or hints file.
 *	Return a PAIR_LIST.
 */
int pairlist_read(TALLOC_CTX *ctx, char const *file, PAIR_LIST **list, int complain)
{
	FILE *fp;
	int mode = FIND_MODE_NAME;
	char entry[256];
	char buffer[8192];
	char const *ptr;
	VALUE_PAIR *check_tmp;
	VALUE_PAIR *reply_tmp;
	PAIR_LIST *pl = NULL, *t;
	PAIR_LIST **last = &pl;
	int lineno = 0;
	int old_lineno = 0;
	FR_TOKEN parsecode;
	char newfile[8192];

	DEBUG2("reading pairlist file %s", file);

	/*
	 *	Open the file.  The error message should be a little
	 *	more useful...
	 */
	if ((fp = fopen(file, "r")) == NULL) {
		if (!complain)
			return -1;
		ERROR("Couldn't open %s for reading: %s", file, fr_syserror(errno));
		return -1;
	}

	parsecode = T_EOL;

	/*
	 *	Read the entire file into memory for speed.
	 */
	while(fgets(buffer, sizeof(buffer), fp) != NULL) {
		lineno++;
		if (!feof(fp) && (strchr(buffer, '\n') == NULL)) {
			fclose(fp);
			ERROR("%s[%d]: line too long", file, lineno);
			pairlist_free(&pl);
			return -1;
		}
		if (buffer[0] == '#' || buffer[0] == '\n') continue;

		/*
		 *	If the line contains nothing but whitespace,
		 *	ignore it.
		 */
		ptr = buffer;
		while (isspace((int) *ptr)) ptr++;
		if (*ptr == '\0') continue;

parse_again:
		if(mode == FIND_MODE_NAME) {
			/*
			 *	Find the entry starting with the users name
			 */
			if (isspace((int) buffer[0]))  {
				if (parsecode != T_EOL) {
					ERROR("%s[%d]: Unexpected trailing comma for entry %s",
					       file, lineno, entry);
					fclose(fp);
					return -1;
				}
				continue;
			}

			ptr = buffer;
			getword(&ptr, entry, sizeof(entry));

			/*
			 *	Include another file if we see
			 *	$INCLUDE filename
			 */
			if (strcasecmp(entry, "$INCLUDE") == 0) {
				while(isspace((int) *ptr))
					ptr++;

				/*
				 *	If it's an absolute pathname,
				 *	then use it verbatim.
				 *
				 *	If not, then make the $include
				 *	files *relative* to the current
				 *	file.
				 */
				if (FR_DIR_IS_RELATIVE(ptr)) {
					char *p;

					strlcpy(newfile, file,
						sizeof(newfile));
					p = strrchr(newfile, FR_DIR_SEP);
					if (!p) {
						p = newfile + strlen(newfile);
						*p = FR_DIR_SEP;
					}
					getword(&ptr, p + 1,
						sizeof(newfile) - 1 - (p - newfile));
				} else {
					getword(&ptr, newfile,
						sizeof(newfile));
				}

				t = NULL;

				if (pairlist_read(ctx, newfile, &t, 0) != 0) {
					pairlist_free(&pl);
					ERROR("%s[%d]: Could not open included file %s: %s",
					      file, lineno, newfile, fr_syserror(errno));
					fclose(fp);
					return -1;
				}
				*last = t;

				/*
				 *	t may be NULL, it may have one
				 *	entry, or it may be a linked list
				 *	of entries.  Go to the end of the
				 *	list.
				 */
				while (*last)
					last = &((*last)->next);
				continue;
			}

			/*
			 *	Parse the check values
			 */
			check_tmp = NULL;
			reply_tmp = NULL;
			old_lineno = lineno;
			parsecode = userparse(ctx, ptr, &check_tmp);
			if (parsecode == T_OP_INVALID) {
				pairlist_free(&pl);
				ERROR("%s[%d]: Parse error (check) for entry %s: %s",
					file, lineno, entry, fr_strerror());
				fclose(fp);
				return -1;
			} else if (parsecode == T_COMMA) {
				ERROR("%s[%d]: Unexpected trailing comma in check item list for entry %s",
				       file, lineno, entry);
				fclose(fp);
				return -1;
			}
			mode = FIND_MODE_REPLY;
			parsecode = T_COMMA;
		}
		else {
			if(*buffer == ' ' || *buffer == '\t') {
				if (parsecode != T_COMMA) {
					ERROR("%s[%d]: Syntax error: Previous line is missing a trailing comma for entry %s",
					       file, lineno, entry);
					fclose(fp);
					return -1;
				}

				/*
				 *	Parse the reply values
				 */
				parsecode = userparse(ctx, buffer, &reply_tmp);
				/* valid tokens are 1 or greater */
				if (parsecode < 1) {
					pairlist_free(&pl);
					ERROR("%s[%d]: Parse error (reply) for entry %s: %s",
					       file, lineno, entry, fr_strerror());
					fclose(fp);
					return -1;
				}
			} else {
				/*
				 *	Done with this entry...
				 */
				MEM(t = talloc_zero(ctx, PAIR_LIST));

				t->check = check_tmp;
				t->reply = reply_tmp;
				t->lineno = old_lineno;
				check_tmp = NULL;
				reply_tmp = NULL;

				t->name = talloc_typed_strdup(t, entry);

				*last = t;
				last = &(t->next);

				mode = FIND_MODE_NAME;
				if (buffer[0] != 0)
					goto parse_again;
			}
		}
	}
	/*
	 *	Make sure that we also read the last line of the file!
	 */
	if (mode == FIND_MODE_REPLY) {
		buffer[0] = 0;
		goto parse_again;
	}
	fclose(fp);

	*list = pl;
	return 0;
}
Ejemplo n.º 28
0
/* This handles piping of the LSUB command, because we have to figure out
 * what mailboxes actually exist before passing them to the end user.
 *
 * It is also needed if we are doing a FIND MAILBOXES, for that we do an
 * LSUB on the backend anyway, because the semantics of FIND do not allow
 * it to return nonexistant mailboxes (RFC1176), but we need to really dumb
 * down the response when this is the case.
 */
int pipe_lsub(struct backend *s, const char *userid, const char *tag,
              int force_notfatal, const char *resp)
{
    int taglen = strlen(tag);
    int c;
    int r = PROXY_OK;
    int exist_r;
    static struct buf tagb, cmd, sep, name;
    struct buf flags = BUF_INITIALIZER;

    const char *end_strip_flags[] = { " \\NonExistent)", "\\NonExistent)",
                                      " \\Noselect)", "\\Noselect)",
                                      NULL };
    const char *mid_strip_flags[] = { "\\NonExistent ",
                                      "\\Noselect ",
                                      NULL
                                    };

    assert(s);
    assert(s->timeout);

    s->timeout->mark = time(NULL) + IDLE_TIMEOUT;

    while(1) {
        c = getword(s->in, &tagb);

        if(c == EOF) {
            if(s == backend_current && !force_notfatal)
                fatal("Lost connection to selected backend", EC_UNAVAILABLE);
            proxy_downserver(s);
            r = PROXY_NOCONNECTION;
            goto out;
        }

        if(!strncmp(tag, tagb.s, taglen)) {
            char buf[2048];
            if(!prot_fgets(buf, sizeof(buf), s->in)) {
                if(s == backend_current && !force_notfatal)
                    fatal("Lost connection to selected backend",
                          EC_UNAVAILABLE);
                proxy_downserver(s);
                r = PROXY_NOCONNECTION;
                goto out;
            }
            /* Got the end of the response */
            buf_appendcstr(&s->last_result, buf);
            buf_cstring(&s->last_result);

            switch (buf[0]) {
            case 'O': case 'o':
                r = PROXY_OK;
                break;
            case 'N': case 'n':
                r = PROXY_NO;
                break;
            case 'B': case 'b':
                r = PROXY_BAD;
                break;
            default: /* huh? no result? */
                if(s == backend_current && !force_notfatal)
                    fatal("Lost connection to selected backend",
                          EC_UNAVAILABLE);
                proxy_downserver(s);
                r = PROXY_NOCONNECTION;
                break;
            }
            break; /* we're done */
        }

        c = getword(s->in, &cmd);

        if(c == EOF) {
            if(s == backend_current && !force_notfatal)
                fatal("Lost connection to selected backend", EC_UNAVAILABLE);
            proxy_downserver(s);
            r = PROXY_NOCONNECTION;
            goto out;
        }

        if(strncasecmp("LSUB", cmd.s, 4) && strncasecmp("LIST", cmd.s, 4)) {
            prot_printf(imapd_out, "%s %s ", tagb.s, cmd.s);
            r = pipe_to_end_of_response(s, force_notfatal);
            if (r != PROXY_OK)
                goto out;
        } else {
            /* build up the response bit by bit */
            int i;

            buf_reset(&flags);
            c = prot_getc(s->in);
            while(c != ')' && c != EOF) {
                buf_putc(&flags, c);
                c = prot_getc(s->in);
            }

            if(c != EOF) {
                /* terminate string */
                buf_putc(&flags, ')');
                buf_cstring(&flags);

                /* get the next character */
                c = prot_getc(s->in);
            }

            if(c != ' ') {
                if(s == backend_current && !force_notfatal)
                    fatal("Bad LSUB response from selected backend",
                          EC_UNAVAILABLE);
                proxy_downserver(s);
                r = PROXY_NOCONNECTION;
                goto out;
            }

            /* Check for flags that we should remove
             * (e.g. Noselect, NonExistent) */
            for(i=0; end_strip_flags[i]; i++)
                buf_replace_all(&flags, end_strip_flags[i], ")");

            for (i=0; mid_strip_flags[i]; i++)
                buf_replace_all(&flags, mid_strip_flags[i], NULL);

            /* Get separator */
            c = getastring(s->in, s->out, &sep);

            if(c != ' ') {
                if(s == backend_current && !force_notfatal)
                    fatal("Bad LSUB response from selected backend",
                          EC_UNAVAILABLE);
                proxy_downserver(s);
                r = PROXY_NOCONNECTION;
                goto out;
            }

            /* Get name */
            c = getastring(s->in, s->out, &name);

            if(c == '\r') c = prot_getc(s->in);
            if(c != '\n') {
                if(s == backend_current && !force_notfatal)
                    fatal("Bad LSUB response from selected backend",
                          EC_UNAVAILABLE);
                proxy_downserver(s);
                r = PROXY_NOCONNECTION;
                goto out;
            }

            /* lookup name */
            exist_r = 1;
            char *intname = mboxname_from_external(name.s, &imapd_namespace, userid);
            mbentry_t *mbentry = NULL;
            exist_r = mboxlist_lookup(intname, &mbentry, NULL);
            free(intname);
            if(!exist_r && (mbentry->mbtype & MBTYPE_RESERVE))
                exist_r = IMAP_MAILBOX_RESERVED;
            mboxlist_entry_free(&mbentry);

            /* send our response */
            /* we need to set \Noselect if it's not in our mailboxes.db */
            if (resp[0] == 'L') {
                if(!exist_r) {
                    prot_printf(imapd_out, "* %s %s \"%s\" ",
                                resp, flags.s, sep.s);
                } else {
                    prot_printf(imapd_out, "* %s (\\Noselect) \"%s\" ",
                                resp, sep.s);
                }

                prot_printstring(imapd_out, name.s);
                prot_printf(imapd_out, "\r\n");

            } else if(resp[0] == 'M' && !exist_r) {
                /* Note that it has to exist for a find response */
                prot_printf(imapd_out, "* %s ", resp);
                prot_printastring(imapd_out, name.s);
                prot_printf(imapd_out, "\r\n");
            }
        }
    } /* while(1) */

out:
    buf_free(&flags);
    return r;
}
Ejemplo n.º 29
0
//
//  Load OBJ file
//
int LoadOBJ(const char* file)
{
   int k;
   int  Nv,Nn,Nt;  //  Number of vertex, normal and textures
   int  Mv,Mn,Mt;  //  Maximum vertex, normal and textures
   float* V;       //  Array of vertexes
   float* N;       //  Array of normals
   float* T;       //  Array if textures coordinates
   char*  line;    //  Line pointer
   char*  str;     //  String pointer

   //  Open file
   FILE* f = fopen(file,"r");
   if (!f) Fatal("Cannot open file %s\n",file);

   // Reset materials
   mtl = NULL;
   Nmtl = 0;

   //  Start new displaylist
   int list = glGenLists(1);
   glNewList(list,GL_COMPILE);
   //  Push attributes for textures
   glPushAttrib(GL_TEXTURE_BIT);

   //  Read vertexes and facets
   V  = N  = T  = NULL;
   Nv = Nn = Nt = 0;
   Mv = Mn = Mt = 0;
   while ((line = readline(f)))
   {
      //  Vertex coordinates (always 3)
      if (line[0]=='v' && line[1]==' ')
         readcoord(line+2,3,&V,&Nv,&Mv);
      //  Normal coordinates (always 3)
      else if (line[0]=='v' && line[1] == 'n')
         readcoord(line+2,3,&N,&Nn,&Mn);
      //  Texture coordinates (always 2)
      else if (line[0]=='v' && line[1] == 't')
         readcoord(line+2,2,&T,&Nt,&Mt);
      //  Read and draw facets
      else if (line[0]=='f')
      {
         line++;
         //  Read Vertex/Texture/Normal triplets
         glBegin(GL_POLYGON);
         while ((str = getword(&line)))
         {
            int Kv,Kt,Kn;
            //  Try Vertex/Texture/Normal triplet
            if (sscanf(str,"%d/%d/%d",&Kv,&Kt,&Kn)==3)
            {
               if (Kv<0 || Kv>Nv/3) Fatal("Vertex %d out of range 1-%d\n",Kv,Nv/3);
               if (Kn<0 || Kn>Nn/3) Fatal("Normal %d out of range 1-%d\n",Kn,Nn/3);
               if (Kt<0 || Kt>Nt/2) Fatal("Texture %d out of range 1-%d\n",Kt,Nt/2);
            }
            //  Try Vertex//Normal pairs
            else if (sscanf(str,"%d//%d",&Kv,&Kn)==2)
            {
               if (Kv<0 || Kv>Nv/3) Fatal("Vertex %d out of range 1-%d\n",Kv,Nv/3);
               if (Kn<0 || Kn>Nn/3) Fatal("Normal %d out of range 1-%d\n",Kn,Nn/3);
               Kt = 0;
            }
            //  Try Vertex index
            else if (sscanf(str,"%d",&Kv)==1)
            {
               if (Kv<0 || Kv>Nv/3) Fatal("Vertex %d out of range 1-%d\n",Kv,Nv/3);
               Kn = 0;
               Kt = 0;
            }
            //  This is an error
            else
               Fatal("Invalid facet %s\n",str);
            //  Draw vectors
            if (Kt) glTexCoord2fv(T+2*(Kt-1));
            if (Kn) glNormal3fv(N+3*(Kn-1));
            if (Kv) glVertex3fv(V+3*(Kv-1));
         }
         glEnd();
      }
      //  Use material
      else if ((str = readstr(line,"usemtl")))
         SetMaterial(str);
      //  Load materials
      else if ((str = readstr(line,"mtllib")))
         LoadMaterial(str);
      //  Skip this line
   }
   fclose(f);
   //  Pop attributes (textures)
   glPopAttrib();
   glEndList();

   //  Free materials
   for (k=0;k<Nmtl;k++)
      free(mtl[k].name);
   free(mtl);

   //  Free arrays
   free(V);
   free(T);
   free(N);

   return list;
}
Ejemplo n.º 30
0
/**
 * Gathers input from the command line and responds to the given
 * arguments.
 * Refer to help menu (-h) for more information.
 *
 * @param argc count the number of arguments on the command line. 
 * @param argv[] array of arguments.
 *
 * @return exit success or exit failure.
 */
int main (int argc, char *argv[]){

    char word[256];
    const char *optstring = "c:df:orh";
    char option;
    tree h;

    tree_t tree_type = BST;
    FILE *outfile;
    char* out = NULL;

    FILE *filename;
    int unknown = 0;
    clock_t fill_start,fill_end, search_start, search_end;

    int cflag = 0;
    int dflag = 0;
    int oflag = 0;

    while ((option = getopt(argc,argv,optstring)) != EOF){
        switch(option){
            case'f':
                out = optarg;
                break;

            case 'o':
                oflag = 1;
                break;

            case 'r':
                tree_type = RBT;
                break;

            case 'd':
                dflag = 1;
                break;

            case 'c':
                if (NULL == (filename = fopen(optarg, "r"))) {
                    fprintf(stderr, "%s: can't find file %s\n", argv[0], argv[1]);
                    return EXIT_FAILURE;
                }
                cflag = 1;
                break;

            case 'h':
                print_usage(argv[0]);
                exit(EXIT_FAILURE);
                break;

            default:
                print_usage(argv[0]);
                exit(EXIT_FAILURE);
        }
    }
    if (out == NULL){
        out = "tree-view.dot";
    }

    h = tree_new(tree_type);

    fill_start = clock();
    while (getword(word, sizeof word, stdin) != EOF){
        h = tree_insert(h,word);
    }
    fill_end = clock();

    if (oflag == 1){
        outfile = fopen(out, "w");
        tree_output_dot(h, outfile);
        fprintf(stderr,"Creating dot file '%s'\n",out );
        fclose(outfile);
    }

    if (cflag == 1){
        dflag = 0;
        oflag = 0;
        search_start = clock();
        while (getword(word, sizeof word, filename) != EOF){
            if (tree_search(h, word) == 0){
                printf("%s\n", word);
                unknown++;
            }
        }

        search_end = clock();
        fclose(filename);

        fprintf(stderr, "Fill time     : %7f\nSearch time   : %7f\nUnknown words = %d\n", \
                (fill_end-fill_start)/(double)CLOCKS_PER_SEC,           \
                (search_end-search_start)/(double)CLOCKS_PER_SEC, unknown);
    }

    if (dflag == 1){
        printf("%d\n",tree_depth(h));
    }else if (dflag == 0 && cflag == 0 && oflag == 0){
        tree_preorder(h, print_info);
    }

    tree_free(h);
    return EXIT_SUCCESS;
}