コード例 #1
0
/*
 * v_sentenceb -- [count](
 *	Move backward count sentences.
 *
 * PUBLIC: int v_sentenceb __P((SCR *, VICMD *));
 */
int
v_sentenceb(SCR *sp, VICMD *vp)
{
	VCS cs;
	db_recno_t slno;
	size_t len, scno;
	u_long cnt;
	int last;

	/*
	 * !!!
	 * Historic vi permitted the user to hit SOF repeatedly.
	 */
	if (vp->m_start.lno == 1 && vp->m_start.cno == 0)
		return (0);

	cs.cs_lno = vp->m_start.lno;
	cs.cs_cno = vp->m_start.cno;
	if (cs_init(sp, &cs))
		return (1);

	cnt = F_ISSET(vp, VC_C1SET) ? vp->count : 1;

	/*
	 * !!!
	 * In empty lines, skip to the previous non-white-space character.
	 * If in text, skip to the prevous white-space character.  Believe
	 * it or not, in the paragraph:
	 *	ab cd.
	 *	AB CD.
	 * if the cursor is on the 'A' or 'B', ( moves to the 'a'.  If it
	 * is on the ' ', 'C' or 'D', it moves to the 'A'.  Yes, Virginia,
	 * Berkeley was once a major center of drug activity.
	 */
	if (cs.cs_flags == CS_EMP) {
		if (cs_bblank(sp, &cs))
			return (1);
		for (;;) {
			if (cs_prev(sp, &cs))
				return (1);
			if (cs.cs_flags != CS_EOL)
				break;
		}
	} else if (cs.cs_flags == 0 && !isblank(cs.cs_ch))
		for (;;) {
			if (cs_prev(sp, &cs))
				return (1);
			if (cs.cs_flags != 0 || isblank(cs.cs_ch))
				break;
		}

	for (last = 0;;) {
		if (cs_prev(sp, &cs))
			return (1);
		if (cs.cs_flags == CS_SOF)	/* SOF is a movement sink. */
			break;
		if (cs.cs_flags == CS_EOL) {
			last = 1;
			continue;
		}
		if (cs.cs_flags == CS_EMP) {
			if (--cnt == 0)
				goto ret;
			if (cs_bblank(sp, &cs))
				return (1);
			last = 0;
			continue;
		}
		switch (cs.cs_ch) {
		case '.':
		case '?':
		case '!':
			if (!last || --cnt != 0) {
				last = 0;
				continue;
			}

ret:			slno = cs.cs_lno;
			scno = cs.cs_cno;

			/*
			 * Move to the start of the sentence, skipping blanks
			 * and special characters.
			 */
			do {
				if (cs_next(sp, &cs))
					return (1);
			} while (!cs.cs_flags &&
			    (cs.cs_ch == ')' || cs.cs_ch == ']' ||
			    cs.cs_ch == '"' || cs.cs_ch == '\''));
			if ((cs.cs_flags || isblank(cs.cs_ch)) &&
			    cs_fblank(sp, &cs))
				return (1);

			/*
			 * If it was ".  xyz", with the cursor on the 'x', or
			 * "end.  ", with the cursor in the spaces, or the
			 * beginning of a sentence preceded by an empty line,
			 * we can end up where we started.  Fix it.
			 */
			if (vp->m_start.lno != cs.cs_lno ||
			    vp->m_start.cno != cs.cs_cno)
				goto okret;

			/*
			 * Well, if an empty line preceded possible blanks
			 * and the sentence, it could be a real sentence.
			 */
			for (;;) {
				if (cs_prev(sp, &cs))
					return (1);
				if (cs.cs_flags == CS_EOL)
					continue;
				if (cs.cs_flags == 0 && isblank(cs.cs_ch))
					continue;
				break;
			}
			if (cs.cs_flags == CS_EMP)
				goto okret;

			/* But it wasn't; try again. */
			++cnt;
			cs.cs_lno = slno;
			cs.cs_cno = scno;
			last = 0;
			break;
		case '\t':
			last = 1;
			break;
		default:
			last =
			    cs.cs_flags == CS_EOL || isblank(cs.cs_ch) ||
			    cs.cs_ch == ')' || cs.cs_ch == ']' ||
			    cs.cs_ch == '"' || cs.cs_ch == '\'' ? 1 : 0;
		}
	}

okret:	vp->m_stop.lno = cs.cs_lno;
	vp->m_stop.cno = cs.cs_cno;

	/*
	 * !!!
	 * If the starting and stopping cursor positions are at the first
	 * columns in the line, i.e. the movement is cutting an entire line,
	 * the buffer is in line mode, and the starting position is the last
	 * character of the previous line.
	 *
	 * All commands move to the end of the range.  Adjust the start of
	 * the range for motion commands.
	 */
	if (ISMOTION(vp))
		if (vp->m_start.cno == 0 &&
		    (cs.cs_flags != 0 || vp->m_stop.cno == 0)) {
			if (db_get(sp,
			    --vp->m_start.lno, DBG_FATAL, NULL, &len))
				return (1);
			vp->m_start.cno = len ? len - 1 : 0;
			F_SET(vp, VM_LMODE);
		} else
			--vp->m_start.cno;
	vp->m_final = vp->m_stop;
	return (0);
}
コード例 #2
0
ファイル: odump.c プロジェクト: razzlefratz/MotleyTools
static void function (file const * file, off_t extent, flag_t flags)

{
	unsigned object = 0;
	unsigned lineno = 0;
	unsigned offset = 0;
	unsigned length = 0;
	char memory [_ADDRSIZE +  1];
	char symbol [_NAMESIZE];
	char string [_LINESIZE];
	char * sp;
	signed c;
	while ((c = getc (stdin)) != EOF)
	{
		if ((c == '#') || (c == ';'))
		{
			do 
			{
				c = getc (stdin);
			}
			while (nobreak (c));
			lineno++;
			continue;
		}
		if (isspace (c))
		{
			if (c == '\n')
			{
				lineno++;
			}
			continue;
		}
		length = 0;
		while (isdigit (c))
		{
			length *= 10;
			length += c - '0';
			c = getc (stdin);
		}
		while (isblank (c))
		{
			c = getc (stdin);
		}
		sp = symbol;
		if (isalpha (c) || (c == '_'))
		{
			do 
			{
				* sp++ = (char) (c);
				c = getc (stdin);
			}
			while (isident (c));
		}
		while (isblank (c))
		{
			c = getc (stdin);
		}
		if (c == '[')
		{
			* sp++ = (char) (c);
			c = getc (stdin);
			while (isblank (c))
			{
				c = getc (stdin);
			}
			while (isdigit (c))
			{
				* sp++ = (char) (c);
				c = getc (stdin);
			}
			while (isblank (c))
			{
				c = getc (stdin);
			}
			* sp = (char) (0);
			if (c != ']')
			{
				error (1, EINVAL, "Have '%s' without ']' on line %d", symbol, lineno);
			}
			* sp++ = (char) (c);
			c = getc (stdin);
		}
		* sp = (char) (0);
		while (isblank (c))
		{
			c = getc (stdin);
		}
		sp = string;
		while (nobreak (c))
		{
			* sp++ = (char) (c);
			c = getc (stdin);
		}
		* sp = (char) (0);
		if (length)
		{
			byte buffer [length];
			if (read (file->file, buffer, length) == (signed) (length))
			{
				if (! object++)
				{
					for (c = 0; c < _ADDRSIZE +  65; c++)
					{
						putc ('-', stdout);
					}
					putc ('\n', stdout);
				}
				printf ("%s %u %s\n", hexoffset (memory, sizeof (memory), offset), length, symbol);
				hexview (buffer, offset, length, stdout);
				for (c = 0; c < _ADDRSIZE +  65; c++)
				{
					putc ('-', stdout);
				}
				putc ('\n', stdout);
			}
		}
		offset += length;
		lineno++;
	}
	if (_allclr (flags, ODD_SILENCE))
	{
		if (offset != (unsigned) (extent))
		{
			error (0, 0, "%s has %u bytes, not " OFF_T_SPEC " bytes.", file->name, offset, extent);
		}
	}
	return;
}
コード例 #3
0
ファイル: io.c プロジェクト: cbeust/banker-amiga
void
readOptionsFile()
{
   FILE *f;
   int isOpen;
   char *p, keyword[80], *pk, buffer[256];
   char *name = (CL_Struct.optionsFile ? CL_Struct.optionsFile : OPTIONSFILENAME);

   f = fopen(name, "r");
   if (! f) {
      myMsg2("couldn't open the configuration file", name);
      goto close;
   }

   while (1) {
      p = fgets(buffer, 256, f);
      if (p == NULL) goto close;
      if (*p == '#' || *p == '\n') continue;      /* skip comments */
      if (feof(f)) goto close;
      pk = keyword;
      while (! isblank(*p)) *pk++ = *p++;
      *pk++ = '\0';               /* now the keyword is recorded */
      while (isblank (*p)) p++;  /* and p is on the first data field */

      if (stricmp(keyword, "mainwindow") == 0 ||
          stricmp(keyword, "list") == 0 ||
          stricmp(keyword, "getentry") == 0 ||
          stricmp(keyword, "automatic") == 0) {

         sscanf(p, " %d\n", & isOpen);
         if (keyword[0] == 'm' || keyword[0] == 'M') {
            OF_Struct.mainWindow.isOpen = isOpen;
         }
         else if (keyword[0] == 'l' || keyword[0] == 'L') {
            OF_Struct.list.isOpen = isOpen;
         }
         else if (keyword[0] == 'g' || keyword[0] == 'G') {
            OF_Struct.getEntry.isOpen = isOpen;
         }
         else if (keyword[0] == 'a' || keyword[0] == 'A') {
            OF_Struct.automatic.isOpen = isOpen;
         }
      }

      else if (stricmp(keyword, "autosave") == 0) {
         OF_Struct.autoSave = atoi(p);
      }

      else if (stricmp(keyword, "defaultdate") == 0) {
         char *df;
         OF_Struct.defaultDate = df = (char *) malloc(strlen(p));
         while (*p && *p != '\n') *df++ = *p++; /* to prevent an '\n' in the date */
         *df = '\0';
      }

      else if (stricmp(keyword, "dateformat") == 0) {
         char *df;
         OF_Struct.dateFormat = df = (char *) malloc(strlen(p));
         while (*p && *p != '\n') *df++ = *p++; /* to prevent an '\n' in the date */
         *df = '\0';
      }

      else if (stricmp(keyword, "printformat") == 0 ||
               stricmp(keyword, "displayformat") == 0 ||
               stricmp(keyword, "exportformat") == 0) {
         if (keyword[0] == 'p')  PrintFormatStructure = *parseFormatString(p);
         else if (keyword[0] == 'e') ExportFormatStructure = *parseFormatString(p);
         else {
            parseListEntry(p, DisplayEntryFormat);
            DisplayFormatStructure = *parseFormatString(p);
         }
      }


      else myMsg2("unknown keyword '%s'", keyword);
      while (*p && *p != '\n') p++;
   }
close:
   fclose(f);
}
コード例 #4
0
ファイル: config.c プロジェクト: davidmcgrew/joy
/* parse commands */
static int config_parse_command (struct configuration *config, 
			 const char *command, char *arg, int num) {  
    char *tmp;
  
    /* remove trailing whitespace from argument */
    tmp = arg + strnlen(arg, LINEMAX) - 1;
    while (isblank(*tmp)) {
        *tmp = 0;
        tmp--;
    }
  
    /*
     * note: because of the simplistic match function currently
     * implemented, each command name MUST NOT be a prefix of any other
     * command name; otherwise, the shorter name will be matched rather
     * than the longer one
     */

    if (match(command, "interface")) {
        parse_check(parse_string(&config->interface, arg, num));

    } else if (match(command, "promisc")) {
        parse_check(parse_bool(&config->promisc, arg, num));

    } else if (match(command, "daemon")) {
        parse_check(parse_bool(&config->daemon, arg, num));

    } else if (match(command, "output")) {
        parse_check(parse_string(&config->filename, arg, num));

    } else if (match(command, "outdir")) {
        parse_check(parse_string(&config->outputdir, arg, num));

    } else if (match(command, "log")) {
        parse_check(parse_string(&config->logfile, arg, num));

    } else if (match(command, "upload")) {
        parse_check(parse_string(&config->upload_servername, arg, num));

    } else if (match(command, "keyfile")) {
        parse_check(parse_string(&config->upload_key, arg, num));

    } else if (match(command, "model")) {
        parse_check(parse_string(&config->params_file, arg, num));

    } else if (match(command, "label")) {
        parse_check(parse_string_multiple(config->subnet, arg, num, config->num_subnets++, MAX_NUM_FLAGS));

    } else if (match(command, "retain")) {
        parse_check(parse_bool(&config->retain_local, arg, num));

    } else if (match(command, "zeros")) {
        parse_check(parse_bool(&config->include_zeroes, arg, num));

    } else if (match(command, "bidir")) {
        parse_check(parse_bool(&config->bidir, arg, num));

    } else if (match(command, "dist")) {
        parse_check(parse_bool(&config->byte_distribution, arg, num));

    } else if (match(command, "cdist")) {
        parse_check(parse_string(&config->compact_byte_distribution, arg, num));

    } else if (match(command, "entropy")) {
        parse_check(parse_bool(&config->report_entropy, arg, num));

    } else if (match(command, "hd")) {
        parse_check(parse_int(&config->report_hd, arg, num, 0, HDR_DSC_LEN));

    } else if (match(command, "tls")) {
        parse_check(parse_bool(&config->include_tls, arg, num));

    } else if (match(command, "classify")) {
        parse_check(parse_bool(&config->include_classifier, arg, num));

    } else if (match(command, "bpf")) {
        parse_check(parse_string(&config->bpf_filter_exp, arg, num));

    } else if (match(command, "verbosity")) {
        parse_check(parse_int(&config->output_level, arg, num, 0, 3));

    } else if (match(command, "num_pkts")) {
        parse_check(parse_int(&config->num_pkts, arg, num, 0, MAX_NUM_PKT_LEN));

    } else if (match(command, "type")) {
        parse_check(parse_int(&config->type, arg, num, 1, 2));
  
    } else if (match(command, "count")) {
        parse_check(parse_int(&config->max_records, arg, num, 1, INT_MAX));

    } else if (match(command, "idp")) {
        parse_check(parse_int(&config->idp, arg, num, 0, MAX_IDP));

    } else if (match(command, "nfv9_port")) {
        parse_check(parse_int(&config->nfv9_capture_port, arg, num, 0, 0xffff));

    } else if (match(command, "ipfix_cap_port")) {
        parse_check(parse_int(&config->ipfix_capture_port, arg, num, 0, 0xffff));

    } else if (match(command, "nat")) {
        parse_check(parse_bool(&config->flow_key_match_method, arg, num));

    } else if (match(command, "http")) {
        parse_check(parse_bool(&config->http, arg, num));

    } else if (match(command, "anon")) {
        parse_check(parse_string(&config->anon_addrs_file, arg, num));

    } else if (match(command, "useranon")) {
        parse_check(parse_string(&config->anon_http_file, arg, num));

    } else if (match(command, "exe")) {
        parse_check(parse_bool(&config->report_exe, arg, num));

    }

    config_all_features_bool(feature_list);

    return failure;
}
コード例 #5
0
ファイル: script_fex.c プロジェクト: CubieeDroid/sunxi-tools
/** find first not blank char */
static inline char *skip_blank(char *p)
{
	while(isblank(*p))
		p++;
	return p;
}
コード例 #6
0
ファイル: ex14.c プロジェクト: baloi/c_me
int can_print_it(char ch)
{
  return isalpha(ch) || isblank(ch);
}
コード例 #7
0
ファイル: ed.c プロジェクト: NikhilNJ/screenplay-dx
/*
 * Do the substitute command.
 * The current line is set to the last substitution done.
 */
static void subCommand(const char *cmd, int num1, int num2)
{
	char *cp, *oldStr, *newStr, buf[USERSIZE];
	int delim, oldLen, newLen, deltaLen, offset;
	LINE *lp, *nlp;
	int globalFlag, printFlag, didSub, needPrint;

	if (bad_nums(num1, num2, "substitute"))
		return;

	globalFlag = FALSE;
	printFlag = FALSE;
	didSub = FALSE;
	needPrint = FALSE;

	/*
	 * Copy the command so we can modify it.
	 */
	strcpy(buf, cmd);
	cp = buf;

	if (isblank(*cp) || (*cp == '\0')) {
		bb_error_msg("bad delimiter for substitute");
		return;
	}

	delim = *cp++;
	oldStr = cp;

	cp = strchr(cp, delim);
	if (cp == NULL) {
		bb_error_msg("missing 2nd delimiter for substitute");
		return;
	}

	*cp++ = '\0';

	newStr = cp;
	cp = strchr(cp, delim);

	if (cp)
		*cp++ = '\0';
	else
		cp = (char*)"";

	while (*cp) switch (*cp++) {
		case 'g':
			globalFlag = TRUE;
			break;
		case 'p':
			printFlag = TRUE;
			break;
		default:
			bb_error_msg("unknown option for substitute");
			return;
	}

	if (*oldStr == '\0') {
		if (searchString[0] == '\0') {
			bb_error_msg("no previous search string");
			return;
		}
		oldStr = searchString;
	}

	if (oldStr != searchString)
		strcpy(searchString, oldStr);

	lp = findLine(num1);
	if (lp == NULL)
		return;

	oldLen = strlen(oldStr);
	newLen = strlen(newStr);
	deltaLen = newLen - oldLen;
	offset = 0;
	nlp = NULL;

	while (num1 <= num2) {
		offset = findString(lp, oldStr, oldLen, offset);

		if (offset < 0) {
			if (needPrint) {
				printLines(num1, num1, FALSE);
				needPrint = FALSE;
			}
			offset = 0;
			lp = lp->next;
			num1++;
			continue;
		}

		needPrint = printFlag;
		didSub = TRUE;
		dirty = TRUE;

		/*
		 * If the replacement string is the same size or shorter
		 * than the old string, then the substitution is easy.
		 */
		if (deltaLen <= 0) {
			memcpy(&lp->data[offset], newStr, newLen);
			if (deltaLen) {
				memcpy(&lp->data[offset + newLen],
					&lp->data[offset + oldLen],
					lp->len - offset - oldLen);

				lp->len += deltaLen;
			}
			offset += newLen;
			if (globalFlag)
				continue;
			if (needPrint) {
				printLines(num1, num1, FALSE);
				needPrint = FALSE;
			}
			lp = lp->next;
			num1++;
			continue;
		}

		/*
		 * The new string is larger, so allocate a new line
		 * structure and use that.  Link it in in place of
		 * the old line structure.
		 */
		nlp = malloc(sizeof(LINE) + lp->len + deltaLen);
		if (nlp == NULL) {
			bb_error_msg("cannot get memory for line");
			return;
		}

		nlp->len = lp->len + deltaLen;

		memcpy(nlp->data, lp->data, offset);
		memcpy(&nlp->data[offset], newStr, newLen);
		memcpy(&nlp->data[offset + newLen],
			&lp->data[offset + oldLen],
			lp->len - offset - oldLen);

		nlp->next = lp->next;
		nlp->prev = lp->prev;
		nlp->prev->next = nlp;
		nlp->next->prev = nlp;

		if (curLine == lp)
			curLine = nlp;

		free(lp);
		lp = nlp;

		offset += newLen;

		if (globalFlag)
			continue;

		if (needPrint) {
			printLines(num1, num1, FALSE);
			needPrint = FALSE;
		}

		lp = lp->next;
		num1++;
	}

	if (!didSub)
		bb_error_msg("no substitutions found for \"%s\"", oldStr);
}
コード例 #8
0
ファイル: expand.c プロジェクト: dezelin/kBuild
/* Scan STRING for variable references and expansion-function calls.  Only
   LENGTH bytes of STRING are actually scanned.  If LENGTH is -1, scan until
   a null byte is found.

   Write the results to LINE, which must point into `variable_buffer'.  If
   LINE is NULL, start at the beginning of the buffer.
   Return a pointer to LINE, or to the beginning of the buffer if LINE is
   NULL.
 */
char *
variable_expand_string (char *line, const char *string, long length)
{
  struct variable *v;
  const char *p, *p1;
  char *abuf = NULL;
  char *o;
  unsigned int line_offset;

  if (!line)
    line = initialize_variable_output();
  o = line;
  line_offset = line - variable_buffer;

  if (length == 0)
    {
      variable_buffer_output (o, "", 1);
      return (variable_buffer);
    }

  /* If we want a subset of the string, allocate a temporary buffer for it.
     Most of the functions we use here don't work with length limits.  */
  if (length > 0 && string[length] != '\0')
    {
      abuf = xmalloc(length+1);
      memcpy(abuf, string, length);
      abuf[length] = '\0';
      string = abuf;
    }
  p = string;

  while (1)
    {
      /* Copy all following uninteresting chars all at once to the
         variable output buffer, and skip them.  Uninteresting chars end
	 at the next $ or the end of the input.  */

      p1 = strchr (p, '$');

      o = variable_buffer_output (o, p, p1 != 0 ? (unsigned int)(p1 - p) : strlen (p) + 1);

      if (p1 == 0)
	break;
      p = p1 + 1;

      /* Dispatch on the char that follows the $.  */

      switch (*p)
	{
	case '$':
	  /* $$ seen means output one $ to the variable output buffer.  */
	  o = variable_buffer_output (o, p, 1);
	  break;

	case '(':
	case '{':
	  /* $(...) or ${...} is the general case of substitution.  */
	  {
	    char openparen = *p;
	    char closeparen = (openparen == '(') ? ')' : '}';
            const char *begp;
	    const char *beg = p + 1;
	    char *op;
            char *abeg = NULL;
	    const char *end, *colon;

	    op = o;
	    begp = p;
	    if (handle_function (&op, &begp))
	      {
		o = op;
		p = begp;
		break;
	      }

	    /* Is there a variable reference inside the parens or braces?
	       If so, expand it before expanding the entire reference.  */

	    end = strchr (beg, closeparen);
	    if (end == 0)
              /* Unterminated variable reference.  */
              fatal (*expanding_var, _("unterminated variable reference"));
	    p1 = lindex (beg, end, '$');
	    if (p1 != 0)
	      {
		/* BEG now points past the opening paren or brace.
		   Count parens or braces until it is matched.  */
		int count = 0;
		for (p = beg; *p != '\0'; ++p)
		  {
		    if (*p == openparen)
		      ++count;
		    else if (*p == closeparen && --count < 0)
		      break;
		  }
		/* If COUNT is >= 0, there were unmatched opening parens
		   or braces, so we go to the simple case of a variable name
		   such as `$($(a)'.  */
		if (count < 0)
		  {
		    abeg = expand_argument (beg, p); /* Expand the name.  */
		    beg = abeg;
		    end = strchr (beg, '\0');
		  }
	      }
	    else
	      /* Advance P to the end of this reference.  After we are
                 finished expanding this one, P will be incremented to
                 continue the scan.  */
	      p = end;

	    /* This is not a reference to a built-in function and
	       any variable references inside are now expanded.
	       Is the resultant text a substitution reference?  */

	    colon = lindex (beg, end, ':');
	    if (colon)
	      {
		/* This looks like a substitution reference: $(FOO:A=B).  */
		const char *subst_beg, *subst_end, *replace_beg, *replace_end;

		subst_beg = colon + 1;
		subst_end = lindex (subst_beg, end, '=');
		if (subst_end == 0)
		  /* There is no = in sight.  Punt on the substitution
		     reference and treat this as a variable name containing
		     a colon, in the code below.  */
		  colon = 0;
		else
		  {
		    replace_beg = subst_end + 1;
		    replace_end = end;

		    /* Extract the variable name before the colon
		       and look up that variable.  */
		    v = lookup_variable (beg, colon - beg);
		    if (v == 0)
		      warn_undefined (beg, colon - beg);

                    /* If the variable is not empty, perform the
                       substitution.  */
		    if (v != 0 && *v->value != '\0')
		      {
			char *pattern, *replace, *ppercent, *rpercent;
			char *value = (v->recursive
                                       ? recursively_expand (v)
				       : v->value);

                        /* Copy the pattern and the replacement.  Add in an
                           extra % at the beginning to use in case there
                           isn't one in the pattern.  */
                        pattern = alloca (subst_end - subst_beg + 2);
                        *(pattern++) = '%';
                        memcpy (pattern, subst_beg, subst_end - subst_beg);
                        pattern[subst_end - subst_beg] = '\0';

                        replace = alloca (replace_end - replace_beg + 2);
                        *(replace++) = '%';
                        memcpy (replace, replace_beg,
                               replace_end - replace_beg);
                        replace[replace_end - replace_beg] = '\0';

                        /* Look for %.  Set the percent pointers properly
                           based on whether we find one or not.  */
			ppercent = find_percent (pattern);
			if (ppercent)
                          {
                            ++ppercent;
                            rpercent = find_percent (replace);
                            if (rpercent)
                              ++rpercent;
                          }
			else
                          {
                            ppercent = pattern;
                            rpercent = replace;
                            --pattern;
                            --replace;
                          }

                        o = patsubst_expand_pat (o, value, pattern, replace,
                                                 ppercent, rpercent);

			if (v->recursive)
			  free (value);
		      }
		  }
	      }

	    if (colon == 0)
	      /* This is an ordinary variable reference.
		 Look up the value of the variable.  */
		o = reference_variable (o, beg, end - beg);

	  if (abeg)
	    free (abeg);
	  }
	  break;

	case '\0':
	  break;

	default:
	  if (isblank ((unsigned char)p[-1]))
	    break;

	  /* A $ followed by a random char is a variable reference:
	     $a is equivalent to $(a).  */
          o = reference_variable (o, p, 1);

	  break;
	}

      if (*p == '\0')
	break;

      ++p;
    }

  if (abuf)
    free (abuf);

  variable_buffer_output (o, "", 1);
  return (variable_buffer + line_offset);
}
コード例 #9
0
ファイル: expand.c プロジェクト: dezelin/kBuild
/* Scan STRING for variable references and expansion-function calls.  Only
   LENGTH bytes of STRING are actually scanned.  If LENGTH is -1, scan until
   a null byte is found.

   Write the results to LINE, which must point into `variable_buffer'.  If
   LINE is NULL, start at the beginning of the buffer.
   Return a pointer to LINE, or to the beginning of the buffer if LINE is
   NULL. Set EOLP to point to the string terminator.
 */
char *
variable_expand_string_2 (char *line, const char *string, long length, char **eolp)
{
  struct variable *v;
  const char *p, *p1, *eos;
  char *o;
  unsigned int line_offset;

  if (!line)
    line = initialize_variable_output();
  o = line;
  line_offset = line - variable_buffer;

  if (length < 0)
    length = strlen (string);
  else
    MY_ASSERT_MSG (string + length == (p1 = memchr (string, '\0', length)) || !p1, ("len=%ld p1=%p %s\n", length, p1, line));

  /* Simple 1: Emptry string. */

  if (length == 0)
    {
      o = variable_buffer_output (o, "\0", 2);
      *eolp = o - 2;
      return (variable_buffer + line_offset);
    }

  /* Simple 2: Nothing to expand. ~50% if the kBuild calls. */

  p1 = (const char *)memchr (string, '$', length);
  if (p1 == 0)
    {
      o = variable_buffer_output (o, string, length);
      o = variable_buffer_output (o, "\0", 2);
      *eolp = o - 2;
      assert (strchr (variable_buffer + line_offset, '\0') == *eolp);
      return (variable_buffer + line_offset);
    }

  p = string;
  eos = p + length;

  while (1)
    {
      /* Copy all following uninteresting chars all at once to the
         variable output buffer, and skip them.  Uninteresting chars end
	 at the next $ or the end of the input.  */

      o = variable_buffer_output (o, p, p1 != 0 ? (p1 - p) : (eos - p));

      if (p1 == 0)
	break;
      p = p1 + 1;

      /* Dispatch on the char that follows the $.  */

      switch (*p)
	{
	case '$':
	  /* $$ seen means output one $ to the variable output buffer.  */
	  o = variable_buffer_output (o, p, 1);
	  break;

	case '(':
	case '{':
	  /* $(...) or ${...} is the general case of substitution.  */
	  {
	    char openparen = *p;
	    char closeparen = (openparen == '(') ? ')' : '}';
            const char *begp;
	    const char *beg = p + 1;
	    char *op;
            char *abeg = NULL;
            unsigned int alen = 0;
	    const char *end, *colon;

	    op = o;
	    begp = p;
            end = may_be_function_name (p + 1, eos);
	    if (    end
                &&  handle_function (&op, &begp, end, eos))
	      {
		o = op;
		p = begp;
                MY_ASSERT_MSG (!(p1 = memchr (variable_buffer + line_offset, '\0', o - (variable_buffer + line_offset))),
                               ("line=%p o/exp_end=%p act_end=%p\n", variable_buffer + line_offset, o, p1));
		break;
	      }

	    /* Is there a variable reference inside the parens or braces?
	       If so, expand it before expanding the entire reference.  */

	    end = memchr (beg, closeparen, eos - beg);
	    if (end == 0)
              /* Unterminated variable reference.  */
              fatal (*expanding_var, _("unterminated variable reference"));
	    p1 = lindex (beg, end, '$');
	    if (p1 != 0)
	      {
		/* BEG now points past the opening paren or brace.
		   Count parens or braces until it is matched.  */
		int count = 0;
		for (p = beg; p < eos; ++p)
		  {
		    if (*p == openparen)
		      ++count;
		    else if (*p == closeparen && --count < 0)
		      break;
		  }
		/* If COUNT is >= 0, there were unmatched opening parens
		   or braces, so we go to the simple case of a variable name
		   such as `$($(a)'.  */
		if (count < 0)
		  {
                    unsigned int len;
                    char saved;

                     /* Expand the name.  */
                    saved = *p;
                    *(char *)p = '\0'; /* XXX: proove that this is safe! XXX2: shouldn't be necessary any longer! */
                    abeg = allocated_variable_expand_3 (beg, p - beg, &len, &alen);
                    beg = abeg;
                    end = beg + len;
                    *(char *)p = saved;
		  }
	      }
	    else
	      /* Advance P to the end of this reference.  After we are
                 finished expanding this one, P will be incremented to
                 continue the scan.  */
	      p = end;

	    /* This is not a reference to a built-in function and
	       any variable references inside are now expanded.
	       Is the resultant text a substitution reference?  */

	    colon = lindex (beg, end, ':');
	    if (colon)
	      {
		/* This looks like a substitution reference: $(FOO:A=B).  */
		const char *subst_beg, *subst_end, *replace_beg, *replace_end;

		subst_beg = colon + 1;
		subst_end = lindex (subst_beg, end, '=');
		if (subst_end == 0)
		  /* There is no = in sight.  Punt on the substitution
		     reference and treat this as a variable name containing
		     a colon, in the code below.  */
		  colon = 0;
		else
		  {
		    replace_beg = subst_end + 1;
		    replace_end = end;

		    /* Extract the variable name before the colon
		       and look up that variable.  */
		    v = lookup_variable (beg, colon - beg);
		    if (v == 0)
		      warn_undefined (beg, colon - beg);

                    /* If the variable is not empty, perform the
                       substitution.  */
		    if (v != 0 && *v->value != '\0')
		      {
			char *pattern, *replace, *ppercent, *rpercent;
			char *value = (v->recursive
                                       ? recursively_expand (v)
				       : v->value);

                        /* Copy the pattern and the replacement.  Add in an
                           extra % at the beginning to use in case there
                           isn't one in the pattern.  */
                        pattern = alloca (subst_end - subst_beg + 2);
                        *(pattern++) = '%';
                        memcpy (pattern, subst_beg, subst_end - subst_beg);
                        pattern[subst_end - subst_beg] = '\0';

                        replace = alloca (replace_end - replace_beg + 2);
                        *(replace++) = '%';
                        memcpy (replace, replace_beg,
                               replace_end - replace_beg);
                        replace[replace_end - replace_beg] = '\0';

                        /* Look for %.  Set the percent pointers properly
                           based on whether we find one or not.  */
			ppercent = find_percent (pattern);
			if (ppercent)
                          {
                            ++ppercent;
                            rpercent = find_percent (replace);
                            if (rpercent)
                              ++rpercent;
                          }
			else
                          {
                            ppercent = pattern;
                            rpercent = replace;
                            --pattern;
                            --replace;
                          }

                        o = patsubst_expand_pat (o, value, pattern, replace,
                                                 ppercent, rpercent);

			if (v->recursive)
			  free (value);
		      }
		  }
	      }

	    if (colon == 0)
	      /* This is an ordinary variable reference.
		 Look up the value of the variable.  */
		o = reference_variable (o, beg, end - beg);

	  if (abeg)
            recycle_variable_buffer (abeg, alen);
	  }
	  break;

	case '\0':
          assert (p == eos);
          break;

	default:
	  if (isblank ((unsigned char)p[-1])) /* XXX: This looks incorrect, previous is '$' */
	    break;

	  /* A $ followed by a random char is a variable reference:
	     $a is equivalent to $(a).  */
          o = reference_variable (o, p, 1);

	  break;
	}

      if (++p >= eos)
	break;
      p1 = memchr (p, '$', eos - p);
    }

  o = variable_buffer_output (o, "\0", 2); /* KMK: compensate for the strlen + 1 that was removed above. */
  *eolp = o - 2;
  MY_ASSERT_MSG (strchr (variable_buffer + line_offset, '\0') == *eolp,
                 ("expected=%d actual=%d\nlength=%ld string=%.*s\n",
                  (int)(*eolp - variable_buffer + line_offset), (int)strlen(variable_buffer + line_offset),
                  length, (int)length, string));
  return (variable_buffer + line_offset);
}
コード例 #10
0
static struct dep_t *build_dep ( void )
{
	int fd;
	struct utsname un;
	struct dep_t *first = 0;
	struct dep_t *current = 0;
	char buffer[256];
	char *filename = buffer;
	int continuation_line = 0;
	
	if ( uname ( &un ))
		return 0;
		
	// check for buffer overflow in following code
	if ( xstrlen ( un.release ) > ( sizeof( buffer ) - 64 )) {
		return 0;
	}
				
	strcpy ( filename, "/lib/modules/" );
	strcat ( filename, un.release );
	strcat ( filename, "/modules.dep" );

	if (( fd = open ( filename, O_RDONLY )) < 0 )
		return 0;

	while ( reads ( fd, buffer, sizeof( buffer ))) {
		int l = xstrlen ( buffer );
		char *p = 0;
		
		while ( isspace ( buffer [l-1] )) {
			buffer [l-1] = 0;
			l--;
		}
		
		if ( l == 0 ) {
			continuation_line = 0;
			continue;
		}
		
		if ( !continuation_line ) {		
			char *col = strchr ( buffer, ':' );
		
			if ( col ) {
				char *mods;
				char *mod;
				int ext = 0;
				
				*col = 0;
				mods = strrchr ( buffer, '/' );
				
				if ( !mods )
					mods = buffer;
				else
					mods++;
					
				if (( *(col-2) == '.' ) && ( *(col-1) == 'o' ))
					ext = 2;
				
				mod = xstrndup ( mods, col - mods - ext );
					
				if ( !current ) {
					first = current = (struct dep_t *) xmalloc ( sizeof ( struct dep_t ));
				}
				else {
					current-> m_next = (struct dep_t *) xmalloc ( sizeof ( struct dep_t ));
					current = current-> m_next;
				}
				current-> m_module  = mod;
				current-> m_isalias = 0;
				current-> m_depcnt  = 0;
				current-> m_deparr  = 0;
				current-> m_next    = 0;
						
				//printf ( "%s:\n", mod );
						
				p = col + 1;		
			}
			else
				p = 0;
		}
		else
			p = buffer;
			
		if ( p && *p ) {
			char *end = &buffer [l-1];
			char *deps = strrchr ( end, '/' );
			char *dep;
			int ext = 0;
			
			while ( isblank ( *end ) || ( *end == '\\' ))
				end--;
				
			deps = strrchr ( p, '/' );
			
			if ( !deps || ( deps < p )) {
				deps = p;
		
				while ( isblank ( *deps ))
					deps++;
			}
			else
				deps++;
			
			if (( *(end-1) == '.' ) && ( *end == 'o' ))
				ext = 2;

			/* Cope with blank lines */
			if ((end-deps-ext+1) <= 0)
				continue;
			
			dep = xstrndup ( deps, end - deps - ext + 1 );
			
			current-> m_depcnt++;
			current-> m_deparr = (char **) xrealloc ( current-> m_deparr, sizeof ( char *) * current-> m_depcnt );
			current-> m_deparr [current-> m_depcnt - 1] = dep;		
			
			//printf ( "    %d) %s\n", current-> m_depcnt, current-> m_deparr [current-> m_depcnt -1] );
		}
	
		if ( buffer [l-1] == '\\' )
			continuation_line = 1;
		else
			continuation_line = 0;
	}
	close ( fd );

	// alias parsing is not 100% correct (no correct handling of continuation lines within an alias) !

	if (( fd = open ( "/etc/modules.conf", O_RDONLY )) < 0 )
		if (( fd = open ( "/etc/conf.modules", O_RDONLY )) < 0 )
			return first;
	
	continuation_line = 0;
	while ( reads ( fd, buffer, sizeof( buffer ))) {
		int l;
		char *p;
		
		p = strchr ( buffer, '#' );	
		if ( p )
			*p = 0;
			
		l = xstrlen ( buffer );
	
		while ( l && isspace ( buffer [l-1] )) {
			buffer [l-1] = 0;
			l--;
		}
		
		if ( l == 0 ) {
			continuation_line = 0;
			continue;
		}
		
		if ( !continuation_line ) {		
			if (( strncmp ( buffer, "alias", 5 ) == 0 ) && isspace ( buffer [5] )) {
				char *alias, *mod;

				alias = buffer + 6;
				
				while ( isspace ( *alias ))
					alias++;			
				mod = alias;					
				while ( !isspace ( *mod ))
					mod++;
				*mod = 0;
				mod++;
				while ( isspace ( *mod ))
					mod++;
										
//					fprintf ( stderr, "ALIAS: '%s' -> '%s'\n", alias, mod );
				
				if ( !current ) {
					first = current = (struct dep_t *) xmalloc ( sizeof ( struct dep_t ));
				}
				else {
					current-> m_next = (struct dep_t *) xmalloc ( sizeof ( struct dep_t ));
					current = current-> m_next;
				}
				current-> m_module  = xstrdup ( alias );
				current-> m_isalias = 1;
				
				if (( strcmp ( alias, "off" ) == 0 ) || ( strcmp ( alias, "null" ) == 0 )) {
					current-> m_depcnt = 0;
					current-> m_deparr = 0;
				}
				else {
					current-> m_depcnt  = 1;
					current-> m_deparr  = xmalloc ( 1 * sizeof( char * ));
					current-> m_deparr[0] = xstrdup ( mod );
				}
				current-> m_next    = 0;					
			}				
		}
	}
	close ( fd );
	
	return first;
}
コード例 #11
0
ファイル: HTTPPacket.cpp プロジェクト: jaejungkim/MonaServer
const UInt8* HTTPPacket::build(Exception& ex,PoolBuffer& pBuffer,const UInt8* data,UInt32& size) {
	/// append data
	if (!_pBuffer.empty()) {
		UInt32 oldSize = _pBuffer->size();
		_pBuffer->resize(oldSize+size,true);
		memcpy(_pBuffer->data()+oldSize, data,size);
	} else
		_pBuffer.swap(pBuffer); // exchange the buffers

	/// read data
	UInt8				newLineCount(0);
	ReadingStep			step(CMD);
	UInt8*				current(_pBuffer->data());
	UInt8*				end(current+_pBuffer->size());
	const char*			signifiant(NULL);
	const char*			key(NULL);

	for (current; current < end;++current) {
		// http header
		UInt8 byte = *current;

		if (byte=='\r') {
			++newLineCount;
			step = LINE_RETURN;
		} else if (step==LINE_RETURN && byte=='\n')
			++newLineCount;
		else {
			newLineCount = 0;

			if ((step == LEFT || step == CMD || step == PATH) && isspace(byte)) {
				if (step == CMD) {
					// by default command == GET
					if ((command = HTTP::ParseCommand(ex, signifiant)) == HTTP::COMMAND_UNKNOWN) {
						_pBuffer.release();
						return NULL;
					}
					signifiant = NULL;
					step = PATH;
				} else if (step == PATH) {
					_buffer.assign(signifiant, (const char*)current - signifiant);
					// parse query
					filePos = Util::UnpackUrl(_buffer, path,query);
					signifiant = NULL;
					step = VERSION;
				} else
					++signifiant; // for trim begin of key or value
				continue;
			} else if (step != CMD && !key && byte == ':') {
				// KEY
				key = signifiant;
				step = LEFT;
				UInt8* prev = current;
				while (isblank(*--current));
				*(current+1) = '\0';
				current = prev;
				headers.emplace_back(signifiant);
				signifiant = (const char*)current + 1;
			} else if (step == CMD || step == PATH || step == VERSION) {
				if (!signifiant)
					signifiant = (const char*)current;
				if (step == CMD && (current-_pBuffer->data())>7) {
					// not a HTTP valid packet, consumes all
					_pBuffer.release();
					ex.set(Exception::PROTOCOL, "unvalid HTTP packet");
					return NULL;
				}
			} else
				step = RIGHT;
			continue;
		}
		
		if (newLineCount == 2) {
			if (signifiant) {
				// KEY = VALUE
				UInt8* prev = current--;
				while (isblank(*--current));
				*(current+1) = '\0';
				current = prev;
				if (!key) { // version case!
					String::ToNumber(signifiant+5, version);
				} else {
					headers.emplace_back(signifiant);
					parseHeader(ex,key,signifiant);
					key = NULL;
				}
			}
			step = LEFT;
			signifiant = (const char*)current+1;
		} else if (newLineCount == 4) {
			content = current + 1;
			current += contentLength;
			break;
		}
	}

	if (current >= end)
		return NULL;  // wait next data

	// exchange the buffers
	pBuffer.swap(_pBuffer);

	UInt32 rest = end-current-1;
	if (rest == 0) {
		_pBuffer.release(); // release buffer
		size = pBuffer->size();
		return pBuffer->data();
	}

	// prepare next iteration
	_pBuffer->resize(rest,false);
	memcpy(_pBuffer->data(), current + 1, rest);
	

	// shrink data
	size = size-rest;
	return pBuffer->data();
}
コード例 #12
0
ファイル: rcfile.c プロジェクト: rofl0r/nano
/* Parse the rcfile, once it has been opened successfully at rcstream,
 * and close it afterwards.  If syntax_only is TRUE, only allow the file
 * to contain color syntax commands: syntax, color, and icolor. */
void parse_rcfile(FILE *rcstream
#ifdef ENABLE_COLOR
	, bool syntax_only
#endif
	)
{
    char *buf = NULL;
    ssize_t len;
    size_t n = 0;

    while ((len = getline(&buf, &n, rcstream)) > 0) {
	char *ptr, *keyword, *option;
	int set = 0;
	size_t i;

	/* Ignore the newline. */
	if (buf[len - 1] == '\n')
	    buf[len - 1] = '\0';

	lineno++;
	ptr = buf;
	while (isblank(*ptr))
	    ptr++;

	/* If we have a blank line or a comment, skip to the next
	 * line. */
	if (*ptr == '\0' || *ptr == '#')
	    continue;

	/* Otherwise, skip to the next space. */
	keyword = ptr;
	ptr = parse_next_word(ptr);

	/* Try to parse the keyword. */
	if (strcasecmp(keyword, "set") == 0) {
#ifdef ENABLE_COLOR
	    if (syntax_only)
		rcfile_error(
			N_("Command \"%s\" not allowed in included file"),
			keyword);
	    else
#endif
		set = 1;
	} else if (strcasecmp(keyword, "unset") == 0) {
#ifdef ENABLE_COLOR
	    if (syntax_only)
		rcfile_error(
			N_("Command \"%s\" not allowed in included file"),
			keyword);
	    else
#endif
		set = -1;
	}
#ifdef ENABLE_COLOR
	else if (strcasecmp(keyword, "include") == 0) {
	    if (syntax_only)
		rcfile_error(
			N_("Command \"%s\" not allowed in included file"),
			keyword);
	    else
		parse_include(ptr);
	} else if (strcasecmp(keyword, "syntax") == 0) {
	    if (endsyntax != NULL && endcolor == NULL)
		rcfile_error(N_("Syntax \"%s\" has no color commands"),
			endsyntax->desc);
	    parse_syntax(ptr);
	}
	else if (strcasecmp(keyword, "magic") == 0) {
 	    parse_magictype(ptr);
	} else if (strcasecmp(keyword, "header") == 0)
	    parse_headers(ptr);
	else if (strcasecmp(keyword, "color") == 0)
	    parse_colors(ptr, FALSE);
	else if (strcasecmp(keyword, "icolor") == 0)
	    parse_colors(ptr, TRUE);
	else if (strcasecmp(keyword, "bind") == 0)
	    parse_keybinding(ptr);
	else if (strcasecmp(keyword, "unbind") == 0)
	    parse_unbinding(ptr);
#endif /* ENABLE_COLOR */
	else
	    rcfile_error(N_("Command \"%s\" not understood"), keyword);

	if (set == 0)
	    continue;

	if (*ptr == '\0') {
	    rcfile_error(N_("Missing flag"));
	    continue;
	}

	option = ptr;
	ptr = parse_next_word(ptr);

	for (i = 0; rcopts[i].name != NULL; i++) {
	    if (strcasecmp(option, rcopts[i].name) == 0) {
#ifdef DEBUG
		fprintf(stderr, "parse_rcfile(): name = \"%s\"\n", rcopts[i].name);
#endif
		if (set == 1) {
		    if (rcopts[i].flag != 0)
			/* This option has a flag, so it doesn't take an
			 * argument. */
			SET(rcopts[i].flag);
		    else {
			/* This option doesn't have a flag, so it takes
			 * an argument. */
			if (*ptr == '\0') {
			    rcfile_error(
				N_("Option \"%s\" requires an argument"),
				rcopts[i].name);
			    break;
			}
			option = ptr;
			if (*option == '"')
			    option++;
			ptr = parse_argument(ptr);

			option = mallocstrcpy(NULL, option);
#ifdef DEBUG
			fprintf(stderr, "option = \"%s\"\n", option);
#endif

			/* Make sure option is a valid multibyte
			 * string. */
			if (!is_valid_mbstring(option)) {
			    rcfile_error(
				N_("Option is not a valid multibyte string"));
			    break;
			}

#ifndef DISABLE_OPERATINGDIR
			if (strcasecmp(rcopts[i].name, "operatingdir") == 0)
			    operating_dir = option;
			else
#endif
#ifndef DISABLE_WRAPJUSTIFY
			if (strcasecmp(rcopts[i].name, "fill") == 0) {
			    if (!parse_num(option, &wrap_at)) {
				rcfile_error(
					N_("Requested fill size \"%s\" is invalid"),
					option);
				wrap_at = -CHARS_FROM_EOL;
			    } else
				free(option);
			} else
#endif
#ifndef NANO_TINY
			if (strcasecmp(rcopts[i].name,
				"matchbrackets") == 0) {
			    matchbrackets = option;
			    if (has_blank_mbchars(matchbrackets)) {
				rcfile_error(
					N_("Non-blank characters required"));
				free(matchbrackets);
				matchbrackets = NULL;
			    }
			} else if (strcasecmp(rcopts[i].name,
				"whitespace") == 0) {
			    whitespace = option;
			    if (mbstrlen(whitespace) != 2 ||
				strlenpt(whitespace) != 2) {
				rcfile_error(
					N_("Two single-column characters required"));
				free(whitespace);
				whitespace = NULL;
			    } else {
				whitespace_len[0] =
					parse_mbchar(whitespace, NULL,
					NULL);
				whitespace_len[1] =
					parse_mbchar(whitespace +
					whitespace_len[0], NULL, NULL);
			    }
			} else
#endif
#ifndef DISABLE_JUSTIFY
			if (strcasecmp(rcopts[i].name, "punct") == 0) {
			    punct = option;
			    if (has_blank_mbchars(punct)) {
				rcfile_error(
					N_("Non-blank characters required"));
				free(punct);
				punct = NULL;
			    }
			} else if (strcasecmp(rcopts[i].name,
				"brackets") == 0) {
			    brackets = option;
			    if (has_blank_mbchars(brackets)) {
				rcfile_error(
					N_("Non-blank characters required"));
				free(brackets);
				brackets = NULL;
			    }
			} else if (strcasecmp(rcopts[i].name,
				"quotestr") == 0)
			    quotestr = option;
			else
#endif
#ifndef NANO_TINY
			if (strcasecmp(rcopts[i].name,
				"backupdir") == 0)
			    backup_dir = option;
			else
#endif
#ifndef DISABLE_SPELLER
			if (strcasecmp(rcopts[i].name, "speller") == 0)
			    alt_speller = option;
			else
#endif
			if (strcasecmp(rcopts[i].name,
				"tabsize") == 0) {
			    if (!parse_num(option, &tabsize) ||
				tabsize <= 0) {
				rcfile_error(
					N_("Requested tab size \"%s\" is invalid"),
					option);
				tabsize = -1;
			    } else
				free(option);
			} else
			    assert(FALSE);
		    }
#ifdef DEBUG
		    fprintf(stderr, "flag = %ld\n", rcopts[i].flag);
#endif
		} else if (rcopts[i].flag != 0)
		    UNSET(rcopts[i].flag);
		else
		    rcfile_error(N_("Cannot unset flag \"%s\""),
			rcopts[i].name);
		/* Looks like we still need this specific hack for undo */
		if (strcasecmp(rcopts[i].name, "undo") == 0)
		    shortcut_init(0);
		break;
	    }
	}
	if (rcopts[i].name == NULL)
	    rcfile_error(N_("Unknown flag \"%s\""), option);
    }

#ifdef ENABLE_COLOR
    if (endsyntax != NULL && endcolor == NULL)
	rcfile_error(N_("Syntax \"%s\" has no color commands"),
		endsyntax->desc);
#endif

    free(buf);
    fclose(rcstream);
    lineno = 0;

    check_vitals_mapped();
    return;
}
コード例 #13
0
void
initialise_months(void)
{
	const nl_item item[12] = { ABMON_1, ABMON_2, ABMON_3, ABMON_4,
	    ABMON_5, ABMON_6, ABMON_7, ABMON_8, ABMON_9, ABMON_10,
	    ABMON_11, ABMON_12 };
	unsigned char *tmp;
	size_t len;

	if (MB_CUR_MAX == 1) {
		if (cmonths == NULL) {
			unsigned char *m;

			cmonths = sort_malloc(sizeof(unsigned char*) * 12);
			for (int i = 0; i < 12; i++) {
				cmonths[i] = NULL;
				tmp = (unsigned char *) nl_langinfo(item[i]);
				if (tmp == NULL)
					continue;
				if (debug_sort)
					printf("month[%d]=%s\n", i, tmp);
				len = strlen((char*)tmp);
				if (len < 1)
					continue;
				while (isblank(*tmp))
					++tmp;
				m = sort_malloc(len + 1);
				memcpy(m, tmp, len + 1);
				m[len] = '\0';
				for (unsigned int j = 0; j < len; j++)
					m[j] = toupper(m[j]);
				cmonths[i] = m;
			}
		}

	} else {
		if (wmonths == NULL) {
			wchar_t *m;

			wmonths = sort_malloc(sizeof(wchar_t *) * 12);
			for (int i = 0; i < 12; i++) {
				wmonths[i] = NULL;
				tmp = (unsigned char *) nl_langinfo(item[i]);
				if (tmp == NULL)
					continue;
				if (debug_sort)
					printf("month[%d]=%s\n", i, tmp);
				len = strlen((char*)tmp);
				if (len < 1)
					continue;
				while (isblank(*tmp))
					++tmp;
				m = sort_malloc(SIZEOF_WCHAR_STRING(len + 1));
				if (mbstowcs(m, (char*)tmp, len) == ((size_t) -1))
					continue;
				m[len] = L'\0';
				for (unsigned int j = 0; j < len; j++)
					m[j] = towupper(m[j]);
				wmonths[i] = m;
			}
		}
	}
}
コード例 #14
0
/*
 * v_sentencef -- [count])
 *	Move forward count sentences.
 *
 * PUBLIC: int v_sentencef __P((SCR *, VICMD *));
 */
int
v_sentencef(SCR *sp, VICMD *vp)
{
	enum { BLANK, NONE, PERIOD } state;
	VCS cs;
	size_t len;
	u_long cnt;

	cs.cs_lno = vp->m_start.lno;
	cs.cs_cno = vp->m_start.cno;
	if (cs_init(sp, &cs))
		return (1);

	cnt = F_ISSET(vp, VC_C1SET) ? vp->count : 1;

	/*
	 * !!!
	 * If in white-space, the next start of sentence counts as one.
	 * This may not handle "  .  " correctly, but it's real unclear
	 * what correctly means in that case.
	 */
	if (cs.cs_flags == CS_EMP || cs.cs_flags == 0 && isblank(cs.cs_ch)) {
		if (cs_fblank(sp, &cs))
			return (1);
		if (--cnt == 0) {
			if (vp->m_start.lno != cs.cs_lno ||
			    vp->m_start.cno != cs.cs_cno)
				goto okret;
			return (1);
		}
	}

	for (state = NONE;;) {
		if (cs_next(sp, &cs))
			return (1);
		if (cs.cs_flags == CS_EOF)
			break;
		if (cs.cs_flags == CS_EOL) {
			if ((state == PERIOD || state == BLANK) && --cnt == 0) {
				if (cs_next(sp, &cs))
					return (1);
				if (cs.cs_flags == 0 &&
				    isblank(cs.cs_ch) && cs_fblank(sp, &cs))
					return (1);
				goto okret;
			}
			state = NONE;
			continue;
		}
		if (cs.cs_flags == CS_EMP) {	/* An EMP is two sentences. */
			if (--cnt == 0)
				goto okret;
			if (cs_fblank(sp, &cs))
				return (1);
			if (--cnt == 0)
				goto okret;
			state = NONE;
			continue;
		}
		switch (cs.cs_ch) {
		case '.':
		case '?':
		case '!':
			state = PERIOD;
			break;
		case ')':
		case ']':
		case '"':
		case '\'':
			if (state != PERIOD)
				state = NONE;
			break;
		case '\t':
			if (state == PERIOD)
				state = BLANK;
			/* FALLTHROUGH */
		case ' ':
			if (state == PERIOD) {
				state = BLANK;
				break;
			}
			if (state == BLANK && --cnt == 0) {
				if (cs_fblank(sp, &cs))
					return (1);
				goto okret;
			}
			/* FALLTHROUGH */
		default:
			state = NONE;
			break;
		}
	}

	/* EOF is a movement sink, but it's an error not to have moved. */
	if (vp->m_start.lno == cs.cs_lno && vp->m_start.cno == cs.cs_cno) {
		v_eof(sp, NULL);
		return (1);
	}

okret:	vp->m_stop.lno = cs.cs_lno;
	vp->m_stop.cno = cs.cs_cno;

	/*
	 * !!!
	 * Historic, uh, features, yeah, that's right, call 'em features.
	 * If the starting and ending cursor positions are at the first
	 * column in their lines, i.e. the movement is cutting entire lines,
	 * the buffer is in line mode, and the ending position is the last
	 * character of the previous line.  Note check to make sure that
	 * it's not within a single line.
	 *
	 * Non-motion commands move to the end of the range.  Delete and
	 * yank stay at the start.  Ignore others.  Adjust the end of the
	 * range for motion commands.
	 */
	if (ISMOTION(vp)) {
		if (vp->m_start.cno == 0 &&
		    (cs.cs_flags != 0 || vp->m_stop.cno == 0)) {
			if (vp->m_start.lno < vp->m_stop.lno) {
				if (db_get(sp,
				    --vp->m_stop.lno, DBG_FATAL, NULL, &len))
					return (1);
				vp->m_stop.cno = len ? len - 1 : 0;
			}
			F_SET(vp, VM_LMODE);
		} else
			--vp->m_stop.cno;
		vp->m_final = vp->m_start;
	} else
		vp->m_final = vp->m_stop;
	return (0);
}
コード例 #15
0
ファイル: read.c プロジェクト: mihaicarabas/dragonfly
/*
 * Main parse routine for an opened file.  This is called for each
 * opened file and simply loops around the full input file, possibly
 * nesting (i.e., with `so').
 */
static void
mparse_buf_r(struct mparse *curp, struct buf blk, int start)
{
	const struct tbl_span	*span;
	struct buf	 ln;
	enum rofferr	 rr;
	int		 i, of, rc;
	int		 pos; /* byte number in the ln buffer */
	int		 lnn; /* line number in the real file */
	unsigned char	 c;

	memset(&ln, 0, sizeof(struct buf));

	lnn = curp->line; 
	pos = 0; 

	for (i = 0; i < (int)blk.sz; ) {
		if (0 == pos && '\0' == blk.buf[i])
			break;

		if (start) {
			curp->line = lnn;
			curp->reparse_count = 0;
		}

		while (i < (int)blk.sz && (start || '\0' != blk.buf[i])) {

			/*
			 * When finding an unescaped newline character,
			 * leave the character loop to process the line.
			 * Skip a preceding carriage return, if any.
			 */

			if ('\r' == blk.buf[i] && i + 1 < (int)blk.sz &&
			    '\n' == blk.buf[i + 1])
				++i;
			if ('\n' == blk.buf[i]) {
				++i;
				++lnn;
				break;
			}

			/*
			 * Make sure we have space for at least
			 * one backslash and one other character
			 * and the trailing NUL byte.
			 */

			if (pos + 2 >= (int)ln.sz)
				resize_buf(&ln, 256);

			/* 
			 * Warn about bogus characters.  If you're using
			 * non-ASCII encoding, you're screwing your
			 * readers.  Since I'd rather this not happen,
			 * I'll be helpful and replace these characters
			 * with "?", so we don't display gibberish.
			 * Note to manual writers: use special characters.
			 */

			c = (unsigned char) blk.buf[i];

			if ( ! (isascii(c) && 
					(isgraph(c) || isblank(c)))) {
				mandoc_msg(MANDOCERR_BADCHAR, curp,
						curp->line, pos, NULL);
				i++;
				ln.buf[pos++] = '?';
				continue;
			}

			/* Trailing backslash = a plain char. */

			if ('\\' != blk.buf[i] || i + 1 == (int)blk.sz) {
				ln.buf[pos++] = blk.buf[i++];
				continue;
			}

			/*
			 * Found escape and at least one other character.
			 * When it's a newline character, skip it.
			 * When there is a carriage return in between,
			 * skip that one as well.
			 */

			if ('\r' == blk.buf[i + 1] && i + 2 < (int)blk.sz &&
			    '\n' == blk.buf[i + 2])
				++i;
			if ('\n' == blk.buf[i + 1]) {
				i += 2;
				++lnn;
				continue;
			}

			if ('"' == blk.buf[i + 1] || '#' == blk.buf[i + 1]) {
				i += 2;
				/* Comment, skip to end of line */
				for (; i < (int)blk.sz; ++i) {
					if ('\n' == blk.buf[i]) {
						++i;
						++lnn;
						break;
					}
				}

				/* Backout trailing whitespaces */
				for (; pos > 0; --pos) {
					if (ln.buf[pos - 1] != ' ')
						break;
					if (pos > 2 && ln.buf[pos - 2] == '\\')
						break;
				}
				break;
			}

			/* Catch escaped bogus characters. */

			c = (unsigned char) blk.buf[i+1];

			if ( ! (isascii(c) && 
					(isgraph(c) || isblank(c)))) {
				mandoc_msg(MANDOCERR_BADCHAR, curp,
						curp->line, pos, NULL);
				i += 2;
				ln.buf[pos++] = '?';
				continue;
			}

			/* Some other escape sequence, copy & cont. */

			ln.buf[pos++] = blk.buf[i++];
			ln.buf[pos++] = blk.buf[i++];
		}

 		if (pos >= (int)ln.sz)
			resize_buf(&ln, 256);

		ln.buf[pos] = '\0';

		/*
		 * A significant amount of complexity is contained by
		 * the roff preprocessor.  It's line-oriented but can be
		 * expressed on one line, so we need at times to
		 * readjust our starting point and re-run it.  The roff
		 * preprocessor can also readjust the buffers with new
		 * data, so we pass them in wholesale.
		 */

		of = 0;

		/*
		 * Maintain a lookaside buffer of all parsed lines.  We
		 * only do this if mparse_keep() has been invoked (the
		 * buffer may be accessed with mparse_getkeep()).
		 */

		if (curp->secondary) {
			curp->secondary->buf = 
				mandoc_realloc
				(curp->secondary->buf, 
				 curp->secondary->sz + pos + 2);
			memcpy(curp->secondary->buf + 
					curp->secondary->sz, 
					ln.buf, pos);
			curp->secondary->sz += pos;
			curp->secondary->buf
				[curp->secondary->sz] = '\n';
			curp->secondary->sz++;
			curp->secondary->buf
				[curp->secondary->sz] = '\0';
		}
rerun:
		rr = roff_parseln
			(curp->roff, curp->line, 
			 &ln.buf, &ln.sz, of, &of);

		switch (rr) {
		case (ROFF_REPARSE):
			if (REPARSE_LIMIT >= ++curp->reparse_count)
				mparse_buf_r(curp, ln, 0);
			else
				mandoc_msg(MANDOCERR_ROFFLOOP, curp,
					curp->line, pos, NULL);
			pos = 0;
			continue;
		case (ROFF_APPEND):
			pos = (int)strlen(ln.buf);
			continue;
		case (ROFF_RERUN):
			goto rerun;
		case (ROFF_IGN):
			pos = 0;
			continue;
		case (ROFF_ERR):
			assert(MANDOCLEVEL_FATAL <= curp->file_status);
			break;
		case (ROFF_SO):
			/*
			 * We remove `so' clauses from our lookaside
			 * buffer because we're going to descend into
			 * the file recursively.
			 */
			if (curp->secondary) 
				curp->secondary->sz -= pos + 1;
			mparse_readfd(curp, -1, ln.buf + of);
			if (MANDOCLEVEL_FATAL <= curp->file_status)
				break;
			pos = 0;
			continue;
		default:
			break;
		}

		/*
		 * If we encounter errors in the recursive parse, make
		 * sure we don't continue parsing.
		 */

		if (MANDOCLEVEL_FATAL <= curp->file_status)
			break;

		/*
		 * If input parsers have not been allocated, do so now.
		 * We keep these instanced between parsers, but set them
		 * locally per parse routine since we can use different
		 * parsers with each one.
		 */

		if ( ! (curp->man || curp->mdoc))
			pset(ln.buf + of, pos - of, curp);

		/* 
		 * Lastly, push down into the parsers themselves.  One
		 * of these will have already been set in the pset()
		 * routine.
		 * If libroff returns ROFF_TBL, then add it to the
		 * currently open parse.  Since we only get here if
		 * there does exist data (see tbl_data.c), we're
		 * guaranteed that something's been allocated.
		 * Do the same for ROFF_EQN.
		 */

		rc = -1;

		if (ROFF_TBL == rr)
			while (NULL != (span = roff_span(curp->roff))) {
				rc = curp->man ?
					man_addspan(curp->man, span) :
					mdoc_addspan(curp->mdoc, span);
				if (0 == rc)
					break;
			}
		else if (ROFF_EQN == rr)
			rc = curp->mdoc ? 
				mdoc_addeqn(curp->mdoc, 
					roff_eqn(curp->roff)) :
				man_addeqn(curp->man,
					roff_eqn(curp->roff));
		else if (curp->man || curp->mdoc)
			rc = curp->man ?
				man_parseln(curp->man, 
					curp->line, ln.buf, of) :
				mdoc_parseln(curp->mdoc, 
					curp->line, ln.buf, of);

		if (0 == rc) {
			assert(MANDOCLEVEL_FATAL <= curp->file_status);
			break;
		}

		/* Temporary buffers typically are not full. */

		if (0 == start && '\0' == blk.buf[i])
			break;

		/* Start the next input line. */

		pos = 0;
	}

	free(ln.buf);
}
コード例 #16
0
ファイル: stat.c プロジェクト: KDE/kde-workspace
void initStat( struct SensorModul* sm ) {
	/* The CPU load is calculated from the values in /proc/stat. The cpu
	* entry contains 7 counters. These counters count the number of ticks
	* the system has spend on user processes, system processes, nice
	* processes, idle and IO-wait time, hard and soft interrupts.
	*
	* SMP systems will have cpu1 to cpuN lines right after the cpu info. The
	* format is identical to cpu and reports the information for each cpu.
	* Linux kernels <= 2.0 do not provide this information!
	*
	* The /proc/stat file looks like this:
	*
	* cpu  <user> <nice> <system> <idling> <waiting> <hardinterrupt> <softinterrupt>
	* disk 7797 0 0 0
	* disk_rio 6889 0 0 0
	* disk_wio 908 0 0 0
	* disk_rblk 13775 0 0 0
	* disk_wblk 1816 0 0 0
	* page 27575 1330
	* swap 1 0
	* intr 50444 38672 2557 0 0 0 0 2 0 2 0 0 3 1429 1 7778 0
	* ctxt 54155
	* btime 917379184
	* processes 347 
	*
	* Linux kernel >= 2.4.0 have one or more disk_io: lines instead of
	* the disk_* lines.
	*
	* Linux kernel >= 2.6.x(?) have disk I/O stats in /proc/diskstats
	* and no disk relevant lines are found in /proc/stat
	*/
	
	char format[ 32 ];
	char tagFormat[ 16 ];
	char buf[ 1024 ];
	char tag[ 32 ];
	
	StatSM = sm;
	
	sprintf( format, "%%%d[^\n]\n", (int)sizeof( buf ) - 1 );
	sprintf( tagFormat, "%%%ds", (int)sizeof( tag ) - 1 );

    FILE *stat = fopen("/proc/stat", "r");
    if(!stat) {
		print_error( "Cannot open file \'/proc/stat\'!\n"
				"The kernel needs to be compiled with support\n"
				"for /proc file system enabled!\n" );
		return;
    }
	while ( fscanf( stat, format, buf ) == 1 ) {
		buf[ sizeof( buf ) - 1 ] = '\0';
		sscanf( buf, tagFormat, tag );
		
		if ( strcmp( "cpu", tag ) == 0 ) {
			/* Total CPU load */
			registerMonitor( "cpu/system/user", "float", printCPUUser, printCPUUserInfo, StatSM );
			registerMonitor( "cpu/system/nice", "float", printCPUNice, printCPUNiceInfo, StatSM );
			registerMonitor( "cpu/system/sys", "float", printCPUSys, printCPUSysInfo, StatSM );
			registerMonitor( "cpu/system/TotalLoad", "float", printCPUTotalLoad, printCPUTotalLoadInfo, StatSM );
			registerMonitor( "cpu/system/idle", "float", printCPUIdle, printCPUIdleInfo, StatSM );
			registerMonitor( "cpu/system/wait", "float", printCPUWait, printCPUWaitInfo, StatSM );

			/* Monitor names changed from kde3 => kde4. Remain compatible with legacy requests when possible. */
			registerLegacyMonitor( "cpu/user", "float", printCPUUser, printCPUUserInfo, StatSM );
			registerLegacyMonitor( "cpu/nice", "float", printCPUNice, printCPUNiceInfo, StatSM );
			registerLegacyMonitor( "cpu/sys", "float", printCPUSys, printCPUSysInfo, StatSM );
			registerLegacyMonitor( "cpu/TotalLoad", "float", printCPUTotalLoad, printCPUTotalLoadInfo, StatSM );
			registerLegacyMonitor( "cpu/idle", "float", printCPUIdle, printCPUIdleInfo, StatSM );
			registerLegacyMonitor( "cpu/wait", "float", printCPUWait, printCPUWaitInfo, StatSM );
		}
		else if ( strncmp( "cpu", tag, 3 ) == 0 ) {
			char cmdName[ 24 ];
			/* Load for each SMP CPU */
			int id;
			
			sscanf( tag + 3, "%d", &id );
			CPUCount++;
			sprintf( cmdName, "cpu/cpu%d/user", id );
			registerMonitor( cmdName, "float", printCPUxUser, printCPUxUserInfo, StatSM );
			sprintf( cmdName, "cpu/cpu%d/nice", id );
			registerMonitor( cmdName, "float", printCPUxNice, printCPUxNiceInfo, StatSM );
			sprintf( cmdName, "cpu/cpu%d/sys", id );
			registerMonitor( cmdName, "float", printCPUxSys, printCPUxSysInfo, StatSM );
			sprintf( cmdName, "cpu/cpu%d/TotalLoad", id );
			registerMonitor( cmdName, "float", printCPUxTotalLoad, printCPUxTotalLoadInfo, StatSM );
			sprintf( cmdName, "cpu/cpu%d/idle", id );
			registerMonitor( cmdName, "float", printCPUxIdle, printCPUxIdleInfo, StatSM );
			sprintf( cmdName, "cpu/cpu%d/wait", id );
			registerMonitor( cmdName, "float", printCPUxWait, printCPUxWaitInfo, StatSM );
		}
		else if ( strcmp( "disk", tag ) == 0 ) {
			unsigned long val;
			char* b = buf + 5;
			
			/* Count the number of registered disks */
			for ( DiskCount = 0; *b && sscanf( b, "%lu", &val ) == 1; DiskCount++ ) {
				while ( *b && isblank( *b++ ) );
				while ( *b && isdigit( *b++ ) );
			}
			
			if ( DiskCount > 0 )
				DiskLoad = (DiskLoadInfo*)malloc( sizeof( DiskLoadInfo ) * DiskCount );

			initStatDisk( tag, buf, "disk", "disk", 0, print24DiskTotal, print24DiskTotalInfo );
		}
		else if ( initStatDisk( tag, buf, "disk_rio", "rio", 1, print24DiskRIO, print24DiskRIOInfo ) );
		else if ( initStatDisk( tag, buf, "disk_wio", "wio", 2, print24DiskWIO, print24DiskWIOInfo ) );
		else if ( initStatDisk( tag, buf, "disk_rblk", "rblk", 3, print24DiskRBlk, print24DiskRBlkInfo ) );
		else if ( initStatDisk( tag, buf, "disk_wblk", "wblk", 4, print24DiskWBlk, print24DiskWBlkInfo ) );
		else if ( strcmp( "disk_io:", tag ) == 0 )
			process24DiskIO( buf );
		else if ( strcmp( "page", tag ) == 0 ) {
			sscanf( buf + 5, "%lu %lu", &OldPageIn, &OldPageOut );
			registerMonitor( "cpu/pageIn", "float", printPageIn, printPageInInfo, StatSM );
			registerMonitor( "cpu/pageOut", "float", printPageOut, printPageOutInfo, StatSM );
		}
		else if ( strcmp( "intr", tag ) == 0 ) {
			unsigned int i;
			char cmdName[ 32 ];
			char* p = buf + 5;
			
			/* Count the number of listed values in the intr line. */
			NumOfInts = 0;
			while ( *p )
				if ( *p++ == ' ' )
					NumOfInts++;
			
			/* It looks like anything above 24 is always 0. So let's just
			* ignore this for the time being. */
			if ( NumOfInts > 25 )
				NumOfInts = 25;
			OldIntr = (unsigned long*)malloc( NumOfInts * sizeof( unsigned long ) );
			Intr = (unsigned long*)malloc( NumOfInts * sizeof( unsigned long ) );
			i = 0;
			p = buf + 5;
			for ( i = 0; p && i < NumOfInts; i++ ) {
				sscanf( p, "%lu", &OldIntr[ i ] );
				while ( *p && *p != ' ' )
					p++;
				while ( *p && *p == ' ' )
					p++;
				sprintf( cmdName, "cpu/interrupts/int%02d", i );
				registerMonitor( cmdName, "float", printInterruptx, printInterruptxInfo, StatSM );
			}
		}
		else if ( strcmp( "ctxt", tag ) == 0 ) {
			sscanf( buf + 5, "%lu", &OldCtxt );
			registerMonitor( "cpu/context", "float", printCtxt, printCtxtInfo, StatSM );
		}
	}
    fclose(stat);

	stat = fopen("/proc/vmstat", "r");
    if(!stat) {
		print_error( "Cannot open file \'/proc/vmstat\'\n");
    } else {
        while ( fscanf( stat, format, buf ) == 1 ) {
            buf[ sizeof( buf ) - 1 ] = '\0';
            sscanf( buf, tagFormat, tag );

            if ( strcmp( "pgpgin", tag ) == 0 ) {
                sscanf( buf + 7, "%lu", &OldPageIn );
                registerMonitor( "cpu/pageIn", "float", printPageIn, printPageInInfo, StatSM );
            }
            else if ( strcmp( "pgpgout", tag ) == 0 ) {
                sscanf( buf + 7, "%lu", &OldPageOut );
                registerMonitor( "cpu/pageOut", "float", printPageOut, printPageOutInfo, StatSM );
            }
        }
        fclose(stat);
    }
	if ( CPUCount > 0 )
		SMPLoad = (CPULoadInfo*)calloc( CPUCount, sizeof( CPULoadInfo ) );
	
	/* Call processStat to eliminate initial peek values. */
	processStat();
}
コード例 #17
0
static int utl_isblank(int ch) {return (ch == 0xA0) || ((ch <= 0xFF) && isblank(ch));}
コード例 #18
0
ファイル: xargs.c プロジェクト: StarchLinux/coreutils
static void
parse_input(int argc, char *argv[])
{
	int hasblank = 0;
	static int hadblank = 0;
	int ch, foundeof = 0;
	char **avj;

	ch = getchar();
	if (isblank(ch)) {
		/* Quotes escape tabs and spaces. */
		if (insingle || indouble)
			goto addch;
		hasblank = 1;
		if (zflag)
			goto addch;
		goto arg2;
	}

	switch (ch) {
	case EOF:
		/* No arguments since last exec. */
		if (p == bbp) {
			if (runeof)
				prerun(0, av);
			waitchildren(*argv, 1);
			exit(rval);
		}
		goto arg1;
	case '\0':
		if (zflag)
			goto arg2;
		goto addch;
	case '\n':
		hasblank = 1;
		if (hadblank == 0)
			count++;
		if (zflag)
			goto addch;

		/* Quotes do not escape newlines. */
arg1:		if (insingle || indouble)
			errx(1, "unterminated quote");
arg2:
		foundeof = *eofstr != '\0' &&
		    strcmp(argp, eofstr) == 0;

		/* Do not make empty args unless they are quoted */
		if ((argp != p || wasquoted) && !foundeof) {
			*p++ = '\0';
			*xp++ = argp;
			if (Iflag) {
				size_t curlen;

				if (inpline == NULL)
					curlen = 0;
				else {
					/*
					 * If this string is not zero
					 * length, append a space for
					 * separation before the next
					 * argument.
					 */
					if ((curlen = strlen(inpline)))
						strlcat(inpline, " ", inpsize);
				}
				curlen++;
				/*
				 * Allocate enough to hold what we will
				 * be holding in a second, and to append
				 * a space next time through, if we have
				 * to.
				 */
				inpsize = curlen + 2 + strlen(argp);
				inpline = realloc(inpline, inpsize);
				if (inpline == NULL)
					errx(1, "realloc failed");
				if (curlen == 1)
					strlcpy(inpline, argp, inpsize);
				else
					strlcat(inpline, argp, inpsize);
			}
		}

		/*
		 * If max'd out on args or buffer, or reached EOF,
		 * run the command.  If xflag and max'd out on buffer
		 * but not on args, object.  Having reached the limit
		 * of input lines, as specified by -L is the same as
		 * maxing out on arguments.
		 */
		if (xp == endxp || p > ebp || ch == EOF ||
		    (Lflag <= count && xflag) || foundeof) {
			if (xflag && xp != endxp && p > ebp)
				errx(1, "insufficient space for arguments");
			if (jfound) {
				for (avj = argv; *avj; avj++)
					*xp++ = *avj;
			}
			prerun(argc, av);
			if (ch == EOF || foundeof) {
				waitchildren(*argv, 1);
				exit(rval);
			}
			p = bbp;
			xp = bxp;
			count = 0;
		}
		argp = p;
		wasquoted = 0;
		break;
	case '\'':
		if (indouble || zflag)
			goto addch;
		insingle = !insingle;
		wasquoted = 1;
		break;
	case '"':
		if (insingle || zflag)
			goto addch;
		indouble = !indouble;
		wasquoted = 1;
		break;
	case '\\':
		if (zflag)
			goto addch;
		/* Backslash escapes anything, is escaped by quotes. */
		if (!insingle && !indouble && (ch = getchar()) == EOF)
			errx(1, "backslash at EOF");
		/* FALLTHROUGH */
	default:
addch:		if (p < ebp) {
			*p++ = ch;
			break;
		}

		/* If only one argument, not enough buffer space. */
		if (bxp == xp)
			errx(1, "insufficient space for argument");
		/* Didn't hit argument limit, so if xflag object. */
		if (xflag)
			errx(1, "insufficient space for arguments");

		if (jfound) {
			for (avj = argv; *avj; avj++)
				*xp++ = *avj;
		}
		prerun(argc, av);
		xp = bxp;
		cnt = ebp - argp;
		memcpy(bbp, argp, (size_t)cnt);
		p = (argp = bbp) + cnt;
		*p++ = ch;
		break;
	}
	hadblank = hasblank;
}
コード例 #19
0
ファイル: ed.c プロジェクト: NikhilNJ/screenplay-dx
/*
 * Read commands until we are told to stop.
 */
static void doCommands(void)
{
	const char *cp;
	char *endbuf, *newname, buf[USERSIZE];
	int len, num1, num2;
	smallint have1, have2;

	while (TRUE) {
		/* Returns:
		 * -1 on read errors or EOF, or on bare Ctrl-D.
		 * 0  on ctrl-C,
		 * >0 length of input string, including terminating '\n'
		 */
		len = read_line_input(": ", buf, sizeof(buf), NULL);
		if (len <= 0)
			return;
		endbuf = &buf[len - 1];
		while ((endbuf > buf) && isblank(endbuf[-1]))
			endbuf--;
		*endbuf = '\0';

		cp = skip_blank(buf);
		have1 = FALSE;
		have2 = FALSE;

		if ((curNum == 0) && (lastNum > 0)) {
			curNum = 1;
			curLine = lines.next;
		}

		if (!getNum(&cp, &have1, &num1))
			continue;

		cp = skip_blank(cp);

		if (*cp == ',') {
			cp++;
			if (!getNum(&cp, &have2, &num2))
				continue;
			if (!have1)
				num1 = 1;
			if (!have2)
				num2 = lastNum;
			have1 = TRUE;
			have2 = TRUE;
		}
		if (!have1)
			num1 = curNum;
		if (!have2)
			num2 = num1;

		switch (*cp++) {
			case 'a':
				addLines(num1 + 1);
				break;

			case 'c':
				deleteLines(num1, num2);
				addLines(num1);
				break;

			case 'd':
				deleteLines(num1, num2);
				break;

			case 'f':
				if (*cp && !isblank(*cp)) {
					bb_error_msg("bad file command");
					break;
				}
				cp = skip_blank(cp);
				if (*cp == '\0') {
					if (fileName)
						printf("\"%s\"\n", fileName);
					else
						printf("No file name\n");
					break;
				}
				newname = strdup(cp);
				if (newname == NULL) {
					bb_error_msg("no memory for file name");
					break;
				}
				free(fileName);
				fileName = newname;
				break;

			case 'i':
				addLines(num1);
				break;

			case 'k':
				cp = skip_blank(cp);
				if ((*cp < 'a') || (*cp > 'z') || cp[1]) {
					bb_error_msg("bad mark name");
					break;
				}
				marks[*cp - 'a'] = num2;
				break;

			case 'l':
				printLines(num1, num2, TRUE);
				break;

			case 'p':
				printLines(num1, num2, FALSE);
				break;

			case 'q':
				cp = skip_blank(cp);
				if (have1 || *cp) {
					bb_error_msg("bad quit command");
					break;
				}
				if (!dirty)
					return;
				len = read_line_input("Really quit? ", buf, 16, NULL);
				/* read error/EOF - no way to continue */
				if (len < 0)
					return;
				cp = skip_blank(buf);
				if ((*cp | 0x20) == 'y') /* Y or y */
					return;
				break;

			case 'r':
				if (*cp && !isblank(*cp)) {
					bb_error_msg("bad read command");
					break;
				}
				cp = skip_blank(cp);
				if (*cp == '\0') {
					bb_error_msg("no file name");
					break;
				}
				if (!have1)
					num1 = lastNum;
				if (readLines(cp, num1 + 1))
					break;
				if (fileName == NULL)
					fileName = strdup(cp);
				break;

			case 's':
				subCommand(cp, num1, num2);
				break;

			case 'w':
				if (*cp && !isblank(*cp)) {
					bb_error_msg("bad write command");
					break;
				}
				cp = skip_blank(cp);
				if (!have1) {
					num1 = 1;
					num2 = lastNum;
				}
				if (*cp == '\0')
					cp = fileName;
				if (cp == NULL) {
					bb_error_msg("no file name specified");
					break;
				}
				writeLines(cp, num1, num2);
				break;

			case 'z':
				switch (*cp) {
				case '-':
					printLines(curNum - 21, curNum, FALSE);
					break;
				case '.':
					printLines(curNum - 11, curNum + 10, FALSE);
					break;
				default:
					printLines(curNum, curNum + 21, FALSE);
					break;
				}
				break;

			case '.':
				if (have1) {
					bb_error_msg("no arguments allowed");
					break;
				}
				printLines(curNum, curNum, FALSE);
				break;

			case '-':
				if (setCurNum(curNum - 1))
					printLines(curNum, curNum, FALSE);
				break;

			case '=':
				printf("%d\n", num1);
				break;
			case '\0':
				if (have1) {
					printLines(num2, num2, FALSE);
					break;
				}
				if (setCurNum(curNum + 1))
					printLines(curNum, curNum, FALSE);
				break;

			default:
				bb_error_msg("unimplemented command");
				break;
		}
	}
}
コード例 #20
0
ファイル: number.c プロジェクト: coyizumi/cs111
static void
convert(char *line)
{
	int flen, len, rval;
	char *p, *fraction;

	flen = 0;
	fraction = NULL;
	for (p = line; *p != '\0' && *p != '\n'; ++p) {
		if (isblank(*p)) {
			if (p == line) {
				++line;
				continue;
			}
			goto badnum;
		}
		if (isdigit(*p))
			continue;
		switch (*p) {
		case '.':
			if (fraction != NULL)
				goto badnum;
			fraction = p + 1;
			*p = '\0';
			break;
		case '-':
			if (p == line)
				break;
			/* FALLTHROUGH */
		default:
badnum:			errx(1, "illegal number: %s", line);
			break;
		}
	}
	*p = '\0';

	if ((len = strlen(line)) > MAXNUM ||
	    (fraction != NULL && ((flen = strlen(fraction)) > MAXNUM)))
		errx(1, "number too large, max %d digits.", MAXNUM);

	if (*line == '-') {
		(void)printf("minus%s", lflag ? " " : "\n");
		++line;
		--len;
	}

	rval = len > 0 ? unit(len, line) : 0;
	if (fraction != NULL && flen != 0)
		for (p = fraction; *p != '\0'; ++p)
			if (*p != '0') {
				if (rval)
					(void)printf("%sand%s",
					    lflag ? " " : "",
					    lflag ? " " : "\n");
				if (unit(flen, fraction)) {
					if (lflag)
						(void)printf(" ");
					pfract(flen);
					rval = 1;
				}
				break;
			}
	if (!rval)
		(void)printf("zero%s", lflag ? "" : ".\n");
	if (lflag)
		(void)printf("\n");
}
コード例 #21
0
ファイル: ed.c プロジェクト: NikhilNJ/screenplay-dx
static char *skip_blank(const char *cp)
{
	while (isblank(*cp))
		cp++;
	return (char *)cp;
}
コード例 #22
0
ファイル: check_isw.c プロジェクト: Basskrapfen/openbsd
void
test2()
{
	unsigned char *s;
	unsigned char *buf;
	int i, j;
	size_t n;
	wchar_t c, d;
	mbstate_t state;

	s = malloc(256);
	if (!s) {
		bad++;
		return;
	}
	buf = malloc(MB_CUR_MAX);
	if (!buf) {
		bad++;
		free(s);
		return;
	}
	for (i = 0; i < 256; i++)
		s[i] = i+1;

	j = 0;
	mbrtowc(NULL, NULL, 1, &state);
	printf(" %02x: ", 0);

	while ((n = mbrtowc(&c, s+j, 256-j, &state)) == 1) {
		printf(" %02x: ", s[j]);
		check_bool(isalnum(s[j]), iswalnum(c), '1');
		check_bool(isalpha(s[j]), iswalpha(c), '2');
		check_bool(isblank(s[j]), iswblank(c), '3');
		check_bool(iscntrl(s[j]), iswcntrl(c), '4');
		check_bool(isdigit(s[j]), iswdigit(c), '5');
		check_bool(isgraph(s[j]), iswgraph(c), '6');
		check_bool(islower(s[j]), iswlower(c), '6');
		check_bool(isprint(s[j]), iswprint(c), '7');
		check_bool(ispunct(s[j]), iswpunct(c), '8');
		check_bool(isspace(s[j]), iswspace(c), '9');
		check_bool(isupper(s[j]), iswupper(c), 'a');
		check_bool(isxdigit(s[j]), iswxdigit(c), 'b');
		d = towlower(c);
		if (wctomb(buf, d) == 1) {	
			check_value(tolower(s[j]), buf[0], 'c');
		} else {
			bad++;
		}
		d = towupper(c);
		if (wctomb(buf, d) == 1) {	
			check_value(toupper(s[j]), buf[0], 'c');
		} else {
			bad++;
		}
		if (s[j] % 8 == 7)
			printf("\n");
		j++;
	}
	if (n != 0 || j != 255) {
		bad++;
	}
	free(s);
	free(buf);
}
コード例 #23
0
struct wowlan_triggers *
wpa_get_wowlan_triggers(const char *wowlan_triggers,
			const struct wpa_driver_capa *capa)
{
	struct wowlan_triggers *triggers;
	char *start, *end, *buf;
	int last;

	if (!wowlan_triggers)
		return NULL;

	buf = os_strdup(wowlan_triggers);
	if (buf == NULL)
		return NULL;

	triggers = os_zalloc(sizeof(*triggers));
	if (triggers == NULL)
		goto out;

#define CHECK_TRIGGER(trigger) \
	wpa_check_wowlan_trigger(start, #trigger,			\
				  capa->wowlan_triggers.trigger,	\
				  &triggers->trigger)

	start = buf;
	while (*start != '\0') {
		while (isblank((unsigned char) *start))
			start++;
		if (*start == '\0')
			break;
		end = start;
		while (!isblank((unsigned char) *end) && *end != '\0')
			end++;
		last = *end == '\0';
		*end = '\0';

		if (!CHECK_TRIGGER(any) &&
		    !CHECK_TRIGGER(disconnect) &&
		    !CHECK_TRIGGER(magic_pkt) &&
		    !CHECK_TRIGGER(gtk_rekey_failure) &&
		    !CHECK_TRIGGER(eap_identity_req) &&
		    !CHECK_TRIGGER(four_way_handshake) &&
		    !CHECK_TRIGGER(rfkill_release)) {
			wpa_printf(MSG_DEBUG,
				   "Unknown/unsupported wowlan trigger '%s'",
				   start);
			os_free(triggers);
			triggers = NULL;
			goto out;
		}

		if (last)
			break;
		start = end + 1;
	}
#undef CHECK_TRIGGER

out:
	os_free(buf);
	return triggers;
}
コード例 #24
0
ファイル: dao_CharType.c プロジェクト: daokoder/dao
static void dao_isblank( DaoProcess *proc, DaoValue *P[], int N )
{
	DaoProcess_PutInteger( proc, isblank( DaoValue_TryGetInteger( P[0] ) ) );
}
コード例 #25
0
// Checks for a blank character, that is, a space or a tab.
inline bool isWhitespace(int c)
{
  return ( isblank (c) == 0 ? false : true);
}
コード例 #26
0
ファイル: libtcmu_config.c プロジェクト: Fubo1/tcmu-runner
static void tcmu_parse_option(char **cur, const char *end)
{
	struct tcmu_conf_option *option;
	tcmu_option_type type;
	char *p = *cur, *q = *cur, *r, *s;

	while (isblank(*p))
		p++;

	TCMU_TO_LINE_END(q, end);
	*q = '\0';
	*cur = q + 1;

	/* parse the boolean type option */
	s = r = strchr(p, '=');
	if (!r) {
		/* boolean type option at file end or line end */
		r = p;
		while (!isblank(*r) && r < q)
			r++;
		*r = '\0';
		option = tcmu_get_option(p);
		if (!option)
			option = tcmu_register_option(p, TCMU_OPT_BOOL);

		if (option)
			option->opt_bool = true;

		return;
	}

	while (isblank(*r) || *r == '=')
		r--;
	r++;
	*r = '\0';

	option = tcmu_get_option(p);
	if (!option) {
		r = s;
		while (isblank(*r) || *r == '=')
			r++;

		if (*r == '"' || *r == '\'') {
			type = TCMU_OPT_STR;
		} else if (isdigit(*r)) {
			type = TCMU_OPT_INT;
		} else {
			tcmu_err("option type %d not supported!\n");
			return;
		}

		option = tcmu_register_option(p, type);
		if (!option)
			return;
	}

	/* parse the int/string type options */
	switch (option->type) {
	case TCMU_OPT_INT:
		while (!isdigit(*s))
			s++;
		r = s;
		while (isdigit(*r))
			r++;
		*r= '\0';

		option->opt_int = atoi(s);
		break;
	case TCMU_OPT_STR:
		s++;
		while (isblank(*s))
			s++;
		/* skip first " or ' if exist */
		if (*s == '"' || *s == '\'')
			s++;
		r = q - 1;
		while (isblank(*r))
			r--;
		/* skip last " or ' if exist */
		if (*r == '"' || *r == '\'')
			*r = '\0';

		option->opt_str = strdup(s);
		break;
	default:
		tcmu_err("option type %d not supported!\n");
		break;
	}
}
コード例 #27
0
ファイル: configuration.c プロジェクト: kissthink/slapt-get
slapt_source_t *slapt_init_source(const char *s)
{
  slapt_source_t *src;
  unsigned int source_len = 0;
  unsigned int attribute_len = 0;
  slapt_regex_t *attribute_regex = NULL;
  char *source_string = NULL;
  char *attribute_string = NULL;

  if (s == NULL)
    return NULL;

  src           = slapt_malloc(sizeof *src);
  src->priority = SLAPT_PRIORITY_DEFAULT;
  src->disabled = SLAPT_FALSE;
  source_string = slapt_strip_whitespace (s);
  source_len    = strlen (source_string);

  /* parse for :[attr] in the source url */
  if ((attribute_regex = slapt_init_regex(SLAPT_SOURCE_ATTRIBUTE_REGEX)) == NULL) {
    exit(EXIT_FAILURE);
  }
  slapt_execute_regex(attribute_regex,source_string);
  if (attribute_regex->reg_return == 0) {
    /* if we find an attribute string, extract it */
    attribute_string = slapt_regex_extract_match(attribute_regex, source_string, 1);
    attribute_len = strlen(attribute_string);
    source_len -= attribute_len;
  }
  slapt_free_regex(attribute_regex);


  /* now add a trailing / if not already there */
  if ( source_string[source_len - 1] == '/' ) {
    src->url = strndup(source_string, source_len);
  } else {
    src->url = slapt_malloc(sizeof *src->url * (source_len + 2));
    src->url[0] = '\0';

    src->url = strncat(
      src->url,
      source_string,
      source_len
    );

    if (isblank(src->url[source_len - 1]) == 0) {
      src->url = strncat(src->url, "/", 1);
    } else {
      if (src->url[source_len - 2] == '/') {
        src->url[source_len - 2] = '/';
        src->url[source_len - 1] = '\0';
      } else {
        src->url[source_len - 1] = '/';
      }
    }

    src->url[source_len + 1] = '\0';
  }

  free(source_string);

  /* now parse the attribute string */
  if (attribute_string != NULL) {
    slapt_source_parse_attributes(src, attribute_string + 1);
    free(attribute_string);
  }

  return src;
}
コード例 #28
0
ファイル: metrics.c プロジェクト: BDA-CODE/monitor-core
void update_ifdata ( char *caller )
{
   char *p;
   int i;
   static struct timeval stamp={0,0};
   stat_t rbi=0, rbo=0, rpi=0, rpo=0;
   stat_t l_bytes_in=0, l_bytes_out=0, l_pkts_in=0, l_pkts_out=0;
   double l_bin, l_bout, l_pin, l_pout;
   net_dev_stats *ns;
   float t;

   p = update_file(&proc_net_dev);
   if ((proc_net_dev.last_read.tv_sec != stamp.tv_sec) &&
       (proc_net_dev.last_read.tv_usec != stamp.tv_usec))
      {
        /*  skip past the two-line header ... */
        p = index (p, '\n') + 1;
        p = index (p, '\n') + 1;

        while (*p != 0x00)
           {
              /*  skip past the interface tag portion of this line */
              /*  but save the name of the interface (hash key) */
              char *src;
              size_t n = 0;

              char if_name[IFNAMSIZ];
              int vlan = 0; // vlan flag

              while (p != 0x00 && isblank(*p))
                 p++;

              src = p;
              while (p != 0x00 && *p != ':')
                 {
                    n++;
                    p++;
                 }

              p = index(p, ':');
              /* l.flis: check whether iface is vlan */
              if (p && n < IFNAMSIZ) {
                  strncpy(if_name,src,IFNAMSIZ);
                  if_name[n] = '\0';
                  vlan = is_vlan_iface(if_name);
              };
                 
              /* Ignore 'lo' and 'bond*' interfaces (but sanely) */
              /* l.flis: skip vlan interfaces to avoid double counting*/
              if (p && strncmp (src, "lo", 2) &&
                  strncmp (src, "bond", 4) && !vlan)
                 {
                    p++;
                    /* Check for data from the last read for this */
                    /* interface.  If nothing exists, add to the table. */
                    ns = hash_lookup(src, n);
                    if ( !ns ) return;

                    /* receive */
                    rbi = strtostat(p, &p ,10);
                    if ( rbi >= ns->rbi ) {
                       l_bytes_in += rbi - ns->rbi;
                    } else {
                       debug_msg("update_ifdata(%s) - Overflow in rbi: %"PRI_STAT" -> %"PRI_STAT,caller,ns->rbi,rbi);
                       l_bytes_in += STAT_MAX - ns->rbi + rbi;
                    }
                    ns->rbi = rbi;

                    rpi = strtostat(p, &p ,10);
                    if ( rpi >= ns->rpi ) {
                       l_pkts_in += rpi - ns->rpi;
                    } else {
                       debug_msg("updata_ifdata(%s) - Overflow in rpi: %"PRI_STAT" -> %"PRI_STAT,caller,ns->rpi,rpi);
                       l_pkts_in += STAT_MAX - ns->rpi + rpi;
                    }
                    ns->rpi = rpi;

                    /* skip unneeded metrics */
                    for (i = 0; i < 6; i++) rbo = strtostat(p, &p, 10);

                    /* transmit */
                    rbo = strtostat(p, &p ,10);
                    if ( rbo >= ns->rbo ) {
                       l_bytes_out += rbo - ns->rbo;
                    } else {
                       debug_msg("update_ifdata(%s) - Overflow in rbo: %"PRI_STAT" -> %"PRI_STAT,caller,ns->rbo,rbo);
                       l_bytes_out += STAT_MAX - ns->rbo + rbo;
                    }
                    ns->rbo = rbo;

                    rpo = strtostat(p, &p ,10);
                    if ( rpo >= ns->rpo ) {
                       l_pkts_out += rpo - ns->rpo;
                    } else {
                       debug_msg("update_ifdata(%s) - Overflow in rpo: %"PRI_STAT" -> %"PRI_STAT,caller,ns->rpo,rpo);
                       l_pkts_out += STAT_MAX - ns->rpo + rpo;
                    }
                    ns->rpo = rpo;
                  }
              p = index (p, '\n') + 1;
            }

        /*
         * Compute timediff. Check for bogus delta-t
         */
        t = timediff(&proc_net_dev.last_read, &stamp);
        if ( t <  proc_net_dev.thresh) {
           err_msg("update_ifdata(%s) - Dubious delta-t: %f", caller, t);
           return;
        }
        stamp = proc_net_dev.last_read;

        /*
         * Compute rates in local variables
         */
        l_bin = l_bytes_in / t;
        l_bout = l_bytes_out / t;
        l_pin = l_pkts_in / t;
        l_pout = l_pkts_out / t;

#ifdef REMOVE_BOGUS_SPIKES
        /*
         * Check for "invalid" data, caused by HW error. Throw away dubious data points
         * FIXME: This should be done per-interface, with threshholds depending on actual link speed
         */
        if ((l_bin > 1.0e13) || (l_bout > 1.0e13) ||
            (l_pin > 1.0e8)  || (l_pout > 1.0e8)) {
           err_msg("update_ifdata(%s): %g %g %g %g / %g", caller,
                   l_bin, l_bout, l_pin, l_pout, t);
           return;
        }
#endif

        /*
         * Finally return Values
         */
        bytes_in  = l_bin;
        bytes_out = l_bout;
        pkts_in   = l_pin;
        pkts_out  = l_pout;
      }

   return;
}
コード例 #29
0
ファイル: argp-fmtstream.c プロジェクト: Boshin/workspace
/* Process FS's buffer so that line wrapping is done from POINT_OFFS to the
   end of its buffer.  This code is mostly from glibc stdio/linewrap.c.  */
void
__argp_fmtstream_update (argp_fmtstream_t fs)
{
  char *buf, *nl;
  size_t len;

  /* Scan the buffer for newlines.  */
  buf = fs->buf + fs->point_offs;
  while (buf < fs->p)
    {
      size_t r;

      if (fs->point_col == 0 && fs->lmargin != 0)
	{
	  /* We are starting a new line.  Print spaces to the left margin.  */
	  const size_t pad = fs->lmargin;
	  if (fs->p + pad < fs->end)
	    {
	      /* We can fit in them in the buffer by moving the
		 buffer text up and filling in the beginning.  */
	      memmove (buf + pad, buf, fs->p - buf);
	      fs->p += pad; /* Compensate for bigger buffer. */
	      memset (buf, ' ', pad); /* Fill in the spaces.  */
	      buf += pad; /* Don't bother searching them.  */
	    }
	  else
	    {
	      /* No buffer space for spaces.  Must flush.  */
	      size_t i;
	      for (i = 0; i < pad; i++)
		{
		  if (_IO_fwide (fs->stream, 0) > 0)
		    putwc_unlocked (L' ', fs->stream);
		  else
		    putc_unlocked (' ', fs->stream);
		}
	    }
	  fs->point_col = pad;
	}

      len = fs->p - buf;
      nl = memchr (buf, '\n', len);

      if (fs->point_col < 0)
	fs->point_col = 0;

      if (!nl)
	{
	  /* The buffer ends in a partial line.  */

	  if (fs->point_col + len < fs->rmargin)
	    {
	      /* The remaining buffer text is a partial line and fits
		 within the maximum line width.  Advance point for the
		 characters to be written and stop scanning.  */
	      fs->point_col += len;
	      break;
	    }
	  else
	    /* Set the end-of-line pointer for the code below to
	       the end of the buffer.  */
	    nl = fs->p;
	}
      else if (fs->point_col + (nl - buf) < (ssize_t) fs->rmargin)
	{
	  /* The buffer contains a full line that fits within the maximum
	     line width.  Reset point and scan the next line.  */
	  fs->point_col = 0;
	  buf = nl + 1;
	  continue;
	}

      /* This line is too long.  */
      r = fs->rmargin - 1;

      if (fs->wmargin < 0)
	{
	  /* Truncate the line by overwriting the excess with the
	     newline and anything after it in the buffer.  */
	  if (nl < fs->p)
	    {
	      memmove (buf + (r - fs->point_col), nl, fs->p - nl);
	      fs->p -= buf + (r - fs->point_col) - nl;
	      /* Reset point for the next line and start scanning it.  */
	      fs->point_col = 0;
	      buf += r + 1; /* Skip full line plus \n. */
	    }
	  else
	    {
	      /* The buffer ends with a partial line that is beyond the
		 maximum line width.  Advance point for the characters
		 written, and discard those past the max from the buffer.  */
	      fs->point_col += len;
	      fs->p -= fs->point_col - r;
	      break;
	    }
	}
      else
	{
	  /* Do word wrap.  Go to the column just past the maximum line
	     width and scan back for the beginning of the word there.
	     Then insert a line break.  */

	  char *p, *nextline;
	  int i;

	  p = buf + (r + 1 - fs->point_col);
	  while (p >= buf && !isblank (*p))
	    --p;
	  nextline = p + 1;	/* This will begin the next line.  */

	  if (nextline > buf)
	    {
	      /* Swallow separating blanks.  */
	      if (p >= buf)
		do
		  --p;
		while (p >= buf && isblank (*p));
	      nl = p + 1;	/* The newline will replace the first blank. */
	    }
	  else
	    {
	      /* A single word that is greater than the maximum line width.
		 Oh well.  Put it on an overlong line by itself.  */
	      p = buf + (r + 1 - fs->point_col);
	      /* Find the end of the long word.  */
	      do
		++p;
	      while (p < nl && !isblank (*p));
	      if (p == nl)
		{
		  /* It already ends a line.  No fussing required.  */
		  fs->point_col = 0;
		  buf = nl + 1;
		  continue;
		}
	      /* We will move the newline to replace the first blank.  */
	      nl = p;
	      /* Swallow separating blanks.  */
	      do
		++p;
	      while (isblank (*p));
	      /* The next line will start here.  */
	      nextline = p;
	    }

	  /* Note: There are a bunch of tests below for
	     NEXTLINE == BUF + LEN + 1; this case is where NL happens to fall
	     at the end of the buffer, and NEXTLINE is in fact empty (and so
	     we need not be careful to maintain its contents).  */

	  if ((nextline == buf + len + 1
	       ? fs->end - nl < fs->wmargin + 1
	       : nextline - (nl + 1) < fs->wmargin)
	      && fs->p > nextline)
	    {
	      /* The margin needs more blanks than we removed.  */
	      if (fs->end - fs->p > fs->wmargin + 1)
		/* Make some space for them.  */
		{
		  size_t mv = fs->p - nextline;
		  memmove (nl + 1 + fs->wmargin, nextline, mv);
		  nextline = nl + 1 + fs->wmargin;
		  len = nextline + mv - buf;
		  *nl++ = '\n';
		}
	      else
		/* Output the first line so we can use the space.  */
		{
#ifdef _LIBC
		  __fxprintf (fs->stream, "%.*s\n",
			      (int) (nl - fs->buf), fs->buf);
#else
		  if (nl > fs->buf)
		    fwrite_unlocked (fs->buf, 1, nl - fs->buf, fs->stream);
		  putc_unlocked ('\n', fs->stream);
#endif

		  len += buf - fs->buf;
		  nl = buf = fs->buf;
		}
	    }
	  else
	    /* We can fit the newline and blanks in before
	       the next word.  */
	    *nl++ = '\n';

	  if (nextline - nl >= fs->wmargin
	      || (nextline == buf + len + 1 && fs->end - nextline >= fs->wmargin))
	    /* Add blanks up to the wrap margin column.  */
	    for (i = 0; i < fs->wmargin; ++i)
	      *nl++ = ' ';
	  else
	    for (i = 0; i < fs->wmargin; ++i)
	      if (_IO_fwide (fs->stream, 0) > 0)
		putwc_unlocked (L' ', fs->stream);
	      else
		putc_unlocked (' ', fs->stream);

	  /* Copy the tail of the original buffer into the current buffer
	     position.  */
	  if (nl < nextline)
	    memmove (nl, nextline, buf + len - nextline);
	  len -= nextline - buf;

	  /* Continue the scan on the remaining lines in the buffer.  */
	  buf = nl;

	  /* Restore bufp to include all the remaining text.  */
	  fs->p = nl + len;

	  /* Reset the counter of what has been output this line.  If wmargin
	     is 0, we want to avoid the lmargin getting added, so we set
	     point_col to a magic value of -1 in that case.  */
	  fs->point_col = fs->wmargin ? fs->wmargin : -1;
	}
    }

  /* Remember that we've scanned as far as the end of the buffer.  */
  fs->point_offs = fs->p - fs->buf;
}
コード例 #30
0
ファイル: conf.c プロジェクト: andreyhammer/nodogsplash
/**
@param filename Full path of the configuration file to be read
*/
void
config_read(const char *filename)
{
	FILE *fd;
	char line[MAX_BUF], *s, *p1, *p2;
	int linenum = 0, opcode, value;

	debug(LOG_INFO, "Reading configuration file '%s'", filename);

	if (!(fd = fopen(filename, "r"))) {
		debug(LOG_ERR, "FATAL: Could not open configuration file '%s', "
			  "exiting...", filename);
		exit(1);
	}

	while (fgets(line, MAX_BUF, fd)) {
		linenum++;
		s = _strip_whitespace(line);

		/* if nothing left, get next line */
		if(s[0] == '\0') continue;

		/* now we require the line must have form: <option><whitespace><arg>
		 * even if <arg> is just a left brace, for example
		 */

		/* find first word (i.e. option) end boundary */
		p1 = s;
		while ((*p1 != '\0') && (!isspace(*p1))) p1++;
		/* if this is end of line, it's a problem */
		if(p1[0] == '\0') {
			debug(LOG_ERR, "Option %s requires argument on line %d in %s", s, linenum, filename);
			debug(LOG_ERR, "Exiting...");
			exit(-1);
		}

		/* terminate option, point past it */
		*p1 = '\0';
		p1++;

		/* skip any additional leading whitespace, make p1 point at start of arg */
		while (isblank(*p1)) p1++;

		debug(LOG_DEBUG, "Parsing option: %s, arg: %s", s, p1);
		opcode = config_parse_opcode(s, filename, linenum);

		switch(opcode) {
		case oDaemon:
			if (config.daemon == -1 && ((value = parse_boolean_value(p1)) != -1)) {
				config.daemon = value;
			}
			break;
		case oDebugLevel:
			if(sscanf(p1, "%d", &config.debuglevel) < 1 || config.debuglevel < LOG_EMERG || config.debuglevel > LOG_DEBUG) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s. Valid debuglevel %d..%d", p1, s, linenum, filename, LOG_EMERG, LOG_DEBUG);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oMaxClients:
			if(sscanf(p1, "%d", &config.maxclients) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oGatewayName:
			config.gw_name = safe_strdup(p1);
			break;
		case oGatewayInterface:
			config.gw_interface = safe_strdup(p1);
			break;
		case oGatewayIPRange:
			config.gw_iprange = safe_strdup(p1);
			break;
		case oGatewayAddress:
			config.gw_address = safe_strdup(p1);
			break;
		case oGatewayPort:
			if(sscanf(p1, "%u", &config.gw_port) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oRemoteAuthenticatorAction:
			config.remote_auth_action = safe_strdup(p1);
			break;
		case oEnablePreAuth:
			value = parse_boolean_value(p1);
			if (value != - 1)
				config.enable_preauth = value;
			break;
		case oBinVoucher:
			config.bin_voucher = safe_strdup(p1);
			break;
		case oForceVoucher:
			value = parse_boolean_value(p1);
			if (value != - 1)
				config.force_voucher = value;
			break;
		case oFirewallRuleSet:
			parse_firewall_ruleset(p1, fd, filename, &linenum);
			break;
		case oEmptyRuleSetPolicy:
			parse_empty_ruleset_policy(p1, filename, linenum);
			break;
		case oTrustedMACList:
			parse_trusted_mac_list(p1);
			break;
		case oBlockedMACList:
			parse_blocked_mac_list(p1);
			break;
		case oAllowedMACList:
			parse_allowed_mac_list(p1);
			break;
		case oMACmechanism:
			if(!strcasecmp("allow",p1)) config.macmechanism = MAC_ALLOW;
			else if(!strcasecmp("block",p1)) config.macmechanism = MAC_BLOCK;
			else {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oWebRoot:
			/* remove any trailing slashes from webroot path */
			while((p2 = strrchr(p1,'/')) == (p1 + strlen(p1) - 1)) *p2 = '\0';
			config.webroot = safe_strdup(p1);
			break;
		case oSplashPage:
			config.splashpage = safe_strdup(p1);
			break;
		case oImagesDir:
			config.imagesdir = safe_strdup(p1);
			break;
		case oPagesDir:
			config.pagesdir = safe_strdup(p1);
			break;
		case oRedirectURL:
			config.redirectURL = safe_strdup(p1);
			break;
		case oNdsctlSocket:
			free(config.ndsctl_sock);
			config.ndsctl_sock = safe_strdup(p1);
			break;
		case oDecongestHttpdThreads:
			if ((value = parse_boolean_value(p1)) != -1) {
				config.decongest_httpd_threads = value;
			} else {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oHttpdThreadThreshold:
			if(sscanf(p1, "%d", &config.httpd_thread_threshold) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oHttpdThreadDelayMS:
			if(sscanf(p1, "%d", &config.httpd_thread_delay_ms) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oClientIdleTimeout:
			if(sscanf(p1, "%d", &config.clienttimeout) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oClientForceTimeout:
			if(sscanf(p1, "%d", &config.clientforceout) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oAuthenticateImmediately:
			if ((value = parse_boolean_value(p1)) != -1) {
				config.authenticate_immediately = value;
			} else {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oPasswordAuthentication:
			if ((value = parse_boolean_value(p1)) != -1) {
				config.passwordauth = value;
			} else {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oUsernameAuthentication:
			if ((value = parse_boolean_value(p1)) != -1) {
				config.usernameauth = value;
			} else {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oPasswordAttempts:
			if(sscanf(p1, "%d", &config.passwordattempts) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oUsername:
			set_username(p1);
			break;
		case oPassword:
			set_password(p1);
			break;
		case oSetMSS:
			if ((value = parse_boolean_value(p1)) != -1) {
				config.set_mss = value;
			} else {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oMSSValue:
			if(sscanf(p1, "%d", &config.mss_value) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oTrafficControl:
			if ((value = parse_boolean_value(p1)) != -1) {
				config.traffic_control = value;
			} else {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oDownloadLimit:
			if(sscanf(p1, "%d", &config.download_limit) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oUploadLimit:
			if(sscanf(p1, "%d", &config.upload_limit) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oDownloadIMQ:
			if(sscanf(p1, "%d", &config.download_imq) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oUploadIMQ:
			if(sscanf(p1, "%d", &config.upload_imq) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oFWMarkAuthenticated:
			if(sscanf(p1, "%x", &config.FW_MARK_AUTHENTICATED) < 1 ||
					config.FW_MARK_AUTHENTICATED == 0 ||
					config.FW_MARK_AUTHENTICATED == config.FW_MARK_BLOCKED ||
					config.FW_MARK_AUTHENTICATED == config.FW_MARK_TRUSTED) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oFWMarkBlocked:
			if(sscanf(p1, "%x", &config.FW_MARK_BLOCKED) < 1 ||
					config.FW_MARK_BLOCKED == 0 ||
					config.FW_MARK_BLOCKED == config.FW_MARK_AUTHENTICATED ||
					config.FW_MARK_BLOCKED == config.FW_MARK_TRUSTED) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oFWMarkTrusted:
			if(sscanf(p1, "%x", &config.FW_MARK_TRUSTED) < 1 ||
					config.FW_MARK_TRUSTED == 0 ||
					config.FW_MARK_TRUSTED == config.FW_MARK_AUTHENTICATED ||
					config.FW_MARK_TRUSTED == config.FW_MARK_BLOCKED) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;

		case oSyslogFacility:
			if(sscanf(p1, "%d", &config.syslog_facility) < 1) {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;
		case oBadOption:
			debug(LOG_ERR, "Bad option %s on line %d in %s", s, linenum, filename);
			debug(LOG_ERR, "Exiting...");
			exit(-1);
			break;
		case oPrivoxyMode:
			if ((value = parse_boolean_value(p1)) != -1) {
				config.privoxy_mode = value;
			} else {
				debug(LOG_ERR, "Bad arg %s to option %s on line %d in %s", p1, s, linenum, filename);
				debug(LOG_ERR, "Exiting...");
				exit(-1);
			}
			break;

		}

	}

	fclose(fd);

	debug(LOG_INFO, "Done reading configuration file '%s'", filename);
}