static EContact *
getNextCSVEntry (CSVImporter *gci,
                 FILE *f)
{
	EContact *contact = NULL;
	GString  *line;
	GString *str;
	gchar *buf;
	gint c;

	line = g_string_new ("");
	while (1) {
		c = fgetc (f);
		if (c == EOF)
			return NULL;
		if (c == '\n') {
			g_string_append_c (line, c);
			break;
		}
		if (c == '"') {
			g_string_append_c (line, c);
			c = fgetc (f);
			while (!feof (f) && c != '"') {
				g_string_append_c (line, c);
				c = fgetc (f);
			}
			g_string_append_c (line, c);
		}
		else
			g_string_append_c (line, c);
	}

	if (gci->count == 0 && importer != MOZILLA_IMPORTER) {
		gci->fields_map = map_fields (line->str, importer);
		g_string_free (line, TRUE);
		line = g_string_new ("");
		while (1) {
			c = fgetc (f);
			if (c == EOF)
				return NULL;
			if (c == '\n') {
				g_string_append_c (line, c);
				break;
			}
			if (c == '"') {
				g_string_append_c (line, c);
				c = fgetc (f);
				while (!feof (f) && c != '"') {
					g_string_append_c (line, c);
					c = fgetc (f);
				}
				g_string_append_c (line, c);
			}
			else
				g_string_append_c (line, c);
		}
		gci->count++;
	}

	str = g_string_new ("");
	str = g_string_append (str, line->str);

	g_string_free (line, TRUE);

	if (strlen (str->str) == 0) {
		g_string_free (str, TRUE);
		return NULL;
	}

	contact = e_contact_new ();

	buf = str->str;

	if (!parseLine (gci, contact, buf)) {
		g_object_unref (contact);
		return NULL;
	}
	gci->count++;

	g_string_free (str, TRUE);

	return contact;
}
Example #2
0
bool DhQHttpHeader::DvhparseLine(const QString& x1, int x2) {
  return parseLine(x1, x2);
}
Example #3
0
/**
   @param fileName the file to open

   @param continueOnErrors whether to continue or immediately bail upon an error

   @param noFileNotFoundMessage whether or not to log if we find a
   file (we normally want to but for robot param files that'd be too
   annoying since we test for a lot of files)

   @param errorBuffer buffer to put errors into if not NULL. Only the
   first error is saved, and as soon as this function is called it
   immediately empties the errorBuffer

   @param errorBufferLen the length of @a errorBuffer
*/
AREXPORT bool ArFileParser::parseFile(const char *fileName,
				      bool continueOnErrors,
				      bool noFileNotFoundMessage,
				      char *errorBuffer,
				      size_t errorBufferLen)
{
  FILE *file;

  char line[10000];
  bool ret = true;

  if (errorBuffer)
    errorBuffer[0] = '\0';

  std::string realFileName;
  if (fileName[0] == '/' || fileName[0] == '\\')
  {
    realFileName = fileName;
  }
  else
  {
    realFileName = myBaseDir;
    realFileName += fileName;
  }

  ArLog::log(ArLog::Verbose, "Opening file %s from fileName given %s and base directory %s", realFileName.c_str(), fileName, myBaseDir.c_str());

  //char *buf = new char[4096];

  if ((file = fopen(realFileName.c_str(), "r")) == NULL)
  {
    if (errorBuffer != NULL)
      snprintf(errorBuffer, errorBufferLen, "cannot open file %s", fileName);
    if (!noFileNotFoundMessage)
      ArLog::log(ArLog::Terse, "ArFileParser::parseFile: Could not open file %s to parse file.", realFileName.c_str());
    return false;
  }
/**
   if( setvbuf( file, buf, _IOFBF, sizeof( buf ) ) != 0 )
         printf( "Incorrect type or size of buffer for file\n" );
     //else
     //    printf( "'file' now has a buffer of 1024 bytes\n" );
**/

  resetCounters();
  // read until the end of the file
  while (fgets(line, sizeof(line), file) != NULL)
  {
    if (!parseLine(line, errorBuffer, errorBufferLen))
    {
      ArLog::log(ArLog::Terse, "## Last error on line %d of file '%s'",
		 myLineNumber, realFileName.c_str());
      ret = false;
      if (!continueOnErrors)
	break;
    }
  }

  fclose(file);
  return ret;
}
Example #4
0
static int
compileConfig (FileInfo * nested)
{
  static const char *mainActions[] = {
    "outputFormat",
    "0",
    "style",
    "1",
    "translation",
    "2",
    "xml",
    "3",
    "include",
    "5",
    NULL
  };
  static const char *yesNo[] = {
    "no",
    "0",
    "yes",
    "1",
    NULL
  };
  int k;
  if (!parseLine (nested))
    return 1;			/*No configuration, run with defaults */
  mainActionNumber = checkActions (nested, mainActions);
  if (mainActionNumber == NOTFOUND)
    {
      configureError (nested,
		      "word %s in first column not recognized",
		      nested->action);
      return 0;
    }
choseMainAction:
  switch (mainActionNumber)
    {
    case 0:			/*outputFormat */
      {
	static const char *actions[] = {
	  "cellsPerLine",
	  "0",
	  "linesPerPage",
	  "1",
	  "interpoint",
	  "2",
	  "lineEnd",
	  "3",
	  "pageEnd",
	  "4",
	  "beginningPageNumber",
	  "5",
	  "braillePages",
	  "6",
	  "paragraphs",
	  "7",
	  "fileEnd",
	  "8",
	  "printPages",
	  "9",
	  "printPageNumberAt",
	  "10",
	  "braillePageNumberAt",
	  "11",
	  "hyphenate",
	  "12",
	  "encoding",
	  "13",
	  "backFormat",
	  "14",
	  "backLineLength",
	  "15",
	  "interline",
	  "16",
	  NULL
	};
	static const char *topBottom[] = {
	  "bottom",
	  "0",
	  "top",
	  "1",
	  NULL
	};
	static const char *encodings[] = {
	  "utf8",
	  "0",
	  "utf16",
	  "1",
	  "utf32",
	  "2",
	  "ascii8",
	  "3",
	  NULL
	};
	static const char *backFormats[] = {
	  "plain",
	  "0",
	  "html",
	  "1",
	  NULL
	};

	while (parseLine (nested))
	  {
	    checkSubActions (nested, mainActions, actions);
	    if (mainActionNumber != NOTFOUND)
	      goto choseMainAction;
	    switch (subActionNumber)
	      {
	      case NOTFOUND:
		break;
	      case 0:
		ud->cells_per_line = atoi (nested->value);
		break;
	      case 1:
		ud->lines_per_page = atoi (nested->value);
		break;
	      case 2:
		if ((k = checkValues (nested, yesNo)) != NOTFOUND)
		  ud->interpoint = k;
		break;
	      case 3:
		if (controlCharValue (nested))
		  memcpy (ud->lineEnd, nested->value,
			  nested->valueLength + 1);
		break;
	      case 4:
		if (controlCharValue (nested))

		  memcpy (ud->pageEnd, nested->value,
			  nested->valueLength + 1);
		break;
	      case 5:
		ud->beginning_braille_page_number = atoi (nested->value);
		break;
	      case 6:
		if ((k = checkValues (nested, yesNo)) != NOTFOUND)
		  ud->braille_pages = k;
		break;
	      case 7:
		if ((k = checkValues (nested, yesNo)) != NOTFOUND)
		  ud->paragraphs = k;
		break;
	      case 8:
		if (controlCharValue (nested))
		  memcpy (ud->fileEnd, nested->value,
			  nested->valueLength + 1);
		break;
	      case 9:
		if ((k = checkValues (nested, yesNo)) != NOTFOUND)
		  ud->print_pages = k;
		break;
	      case 10:
		if ((k = checkValues (nested, topBottom)) != NOTFOUND)
		  ud->print_page_number_at = ud->braille_page_number_at = k;
		break;
	      case 11:
		if ((k = checkValues (nested, topBottom)) != NOTFOUND)
		  {
		    if (k)
		      k = 0;
		    else
		      k = 1;
		    ud->print_page_number_at = ud->braille_page_number_at = k;
		  }
		break;
	      case 12:
		if ((k = checkValues (nested, yesNo)) != NOTFOUND)
		  ud->hyphenate = k;
		break;
	      case 13:
		if ((k = checkValues (nested, encodings)) != NOTFOUND)
		  ud->output_encoding = k;
		break;
	      case 14:
		if ((k = checkValues (nested, backFormats)) != NOTFOUND)
		  ud->back_text = k;
		break;
	      case 15:
		ud->back_line_length = atoi (nested->value);
		break;
	      case 16:
		if ((k = checkValues (nested, yesNo)) != NOTFOUND)
		  ud->interline = k;
		break;
	      default:
		configureError (nested, "Program error in readconfig.c");
		continue;
	      }
	  }
	if (!((ud->print_page_number_at && ud->braille_page_number_at) ||
	      (!ud->print_page_number_at && !ud->braille_page_number_at)))
	  configureError (nested,
			  "invalid combination of braille and print page number placements");
	break;

    case 1:			/*style */
	{
	  static const char *actions[] = {
	    "linesBefore",
	    "0",
	    "linesAfter",
	    "1",
	    "leftMargin",
	    "2",
	    "firstLineIndent",
	    "3",
	    "translate",
	    "6",
	    "skipNumberLines",
	    "7",
	    "format",
	    "8",
	    "newPageBefore",
	    "9",
	    "newPageAfter",
	    "10",
	    "rightHandPage",
	    "11",
	    NULL
	  };
	  static const char *formats[] = {
	    "leftJustified",
	    "0",
	    "rightJustified",
	    "1",
	    "centered",
	    "2",
	    "alignColumnsLeft",
	    "3",
	    "alignColumnsRight",
	    "4",
	    "listColumns",
	    "5",
	    "listLines",
	    "6",
	    "computerCoded",
	    "7",
	    NULL
	  };
	  static int styleCount = 0;
	  StyleType *style;
	  sem_act styleAction;
	  if (nested->value == NULL)
	    {
	      configureError (nested, "no style name given in second column");
	      break;
	    }
	  styleCount++;
	  styleAction = find_semantic_number (nested->value);
	  style = style_cases (styleAction);
	  if (style == NULL)
	    {
	      configureError (nested,
			      "invalid style name %s in column two",
			      nested->value);
	      break;
	    }
	  if (style->action == document)
	    {
	      if (styleCount != 1)
		{
		  configureError (nested,
				  "docunent style must be the first one specified");
		  break;
		}
	      else
		memcpy (&ud->para_style, &ud->document_style,
			(&ud->scratch_style - &ud->para_style));
	    }
	  style->action = styleAction;
	  while (parseLine (nested))
	    {
	      checkSubActions (nested, mainActions, actions);
	      if (mainActionNumber != NOTFOUND)
		goto choseMainAction;
	      switch (subActionNumber)
		{
		case NOTFOUND:
		  break;
		case 0:
		  style->lines_before = atoi (nested->value);
		  break;
		case 1:
		  style->lines_after = atoi (nested->value);
		  break;
		case 2:
		  style->left_margin = atoi (nested->value);
		  break;
		case 3:
		  style->first_line_indent = atoi (nested->value);
		  break;
		case 6:
		  switch ((k = find_semantic_number (nested->value)))
		    {
		    case contracted:
		    case uncontracted:
		    case compbrl:
		      style->translate = k;
		      break;
		    default:
		      configureError (nested, "no such translation");
		      break;
		    }
		  break;
		case 7:
		  if ((k = checkValues (nested, yesNo)) != NOTFOUND)
		    style->skip_number_lines = k;
		  break;
		case 8:
		  if ((k = checkValues (nested, formats)) != NOTFOUND)
		    style->format = k;
		  break;
		case 9:
		  if ((k = checkValues (nested, yesNo)) != NOTFOUND)
		    style->newpage_before = k;
		  break;
		case 10:
		  if ((k = checkValues (nested, yesNo)) != NOTFOUND)
		    style->newpage_after = k;
		  break;
		case 11:
		  if ((k = checkValues (nested, yesNo)) != NOTFOUND)
		    style->righthand_page = k;
		  break;
		default:
		  configureError (nested, "Program error in readconfig.c");
		  continue;
		}
	    }
	  break;

    case 2:			/*translation */
	  {
	    static const char *actions[] = {
	      "contractedTable",
	      "0",
	      "literarytextTable",
	      "0",
	      "editTable",
	      "1",
	      "uncontractedTable",
	      "2",
	      "compbrlTable",
	      "3",
	      "mathtextTable",
	      "4",
	      "mathexprTable",
	      "5",
	      "interlineBackTable",
	      "6",
	      NULL
	    };
	    while (parseLine (nested))
	      {
		checkSubActions (nested, mainActions, actions);
		if (mainActionNumber != NOTFOUND)
		  goto choseMainAction;
		switch (subActionNumber)
		  {
		  case NOTFOUND:
		    break;
		  case 0:
		    findTable (nested, nested->value,
			       ud->contracted_table_name);
		    break;
		  case 1:
		    findTable (nested, nested->value, ud->edit_table_name);
		    break;
		  case 2:
		    findTable (nested, nested->value,
			       ud->uncontracted_table_name);
		    break;
		  case 3:
		    findTable (nested, nested->value, ud->compbrl_table_name);
		    break;
		  case 4:
		    findTable (nested, nested->value,
			       ud->mathtext_table_name);
		    break;
		  case 5:
		    findTable (nested, nested->value,
			       ud->mathexpr_table_name);
		    break;
		  case 6:
		    findTable (nested, nested->value,
			       ud->interline_back_table_name);
		    break;
		  default:
		    configureError (nested, "Program error in readconfig.c");
		    continue;
		  }
	      }
	    break;

    case 3:			/*xml */
	    {
	      static const char *actions[] = {
		"xmlHeader",
		"0",
		"entity",
		"1",
		"internetAccess",
		"2",
		"semanticFiles",
		"3",
		"newEntries",
		"4",
		NULL
	      };
	      while (parseLine (nested))
		{
		  checkSubActions (nested, mainActions, actions);
		  if (mainActionNumber != NOTFOUND)
		    goto choseMainAction;
		  switch (subActionNumber)
		    {
		    case NOTFOUND:
		      break;
		    case 0:
		      if (entities)
			{
			  configureError
			    (nested,
			     "The header definition must precede all entity definitions.");
			  break;
			}
		      strncpy (ud->xml_header, nested->value,
			       nested->valueLength);
		      break;
		    case 1:
		      if (!entities)
			strcat (ud->xml_header, "<!DOCTYPE entities [\n");
		      entities = 1;
		      strcat (ud->xml_header, "<!ENTITY ");
		      strcat (ud->xml_header, nested->value);
		      strcat (ud->xml_header, " \"");
		      strcat (ud->xml_header, nested->value2);
		      strcat (ud->xml_header, "\">\n");
		      break;
		    case 2:
		      if ((k = checkValues (nested, yesNo)) != NOTFOUND)
			ud->internet_access = k;
		      break;
		    case 3:
		      strcpy (ud->semantic_files, nested->value);
		      break;
		    case 4:
		      if ((k = checkValues (nested, yesNo)) != NOTFOUND)
			ud->new_entries = k;
		      break;
		    default:
		      configureError (nested,
				      "Program error in readconfig.c");
		      continue;
		    }
		}
	      break;

    case 4:			/*reserved */
	      {
		static const char *actions[] = {
		  NULL
		};
		while (parseLine (nested))
		  {
		    checkSubActions (nested, mainActions, actions);
		    if (mainActionNumber != NOTFOUND)
		      goto choseMainAction;
		    switch (subActionNumber)
		      {
		      case NOTFOUND:
			break;
		      default:
			configureError (nested,
					"Program error in readconfig.c");
			continue;
		      }
		  }
		break;

    case 5:			/*include */
		{
		  static const char *actions[] = { NULL };
		  if (nested->value == NULL)
		    configureError (nested,
				    "a file name in column 2 is required");
		  else
		    config_compileFile (nested->value);
		  parseLine (nested);
		  checkSubActions (nested, mainActions, actions);
		  if (mainActionNumber != NOTFOUND)
		    goto choseMainAction;
		}
		break;

    default:
		configureError (nested, "Program error in readconfig.c");
		break;
	      }
	    }
	  }
	}
      }
    }
  return 1;
}
Example #5
0
//This function may be recruse called
void plainconf::loadConfFile(const char *path)
{
    logToMem(LOG_LEVEL_INFO, "start parsing file %s", path);

    ConfFileType type = checkFiletype(path);

    if (type == eConfUnknown)
        return;

    else if (type == eConfDir)
        loadDirectory(path, NULL);

    else if (type == eConfWildcard)
    {
        AutoStr2 prefixPath = path;
        const char *p = strrchr(path, '/');

        if (p)
            prefixPath.setStr(path, p - path);

        struct stat sb;

        //removed the wildchar filename, should be a directory if exist
        if (stat(prefixPath.c_str(), &sb) == -1)
        {
            logToMem(LOG_LEVEL_ERR, "LoadConfFile error 1, path:%s directory:%s",
                     path, prefixPath.c_str());
            return ;
        }

        if ((sb.st_mode & S_IFMT) != S_IFDIR)
        {
            logToMem(LOG_LEVEL_ERR, "LoadConfFile error 2, path:%s directory:%s",
                     path, prefixPath.c_str());
            return ;
        }

        loadDirectory(prefixPath.c_str(), p + 1);
    }

    else //existed file
    {
        //gModuleList.push_back();
        //XmlNode *xmlNode = new XmlNode;
        FILE *fp = fopen(path, "r");

        if (fp == NULL)
        {
            logToMem(LOG_LEVEL_ERR, "Cannot open configuration file: %s", path);
            return;
        }


        const int MAX_LINE_LENGTH = 8192;
        char sLine[MAX_LINE_LENGTH];
        char *p;
        char sLines[MAX_LINE_LENGTH] = {0};
        int lineNumber = 0;
        const int MAX_MULLINE_SIGN_LENGTH = 128;
        char sMultiLineModeSign[MAX_MULLINE_SIGN_LENGTH] = {0};
        size_t  nMultiLineModeSignLen = 0;  //>0 is mulline mode

        while (!feof(fp))
        {
            sLine[0] = 0x00;
            fgets(sLine, MAX_LINE_LENGTH, fp);
            ++lineNumber;
            p = sLine;

            if (nMultiLineModeSignLen)
            {
                //Check if reach the END of the milline mode
                size_t len = 0;
                const char *pLineStart = getStrNoSpace(p, len);

                if (len == nMultiLineModeSignLen &&
                    strncasecmp(pLineStart, sMultiLineModeSign, nMultiLineModeSignLen) == 0)
                {
                    nMultiLineModeSignLen = 0;
                    removeSpace(sLines,
                                1);   //Remove the last \r\n so that if it is one line, it will still be one line
                    parseLine(path, lineNumber, sLines);
                    sLines[0] = 0x00;
                }
                else
                    strcat(sLines, p);

                continue;
            }

            removeSpace(p, 0);
            removeSpace(p, 1);

            if (!isValidline(p))
                continue;

            AutoStr2 pathInclude;

            if (isInclude(p, pathInclude))
            {
                char achBuf[512] = {0};
                char *pathc = strdup(path);
                const char *curDir = dirname(pathc);
                getIncludeFile(curDir, pathInclude.c_str(), achBuf);
                free(pathc);
                loadConfFile(achBuf);
            }
            else
            {
                nMultiLineModeSignLen = checkMultiLineMode(p, sMultiLineModeSign,
                                        MAX_MULLINE_SIGN_LENGTH);

                if (nMultiLineModeSignLen > 0)
                    strncat(sLines, p, strlen(p) - (3 + nMultiLineModeSignLen));
                //need to continue
                else if (isChunkedLine(p))
                {
                    strncat(sLines, p, strlen(p) - 1);
                    //strcatchr(sLines, ' ', MAX_LINE_LENGTH); //add a space at the end of the line which has a '\\'
                }

                else
                {
                    strcat(sLines, p);
                    parseLine(path, lineNumber, sLines);
                    sLines[0] = 0x00;
                }
            }
        }

        fclose(fp);

        //Parsed, check in it
        checkInFile(path);
    }
}
Example #6
0
static boolean parseLoop (tokenInfo *const token, tokenInfo *const parent)
{
	/*
	 * Handles these statements
	 *	   for (x=0; x<3; x++)
	 *		   document.write("This text is repeated three times<br>");
	 *
	 *	   for (x=0; x<3; x++)
	 *	   {
	 *		   document.write("This text is repeated three times<br>");
	 *	   }
	 *
	 *	   while (number<5){
	 *		   document.write(number+"<br>");
	 *		   number++;
	 *	   }
	 *
	 *	   do{
	 *		   document.write(number+"<br>");
	 *		   number++;
	 *	   }
	 *	   while (number<5);
	 */
	boolean is_terminated = TRUE;

	if (isKeyword (token, KEYWORD_for) || isKeyword (token, KEYWORD_while))
	{
		readToken(token);

		if (isType (token, TOKEN_OPEN_PAREN))
		{
			skipArgumentList(token, FALSE, NULL);
		}

		if (isType (token, TOKEN_OPEN_CURLY))
		{
			parseBlock (token, parent);
		}
		else
		{
			is_terminated = parseLine(token, parent, FALSE);
		}
	}
	else if (isKeyword (token, KEYWORD_do))
	{
		readToken(token);

		if (isType (token, TOKEN_OPEN_CURLY))
		{
			parseBlock (token, parent);
		}
		else
		{
			is_terminated = parseLine(token, parent, FALSE);
		}

		if (is_terminated)
			readToken(token);

		if (isKeyword (token, KEYWORD_while))
		{
			readToken(token);

			if (isType (token, TOKEN_OPEN_PAREN))
			{
				skipArgumentList(token, TRUE, NULL);
			}
			if (! isType (token, TOKEN_SEMICOLON))
				is_terminated = FALSE;
		}
	}

	return is_terminated;
}
int processTable(char* line1, FILE* in, FILE* out) 
{
    numberOfCols = 0;
    cols = NULL;
    int i=0;
    while(line1[i] != '\0' && line1[i] != '\n') {
        if(line1[i] == '|') {
            numberOfCols++;
        }
        i++;
    } 
    numberOfCols -= 1; //Reduce for the first and last '|' which means we get 1 more than we should

    cols = malloc(numberOfCols * sizeof(Col));
    if(cols == NULL) {
        fprintf(stderr, "Out of memory\nUnable to process table.");
        return 1;
    }
    for(i=0; i<numberOfCols; i++) {
        Col c = {FALSE, FALSE, DEFAULT};
        cols[i] = c;
    }
    

    //Read the next line
    char c = 0;
    i = -1; //the col we are in
    do {
        c = getc(in);
        if(c == '|') {
            i++;
            if( i > numberOfCols) {
                // There should be more cols than first predicted (using the first line of the table) 
                numberOfCols++;
                cols = realloc (cols, numberOfCols*sizeof(Col));
                if(cols == NULL) outOfMemoryError();

                Col c = {FALSE, FALSE, DEFAULT};
                cols[i-1] = c;
            }
            c = getc(in);
            if(c == ':') {
                cols[i].l = TRUE;
            }
        } else if(c == ':') {
            c = getc(in);
            if(c == '|') {
                cols[i].r = TRUE;
                i++;
                if( i > numberOfCols) {
                    // There should be more cols than first predicted (using the first line of the table)
                    numberOfCols++;
                    cols = realloc (cols, numberOfCols*sizeof(Col));
                    if(cols == NULL) outOfMemoryError();

                    Col c = {FALSE, FALSE, DEFAULT};
                    cols[i-1] = c;
                }
                c = getc(in);
                if(c == ':') {
                    
                    cols[i].l = TRUE;
                }
            }
        }
    } while(c != '\n');

    //use up to the new line if not there already
    while(c != '\n') c = getc(in);

    for(i=0; i<numberOfCols; i++) {
        if(cols[i].r && cols[i].l) {
            cols[i].align = CENTER;
        } else if(cols[i].r) {
            cols[i].align = RIGHT;
        } else if(cols[i].l) {
            cols[i].align = LEFT;
        }
    }

    //Do we need table x? (If there are any defaults then yes)
    char tablex = false;
    for(i=0; i<numberOfCols; i++) {
        if(cols[i].align == DEFAULT) {
            tablex = true;
            break;
        }
    }

    fprintf(out, "\\begin{center}\n\\rowcolors{3}{tableShade}{white}\n");
    if(tablex) {
        fprintf(out, "\\begin{tabularx}{\\linewidth}");
    } else {
        fprintf(out, "\\begin{tabular}");
    }
    fprintf(out, "{ ");

    for(i=0; i<numberOfCols; i++) {
        putc(toChar(cols[i].align), out);
        putc(' ', out);
        if(i < numberOfCols-1) {
            putc('|', out); putc(' ', out);
        }
    }
    fprintf(out, "}\n\\hiderowcolors\n");

    int pos = 0;
    i = 0; //number of cols we have written
    c = line1[pos];
    pos++;

    int buf_size = CELL_BUF_SIZE;
    char* buf = malloc(sizeof(char) * buf_size);
    if( buf == NULL ) outOfMemoryError();
    int buf_pos = 0;

    while(c != '\n' && c != '\0') {
        c = line1[pos];
        pos++;
        if(c == '\0') break;
        if(c == '|') {
            buf[buf_pos] = '\0';
            parseLine(buf, buf_pos, in, out); //Use the markdownlatex method to process the cell
            buf_pos = 0;
            buf[0] = '\0';
            if(i < numberOfCols-1) {
                putc(' ', out);
                putc('&', out);
                putc(' ', out);
            }
            i++;
        } else if (c != '\n'){
            if(buf_pos >= buf_size-1) {
                //We need a bigger buffer!
                buf_size *= 2;
                char* newBuf = malloc(sizeof(char) * buf_size);
                if( newBuf == NULL ) outOfMemoryError();
                for(int i=0; i<buf_pos; i++) {
                    newBuf[i] = buf[i];
                }
                free(buf);
                buf = newBuf;
            }
            buf[buf_pos] = c;
            buf_pos++;
        }
    }

    // Put some empty cells at the end if there are not enough
    while(i < numberOfCols-1) {
        putc(' ', out);
        putc('&', out);
        putc(' ', out);
        i++;
    }
    
    fprintf(out, "\\\\\n\\showrowcolors \n\\hline\n");

    //while the lines start with a '|'
    while((c=getc(in)) == '|') {
        i=0;
        do {
            c = getc(in);
            if(c == '|') {
                buf[buf_pos] = '\0';
                parseLine(buf, buf_pos, in, out); //Use the markdownlatex method to process the cell
                buf_pos = 0;
                buf[0] = '\0';
                if(i != -1 && i < numberOfCols-1) putc('&', out);
                i++;
            } else if (c != '\n'){
                if(buf_pos >= buf_size-1) {
                    //We need a bigger buffer!
                    buf_size *= 2;
                    char* newBuf = malloc(sizeof(char) * buf_size);
                    if( newBuf == NULL ) outOfMemoryError();
                    for(int i=0; i<buf_pos; i++) {
                        newBuf[i] = buf[i];
                    }
                    free(buf);
                    buf = newBuf;
                }
                buf[buf_pos] = c;
                buf_pos++;
            }
        } while(c != '\n');
        

        fprintf(out, "\\\\\n");
    }
    free(buf);

    if(tablex) {
        fprintf(out, "\\end{tabularx}");
    } else {
        fprintf(out, "\\end{tabular}");
    }
    fprintf(out, "\n\\end{center}\n\\vspace{5mm}\n");

    free(cols);
    return 0;
}
Example #8
0
int main(int argc, char **argv, char **envp)
{
	struct ReadBuffer * buf = newReadBuffer(fileno(stdin));
	char * line = NULL;
	size_t linesz = 0;
	int act = 0;

	setupSignals();

	openlog("squidGuard", LOG_PID | LOG_NDELAY | LOG_CONS, SYSLOG_FAC);

	if (!parseOptions(argc, argv)) {
		closelog();
		exit(1);
	}

	registerSettings();

	//sgSetGlobalErrorLogFile();
	sgReadConfig(configFile);
	sgSetGlobalErrorLogFile();

	sgLogInfo("squidGuard %s started", VERSION);

	if (globalUpdate || globalCreateDb != NULL) {
		sgLogInfo("db update done");
		sgLogInfo("squidGuard stopped.");
		closelog();

		freeAllLists();
		exit(0);
	}

	sgLogInfo("squidGuard ready for requests");

	while ((act = doBufferRead(buf, &line, &linesz)) >= 0) {
		struct AccessList *acl;
		static struct SquidInfo request;

		if (act == 0) {
			sgReloadConfig(configFile);
			continue;
		}

		if (authzMode == 1) {
			if (parseAuthzLine(line, &request) != 1) {
				sgLogError("Error parsing squid acl helper line");
				denyOnError("Error parsing squid acl helper line");
				continue;
			}
		} else {
			if (parseLine(line, &request) != 1) {
				sgLogError("Error parsing squid redirector line");
				denyOnError("Error parsing squid redirector line");
				continue;
			}
		}

		if (inEmergencyMode) {
			const char *message = "squidGuard is in emergency mode, check configuration";
			if (passthrough)
				allowOnError(message);
			else
				denyOnError(message);
			continue;
		}

		for (acl = getFirstAccessList(); acl; acl = acl->next) {
			char *redirect = NULL;
			enum AccessResults access = checkAccess(acl, &request, &redirect);

			if (access == ACCESS_UNDEFINED)
				continue;

			if (access == ACCESS_GRANTED) {
				grantAccess(acl);
				break;
			}

			denyAccess(acl, redirect, &request);
			sgFree(redirect);

			break;
		}

		fflush(stdout);
	}

	sgLogNotice("squidGuard stopped");
	closelog();
	freeAllLists();
	sgFree(line);
	freeReadBuffer(buf);
	exit(0);
}
Example #9
0
bool INIFile::loadINIFile()
{
   FILE * inf;
   TEMPBUFF( buffer, 256 );
   INISection *thisSect;
   IniEntryPtr this_entry;
   bool realSections = false;

   if ( fileLoaded )
   {
      if ( !checkStat() )
         return false;			// no change, so don't re-read
      writePrivateProfileString( 0, 0, 0 );
      for ( std::vector <IniSectionPtr>::iterator thisSect = sections.begin(); thisSect != sections.end(); thisSect++ )
      {
         delete ( *thisSect );
      }
      sections.clear();
      fileLoaded = false;
   }

   fileLoaded = true;

   if ( ( inf = fopen( loadedFileName.c_str(), "rt" ) ) == 0 )
   {
      MinosParameters::getMinosParameters() ->mshowMessage( String( "Initialisation file \"" ) + loadedFileName.c_str() + "\" not found." );
      //      invalid = false;
      return false;
   }

   thisSect = new INISection( this, "?Comments", false );
   // create dummy section for leading comments

   while ( fgets( buffer, 256, inf ) != 0 )
   {
      TEMPBUFF ( Parameter, 256 );
      if ( strchr( buffer, '[' ) && ( sscanf( buffer, " [ %255[^\n]", Parameter ) == 1 ) )
      {
         char * p = strchr( Parameter, ']' );
         if ( p != 0 )
         {
            *p = '\0';
            thisSect = new INISection( this, Parameter, true );
            realSections = true;
            continue;
         }
         // and if no trailing ']' should we be lenient?
      }

      if ( buffer[ strlen( buffer ) - 1 ] == '\n' )
         buffer[ strlen( buffer ) - 1 ] = 0;		// take off trailing new line

      char *a[ 3 ];
      bool sep2seen;
      int scnt = parseLine( buffer, '=', a, 2, 0, sep2seen );
      trimr( a[ 0 ] );
      trimr( a[ 1 ] );

      if ( scnt )
      {
         this_entry = new INIEntry( thisSect, a[ 0 ], true );
         // somewhere we need to cope with quoted parameters
         this_entry->setValue( a[ 1 ] );
         this_entry->setClean();
      }
      else
      {
         // create comment entry
         this_entry = new INIEntry( thisSect, "??", false );
         this_entry->setValue( a[ 0 ] );
         this_entry->setClean();
      }
   }
   fclose( inf );
   // now stat the file so we can check for changes
   checkStat();

   /*
      if ( !realSections )
      {
         mshowMessage( String( "Initialisation file \"" ) + loadedFileName.c_str() + "\" invalid (no sections)." );
         invalid = true;
      }
      else
      {
         invalid = false;
      }
   */ 
   return realSections;
}
Example #10
0
static boolean parseLoop (tokenInfo *const token, tokenInfo *const parent)
{
	/*
	 * Handles these statements
	 *	   for (x=0; x<3; x++)
	 *		   document.write("This text is repeated three times<br>");
	 *
	 *	   for (x=0; x<3; x++)
	 *	   {
	 *		   document.write("This text is repeated three times<br>");
	 *	   }
	 *
	 *	   while (number<5){
	 *		   document.write(number+"<br>");
	 *		   number++;
	 *	   }
	 *
	 *	   do{
	 *		   document.write(number+"<br>");
	 *		   number++;
	 *	   }
	 *	   while (number<5);
	 */
	boolean is_terminated = TRUE;

	if (isKeyword (token, KEYWORD_for) || isKeyword (token, KEYWORD_while))
	{
		readToken(token);

		if (isType (token, TOKEN_OPEN_PAREN))
		{
			/*
			 * Handle nameless functions, these will only
			 * be considered methods.
			 */
			skipArgumentList(token, FALSE, NULL);
		}

		if (isType (token, TOKEN_OPEN_CURLY))
		{
			/*
			 * This will be either a function or a class.
			 * We can only determine this by checking the body
			 * of the function.  If we find a "this." we know
			 * it is a class, otherwise it is a function.
			 */
			parseBlock (token, parent);
		}
		else
		{
			is_terminated = parseLine(token, parent, FALSE);
		}
	}
	else if (isKeyword (token, KEYWORD_do))
	{
		readToken(token);

		if (isType (token, TOKEN_OPEN_CURLY))
		{
			/*
			 * This will be either a function or a class.
			 * We can only determine this by checking the body
			 * of the function.  If we find a "this." we know
			 * it is a class, otherwise it is a function.
			 */
			parseBlock (token, parent);
		}
		else
		{
			is_terminated = parseLine(token, parent, FALSE);
		}

		if (is_terminated)
			readToken(token);

		if (isKeyword (token, KEYWORD_while))
		{
			readToken(token);

			if (isType (token, TOKEN_OPEN_PAREN))
			{
				/*
				 * Handle nameless functions, these will only
				 * be considered methods.
				 */
				skipArgumentList(token, TRUE, NULL);
			}
			if (! isType (token, TOKEN_SEMICOLON))
				is_terminated = FALSE;
		}
	}

	return is_terminated;
}
Example #11
0
int
_tr_blocklistSetContent (tr_blocklist * b, const char * filename)
{
    FILE * in;
    FILE * out;
    int inCount = 0;
    char line[2048];
    const char * err_fmt = _("Couldn't read \"%1$s\": %2$s");
    struct tr_ipv4_range * ranges = NULL;
    size_t ranges_alloc = 0;
    size_t ranges_count = 0;

    if (!filename)
    {
        blocklistDelete (b);
        return 0;
    }

    in = fopen (filename, "rb");
    if (!in)
    {
        tr_err (err_fmt, filename, tr_strerror (errno));
        return 0;
    }

    blocklistClose (b);

    out = fopen (b->filename, "wb+");
    if (!out)
    {
        tr_err (err_fmt, b->filename, tr_strerror (errno));
        fclose (in);
        return 0;
    }

    /* load the rules into memory */
    while (fgets (line, sizeof (line), in) != NULL)
    {
        char * walk;
        struct tr_ipv4_range range;

        ++inCount;

        /* zap the linefeed */
        if ((walk = strchr (line, '\r'))) *walk = '\0';
        if ((walk = strchr (line, '\n'))) *walk = '\0';

        if (!parseLine (line, &range))
        {
            /* don't try to display the actual lines - it causes issues */
            tr_err (_("blocklist skipped invalid address at line %d"), inCount);
            continue;
        }

        if (ranges_alloc == ranges_count)
        {
            ranges_alloc += 4096; /* arbitrary */
            ranges = tr_renew (struct tr_ipv4_range, ranges, ranges_alloc);
        }

        ranges[ranges_count++] = range;
    }
QStringList CSV::parseLine(){
	return parseLine(readLine());
}
Example #13
0
void DirectiveParser::parseDirective(Token *token)
{
    assert(token->type == Token::PP_HASH);

    mTokenizer->lex(token);
    if (isEOD(token))
    {
        // Empty Directive.
        return;
    }

    DirectiveType directive = getDirective(token);

    // While in an excluded conditional block/group,
    // we only parse conditional directives.
    if (skipping() && !isConditionalDirective(directive))
    {
        skipUntilEOD(mTokenizer, token);
        return;
    }

    switch(directive)
    {
      case DIRECTIVE_NONE:
        mDiagnostics->report(Diagnostics::PP_DIRECTIVE_INVALID_NAME,
                             token->location, token->text);
        skipUntilEOD(mTokenizer, token);
        break;
      case DIRECTIVE_DEFINE:
        parseDefine(token);
        break;
      case DIRECTIVE_UNDEF:
        parseUndef(token);
        break;
      case DIRECTIVE_IF:
        parseIf(token);
        break;
      case DIRECTIVE_IFDEF:
        parseIfdef(token);
        break;
      case DIRECTIVE_IFNDEF:
        parseIfndef(token);
        break;
      case DIRECTIVE_ELSE:
        parseElse(token);
        break;
      case DIRECTIVE_ELIF:
        parseElif(token);
        break;
      case DIRECTIVE_ENDIF:
        parseEndif(token);
        break;
      case DIRECTIVE_ERROR:
        parseError(token);
        break;
      case DIRECTIVE_PRAGMA:
        parsePragma(token);
        break;
      case DIRECTIVE_EXTENSION:
        parseExtension(token);
        break;
      case DIRECTIVE_VERSION:
        parseVersion(token);
        break;
      case DIRECTIVE_LINE:
        parseLine(token);
        break;
      default:
        assert(false);
        break;
    }

    skipUntilEOD(mTokenizer, token);
    if (token->type == Token::LAST)
    {
        mDiagnostics->report(Diagnostics::PP_EOF_IN_DIRECTIVE,
                             token->location, token->text);
    }
}
Example #14
0
// received a character from UART
void GSwifi::parseByte(uint8_t dat) {
    static uint8_t  next_token; // split each byte into tokens (cid,ip,port,length,data)
    static bool     escape = false;
    char temp[GS_MAX_PATH_LENGTH+1];

    if (dat == ESCAPE) {
        // 0x1B : Escape
        GSLOG_PRINT("e< ");
    }
    else { // if (next_token != NEXT_TOKEN_DATA) {
        GSLOG_WRITE(dat);
    }

    if (gs_mode_ == GSMODE_COMMAND) {
        if (escape) {
            // esc
            switch (dat) {
            case 'O':
            case 'F':
                // ignore
                break;
            case 'Z':
            case 'H':
                gs_mode_   = GSMODE_DATA_RX_BULK;
                next_token = NEXT_TOKEN_CID;
                break;
            default:
                // GSLOG_PRINT("!E1 "); GSLOG_PRINTLN2(dat,HEX);
                break;
            }
            escape = false;
        }
        else {
            if (dat == ESCAPE) {
                escape = true;
            }
            else if (dat == '\n') {
                // end of line
                parseLine();
            }
            else if (dat != '\r') {
                if ( ! ring_isfull(_buf_cmd) ) {
                    ring_put(_buf_cmd, dat);
                }
                else {
                    GSLOG_PRINTLN("!E2");
                }
            }
        }
        return;
    }
    else if (gs_mode_ != GSMODE_DATA_RX_BULK) {
        return;
    }

    static uint16_t       len;
    static char           len_chars[5];
    static int8_t         current_cid;
    static GSREQUESTSTATE request_state;

    if (next_token == NEXT_TOKEN_CID) {
        // dat is cid
        current_cid = x2i(dat);
        ASSERT((0 <= current_cid) && (current_cid <= 16));

        next_token  = NEXT_TOKEN_LENGTH;
        len         = 0;
    }
    else if (next_token == NEXT_TOKEN_LENGTH) {
        // Data Length is 4 ascii char represents decimal value i.e. 1400 byte (0x31 0x34 0x30 0x30)
        len_chars[ len ++ ] = dat;
        if (len >= 4) {
            len_chars[ len ] = 0;
            len        = atoi(len_chars); // length of data
            next_token = NEXT_TOKEN_DATA;

            if (content_lengths_[ current_cid ] > 0) {
                // this is our 2nd bulk message from GS for this response
                // we already swallowed HTTP response headers,
                // following should be body
                request_state = GSREQUESTSTATE_BODY;
            }
            else {
                request_state = GSREQUESTSTATE_HEAD1;
            }
            ring_clear( _buf_cmd ); // reuse _buf_cmd to store HTTP request
        }
    }
    else if (next_token == NEXT_TOKEN_DATA) {
        len --;

        if (cidIsRequest(current_cid)) { // request against us
            static uint16_t error_code;
            static int8_t   routeid;

            switch (request_state) {
            case GSREQUESTSTATE_HEAD1:
                if (dat != '\n') {
                    if ( ! ring_isfull(_buf_cmd) ) {
                        ring_put( _buf_cmd, dat );
                    }
                    // ignore overflowed
                }
                else {
                    // end of request line

                    // reuse "temp" buffer to parse method and path
                    int8_t  result  = parseRequestLine((char*)temp, 7);
                    GSMETHOD method = GSMETHOD_UNKNOWN;
                    if ( result == 0 ) {
                        method = x2method(temp);
                        result = parseRequestLine((char*)temp, GS_MAX_PATH_LENGTH);
                    }
                    if ( result != 0 ) {
                        // couldn't detect method or path
                        request_state = GSREQUESTSTATE_ERROR;
                        error_code    = 400;
                        ring_clear(_buf_cmd);
                        break;
                    }

                    routeid = router(method, temp);
                    if ( routeid < 0 ) {
                        request_state = GSREQUESTSTATE_ERROR;
                        error_code    = 404;
                        ring_clear(_buf_cmd);
                        break;
                    }
                    request_state                   = GSREQUESTSTATE_HEAD2;
                    continuous_newlines_            = 0;
                    content_lengths_[ current_cid ] = 0;
                    has_requested_with_             = false;
                    ring_clear(_buf_cmd);
                }
                break;
            case GSREQUESTSTATE_HEAD2:
                if(0 == parseHead2(dat, current_cid)) {
                    request_state = GSREQUESTSTATE_BODY;
                    // dispatched once, at start of body
                    dispatchRequestHandler(current_cid, routeid, GSREQUESTSTATE_BODY_START);
                }
                break;
            case GSREQUESTSTATE_BODY:
                if (content_lengths_[ current_cid ] > 0) {
                    content_lengths_[ current_cid ] --;
                }
                if (ring_isfull(_buf_cmd)) {
                    dispatchRequestHandler(current_cid, routeid, request_state); // POST, user callback should write()
                }
                ring_put(_buf_cmd, dat);
                break;
            case GSREQUESTSTATE_ERROR:
                // skip until received whole request
                break;
            case GSREQUESTSTATE_RECEIVED:
            default:
                break;
            }

            // end of bulk transfered data
            if (len == 0) {
                gs_mode_ = GSMODE_COMMAND;

                if ( request_state == GSREQUESTSTATE_ERROR ) {
                    writeHead( current_cid, error_code );
                    writeEnd();
                    ring_put( &commands, COMMAND_CLOSE );
                    ring_put( &commands, current_cid );
                }
                else {
                    if (content_lengths_[ current_cid ] == 0) {
                        // if Content-Length header was longer than <ESC>Z length,
                        // we wait til next bulk transfer
                        request_state = GSREQUESTSTATE_RECEIVED;
                    }
                    // user callback should write(), writeEnd() and close()
                    dispatchRequestHandler(current_cid, routeid, request_state);
                }
                ring_clear(_buf_cmd);
            }
        }
        else {
            // is request from us
            static uint16_t status_code;

            switch (request_state) {
            case GSREQUESTSTATE_HEAD1:
                if (dat != '\n') {
                    if ( ! ring_isfull(_buf_cmd) ) {
                        // ignore if overflowed
                        ring_put( _buf_cmd, dat );
                    }
                }
                else {
                    uint8_t i=0;

                    // skip 9 characters "HTTP/1.1 "
                    while (i++ < 9) {
                        ring_get( _buf_cmd, &temp[0], 1 );
                    }

                    // copy 3 numbers representing status code into temp buffer
                    temp[ 3 ] = 0;
                    int8_t count = ring_get( _buf_cmd, temp, 3 );
                    if (count != 3) {
                        // protocol error
                        // we should receive something like: "200 OK", "401 Unauthorized"
                        status_code   = 999;
                        request_state = GSREQUESTSTATE_ERROR;
                        break;
                    }
                    status_code                     = atoi(temp);
                    request_state                   = GSREQUESTSTATE_HEAD2;
                    continuous_newlines_            = 0;
                    content_lengths_[ current_cid ] = 0;
                    ring_clear(_buf_cmd);
                }
                break;
            case GSREQUESTSTATE_HEAD2:
                if(0 == parseHead2(dat, current_cid)) {
                    request_state = GSREQUESTSTATE_BODY;
                    // dispatched once, at start of body
                    dispatchResponseHandler(current_cid, status_code, GSREQUESTSTATE_BODY_START);
                }
                break;
            case GSREQUESTSTATE_BODY:
                if (content_lengths_[ current_cid ] > 0) {
                    content_lengths_[ current_cid ] --;
                }
                if (ring_isfull(_buf_cmd)) {
                    dispatchResponseHandler(current_cid, status_code, GSREQUESTSTATE_BODY);
                }
                ring_put(_buf_cmd, dat);
                break;
            case GSREQUESTSTATE_ERROR:
            case GSREQUESTSTATE_RECEIVED:
            default:
                break;
            }

            if (len == 0) {
                gs_mode_ = GSMODE_COMMAND;

                if ( request_state == GSREQUESTSTATE_ERROR ) {
                    dispatchResponseHandler(current_cid, status_code, request_state);
                }
                else {
                    if (content_lengths_[ current_cid ] == 0) {
                        // if Content-Length header was longer than <ESC>Z length,
                        // we wait til all response body received.
                        // we need to close our clientRequest before handling it.
                        // GS often locks when closing 2 connections in a row
                        // ex: POST /keys from iPhone (cid:1) -> POST /keys to server (cid:2)
                        //     response from server arrives -> close(1) -> close(2) -> lock!!
                        // the other way around: close(2) -> close(1) doesn't lock :(
                        request_state = GSREQUESTSTATE_RECEIVED;
                    }
                    dispatchResponseHandler(current_cid, status_code, request_state);
                }
                ring_clear( _buf_cmd );
            }
        } // is response
    } // (next_token == NEXT_TOKEN_DATA)
}
Example #15
0
int
tr_blocklistFileSetContent (tr_blocklistFile * b, const char * filename)
{
    tr_sys_file_t in;
    tr_sys_file_t out;
    int inCount = 0;
    char line[2048];
    const char * err_fmt = _("Couldn't read \"%1$s\": %2$s");
    struct tr_ipv4_range * ranges = NULL;
    size_t ranges_alloc = 0;
    size_t ranges_count = 0;
    tr_error * error = NULL;

    if (!filename)
    {
        blocklistDelete (b);
        return 0;
    }

    in = tr_sys_file_open (filename, TR_SYS_FILE_READ, 0, &error);
    if (in == TR_BAD_SYS_FILE)
    {
        tr_logAddError (err_fmt, filename, error->message);
        tr_error_free (error);
        return 0;
    }

    blocklistClose (b);

    out = tr_sys_file_open (b->filename,
                            TR_SYS_FILE_WRITE | TR_SYS_FILE_CREATE | TR_SYS_FILE_TRUNCATE,
                            0666, &error);
    if (out == TR_BAD_SYS_FILE)
    {
        tr_logAddError (err_fmt, b->filename, error->message);
        tr_error_free (error);
        tr_sys_file_close (in, NULL);
        return 0;
    }

    /* load the rules into memory */
    while (tr_sys_file_read_line (in, line, sizeof (line), NULL))
    {
        struct tr_ipv4_range range;

        ++inCount;

        if (!parseLine (line, &range))
        {
            /* don't try to display the actual lines - it causes issues */
            tr_logAddError (_("blocklist skipped invalid address at line %d"), inCount);
            continue;
        }

        if (ranges_alloc == ranges_count)
        {
            ranges_alloc += 4096; /* arbitrary */
            ranges = tr_renew (struct tr_ipv4_range, ranges, ranges_alloc);
        }

        ranges[ranges_count++] = range;
    }
Example #16
0
int CPU::openfile(const string &filename) {
	FILE *input = fopen(filename.c_str(), "r");
	if (input == NULL) {
		printf("Unable to open input file '%s'\n", filename.c_str());
		return -1;
	}
	
	vector<int> totalData;
	printf("Opened file!\n\n");
	
	char line[128];
	int lineNum = 0;
	while (fgets(line, sizeof (line), input) != NULL) {
		lineNum++;
		size_t lineLen = strlen(line);
		
#ifdef DEBUG
		printf("Line %d, %s\n", lineLen, line);
#endif
		if (lineLen > 1) {
			char end = line[lineLen - 1];
			if (end < 32) {
				line[lineLen - 1] = '\0';
			}
#ifdef DEBUG
			printf("%d: %s\n", lineNum, line);
#endif
			
			if (lineLen > 2) {
				if (line[0] == '/' && line[1] == '/') {
					continue;
				}
			}
			
			vector<string> lineTokened;
			
			Tokeniser t(line);
			const char *token = t.nextToken();
			bool first = true;
			bool preproc = false;
			while(token != NULL) { 
				if (first && token[0] == '#') {
					preproc = true;
					token = t.nextToken();
					first = false;
					continue;
				}
				if (!preproc) {
					const char *defineCheck = getDefine(token);
					if (defineCheck != NULL) {
#ifdef DEBUG
						printf("Replacing >%s< with >%s<\n", token, defineCheck);
#endif
						token = defineCheck;
					}
				}
				string tokenStr = string(token);
				
				lineTokened.push_back(string(token));
				token = t.nextToken();
				first = false;
			}
			
			if (preproc) {
				parsePreproc(lineTokened);
			} else if (conditionOk()) {
				parseLine(lineTokened);
			}
		}
	}
	fclose(input);
}
Example #17
0
static boolean parseBlock (tokenInfo *const token, tokenInfo *const orig_parent)
{
	boolean is_class = FALSE;
	boolean read_next_token = TRUE;
	vString * saveScope = vStringNew ();
	tokenInfo *const parent = newToken ();

	/* backup the parent token to allow calls like parseBlock(token, token) */
	copyToken (parent, orig_parent, TRUE);

	token->nestLevel++;
	/*
	 * Make this routine a bit more forgiving.
	 * If called on an open_curly advance it
	 */
	if (isType (token, TOKEN_OPEN_CURLY))
		readToken(token);

	if (! isType (token, TOKEN_CLOSE_CURLY))
	{
		/*
		 * Read until we find the closing brace,
		 * any nested braces will be handled within
		 */
		do
		{
			read_next_token = TRUE;
			if (isKeyword (token, KEYWORD_this))
			{
				/*
				 * Means we are inside a class and have found
				 * a class, not a function
				 */
				is_class = TRUE;
				vStringCopy(saveScope, token->scope);
				addToScope (token, parent->string);

				/*
				 * Ignore the remainder of the line
				 * findCmdTerm(token);
				 */
				read_next_token = parseLine (token, parent, is_class);

				vStringCopy(token->scope, saveScope);
			}
			else if (isKeyword (token, KEYWORD_var) ||
					 isKeyword (token, KEYWORD_let) ||
					 isKeyword (token, KEYWORD_const))
			{
				/*
				 * Potentially we have found an inner function.
				 * Set something to indicate the scope
				 */
				vStringCopy(saveScope, token->scope);
				addToScope (token, parent->string);
				read_next_token = parseLine (token, parent, is_class);
				vStringCopy(token->scope, saveScope);
			}
			else if (isKeyword (token, KEYWORD_function))
			{
				vStringCopy(saveScope, token->scope);
				addToScope (token, parent->string);
				parseFunction (token);
				vStringCopy(token->scope, saveScope);
			}
			else if (isType (token, TOKEN_OPEN_CURLY))
			{
				/* Handle nested blocks */
				parseBlock (token, parent);
			}
			else
			{
				/*
				 * It is possible for a line to have no terminator
				 * if the following line is a closing brace.
				 * parseLine will detect this case and indicate
				 * whether we should read an additional token.
				 */
				read_next_token = parseLine (token, parent, is_class);
			}

			/*
			 * Always read a new token unless we find a statement without
			 * a ending terminator
			 */
			if( read_next_token )
				readToken(token);

			/*
			 * If we find a statement without a terminator consider the
			 * block finished, otherwise the stack will be off by one.
			 */
		} while (! isType (token, TOKEN_EOF) &&
				 ! isType (token, TOKEN_CLOSE_CURLY) && read_next_token);
	}

	deleteToken (parent);
	vStringDelete(saveScope);
	token->nestLevel--;

	return is_class;
}
//------------------------------------------------------------------------------
tFirmwareRet firmwareinfodecode_decodeInfo(tFirmwareStoreHandle pStore_p,
                                           tFirmwareInfoList* ppInfoList_p)
{
    tFirmwareRet            ret = kFwReturnOk;
    size_t                  dataSize;
    void*                   pData;
    char*                   pFileString;
    char*                   pLine;
    tFirmwareInfoList       pList = NULL;
    tFirmwareInfoEntry**    ppInsertIter = &pList;
    tFirmwareInfoEntry*     pEntry = NULL;

    if (ppInfoList_p == NULL)
    {
        ret = kFwReturnInvalidParameter;
        goto EXIT;
    }

    ret = firmwarestore_loadData(pStore_p);
    if (ret != kFwReturnOk)
    {
        goto EXIT;
    }

    ret = firmwarestore_getData(pStore_p, &pData, &dataSize);
    if (ret != kFwReturnOk)
    {
        goto EXIT;
    }

    pFileString = pData;

    pLine = strtok(pFileString, FIRMWAREINFO_ASCII_LINE_SEPERATOR);

    while (pLine != NULL)
    {
        pEntry = malloc(sizeof(tFirmwareInfoEntry));
        if (pEntry == NULL)
        {
            ret = kFwReturnNoResource;
            goto EXIT;
        }

        memset(pEntry, 0, sizeof(tFirmwareInfoEntry));

        ret = parseLine(pStore_p, pLine, &pEntry->fwInfo);
        if (ret == kFwReturnOk)
        {
            if (*ppInsertIter != NULL)
            {
                (*ppInsertIter)->pNext = pEntry;
            }
            *ppInsertIter = pEntry;
            ppInsertIter = &pEntry->pNext;
        }
        else
        {
            free(pEntry);

            if (ret == kFwReturnIgnoreInfoFileLine)
            {
                ret = kFwReturnOk;
            }
            else
            {
                break;
            }
        }

        pLine = strtok(NULL, FIRMWAREINFO_ASCII_LINE_SEPERATOR);
    }

    *ppInfoList_p = pList;

EXIT:
    (void)firmwarestore_flushData(pStore_p);

    if (ret != kFwReturnOk)
    {
        while (pList != NULL)
        {
            pEntry = pList;
            pList = pEntry->pNext;
            free(pEntry);
        }
    }

    return ret;
}
Example #19
0
bool LDModelParser::parseModel(
	LDLModel *ldlModel,
	TREModel *treModel,
	bool bfc,
	int activeColorNumber)
{
	BFCState newState = ldlModel->getBFCState();
	LDObiInfo obiInfo;
	LDObiInfo *origObiInfo = m_obiInfo;

	if (m_obiInfo != NULL && m_obiInfo->isActive() &&
		!ldlModel->colorNumberIsTransparent(activeColorNumber))
	{
		obiInfo.start(m_obiInfo->getColor(), m_obiInfo->getEdgeColor(), true);
	}
	m_obiInfo = &obiInfo;
	bfc = ((bfc && (newState == BFCOnState)) || newState == BFCForcedOnState)
		&& getBFCFlag();
	if (ldlModel && !performPrimitiveSubstitution(ldlModel, treModel,
		activeColorNumber, bfc))
	{
		LDLFileLineArray *fileLines = ldlModel->getFileLines();

		if (fileLines)
		{
			int i;
			int count = ldlModel->getActiveLineCount();
			StringSet obiOrigTokens = m_obiTokens;

			for (i = 0; i < count && !m_abort; i++)
			{
				LDLFileLine *fileLine = (*fileLines)[i];

				if (fileLine->isValid())
				{
					if (fileLine->isActionLine() &&
						actionLineIsActive((LDLActionLine *)fileLine))
					{
						if (m_flags.newTexmap)
						{
							treModel->startTexture(fileLine->getTexmapType(),
								fileLine->getTexmapFilename(),
								fileLine->getTexmapImage(),
								fileLine->getTexmapPoints());
							m_flags.newTexmap = false;
							m_flags.texmapStarted = true;
						}
						//if (m_flags.obi)
						//{
						//	((LDLActionLine *)fileLine)->setObiOverrideActive(
						//		!ldlModel->colorNumberIsTransparent(
						//		activeColorNumber));
						//}
						switch (fileLine->getLineType())
						{
						case LDLLineTypeModel:
							parseModel((LDLModelLine *)fileLine, treModel, bfc,
								activeColorNumber);
							break;
						case LDLLineTypeLine:
							parseLine((LDLShapeLine *)fileLine, treModel,
								activeColorNumber);
							break;
						case LDLLineTypeTriangle:
							parseTriangle((LDLShapeLine *)fileLine, treModel,
								bfc, false, activeColorNumber);
							break;
						case LDLLineTypeQuad:
							parseQuad((LDLShapeLine *)fileLine, treModel, bfc,
								false, activeColorNumber);
							break;
						case LDLLineTypeConditionalLine:
							parseConditionalLine(
								(LDLConditionalLineLine *)fileLine, treModel,
								activeColorNumber);
							break;
						default:
							break;
						}
						m_obiInfo->actionHappened();
						if (m_flags.texmapNext)
						{
							treModel->endTexture();
						}
					}
					else if (fileLine->getLineType() == LDLLineTypeComment)
					{
						parseCommentLine((LDLCommentLine *)fileLine, treModel);
					}
				}
				if (ldlModel == m_topLDLModel && m_alertSender != NULL)
				{
					TCProgressAlert::send("LDLModelParser",
						TCLocalStrings::get(_UC("ParsingStatus")),
						(float)(i + 1) / (float)(count + 1), &m_abort, this);
				}
			}
			m_obiTokens = obiOrigTokens;
		}
	}
	m_obiInfo = origObiInfo;
	return !m_abort;
}
void parseSchedule() {
    
    String s=   "1,00:00,0,1 \n"
    
                //"1,14:00,D0C0D0 00000000 A0C0C0 A0C0C0 000040,1 \n" // super bright
    
                "1,07:30,040002 00000000 020403 020403 000001,1 \n"
                "1,08:00,000000 300D1525 040E0F 030E0F 000002,1 \n"
                "1,10:00,4A0020 400D1540 2C2210 2C2210 000020,1 \n"
                "1,12:00,9D0035 390A163A 614420 57441C 000020,1 \n"
                "1,13:00,C00073 60303060 B68054 B6B154 000040,1 \n" // peak day - better colors
                "1,14:00,D000C0 FF4040B8 B09080 B0B080 000080,1 \n" // super bright
                "1,14:30,000000 05000005 000093 000000 500000,1 \n" // siesta
                //"1,14:30,000000 0C00000C 040000 040000 180000,1 \n" // siesta
                "1,15:45,D000C0 FF3F3FB4 A8C0D1 A8DFC8 0001DF,1 \n" //extra super bright
                //"1,15:30,D000C0 FF4040B8 B0B080 B0B080 000080,1 \n" // super bright
                "1,18:00,C00073 60303060 A0A054 A0B154 000040,1 \n" // peak day - better colors
                "1,19:30,B10026 30000040 194F20 194F20 00001B,1 \n"
                "1,20:30,35405F 08000000 1B080B 1B080B 0A0131,1 \n" // early sunset
                //"1,20:20,03005D 08000000 1A070A 1A070A 090130,1 \n" // late sunset
                "1,20:50,34615B 17000000 190009 190009 3A460C,1 \n" // late sunset
                "1,21:10,14400E 08000000 060805 060805 10060D,1 \n" // midway between sunset and dusk
                "1,21:30,04001D 04000004 020413 010424 0F0505,1 \n" // dusk2
                "1,22:00,000000 00030300 010B0A 010D0A 000001,1 \n" // bright moonlight
                "1,22:15,000000 00030300 010804 010804 000001,1 \n" // moonlight
                "1,22:30,000000 00020300 000000 010603 000000,1 \n"
                "1,22:45,000000 00000000 000000 000000 000000,1 \n"    
    
    
    
    
    /*
                "1,07:30,0400 0200 020403000001 020403000001,1 \n"
                "1,08:00,1200 1008 100810040006 100810040006,1 \n"
                //"1,10:00,2D00 2000 184810000020 184810000020,1 \n"
                "1,10:00,4A26 2000 2E2210000020 2C2210000020,1 \n"
                
                "1,12:00,A070 4000 60A020000060 60A020000060,1 \n"
                //"1,15:00,E800 815F FFFFD30000FF FFFFDF0000FF,1 \n" // peak day 
                //"1,15:00,6F0A 0009 7EA9A0000CA9 81F2BC0000CA,1 \n" // peak day - less bright
                "1,13:00,C07C 736F A08B40000080 B6B154000080,1 \n" // peak day - better colors
                
                //"1,14:00,E0D0 D0E0 C0FFFF000080 C0FFFF000080,1 \n" // super bright
                //on holiday reduce lighting
                "1,14:00,D0C0 C0D0 A0C0C0000040 A0C0C0000040,1 \n" // super bright
                
                
                "1,17:00,C07C 736F A0B140000060 A0B154000060,1 \n" // peak day - better colors
                
                //"1,19:00,6B50 6043 605020000040 605020000040,1 \n"
                "1,19:00,B15A 2672 0F4F2000001E 194F2000001B,1 \n"
                
                "1,20:00,3500 5F7A 16081D0F0335 1B080B0A0131,1 \n" // early sunset
        
                "1,20:20,2030 0020 0C01032A2426 0D0101282225,1 \n" // late sunset
                "1,20:40,1400 0E2A 06080711070D 06080510060D,1 \n" // midway between sunset and dusk
                "1,21:00,0F02 0519 01080F070000 010419050000,1 \n" // dusk2
                //"1,20:40,1000 0E1B 012010080000 012010080000,1 \n" // dusk
                "1,21:30,0600 0007 010804000001 010804000001,1 \n" // moonlight
                "1,22:00,0000 0003 000002000000 000002000000,1 \n"
                "1,22:15,0000 0000 000000000000 000000000000,1 \n"
                //"1,22:30,00,1 \n"
    */
                "1,23:59,00,1 \n"
                
                //"0,12:00,2700 0000 3FE94B0000F4 17FF480000FF,1 \n" // early afternoon AWAY
                //"0,15:00,2700 0000 3FE94B0000F4 17FF480000FF,1 \n" // peak day AWAY
                
                ;
    
    scheduleCount=0;
    int lineStart=0;
    for (int i=0; i<((int)s.length()); i++)
    {   char c=s.charAt(i);
        if (c=='\n')
        {   String line=s.substring(lineStart,i);
            //Serial.println(line);
            parseLine(line);
            lineStart=i+1;
        }
    }
}
Example #21
0
static void
parseFile(FileStream *in) {
    char line[MAX_LINE_SIZE];
    char lastLine[MAX_LINE_SIZE];
    int32_t lineSize = 0;
    int32_t lastLineSize = 0;
    UBool validParse = TRUE;

    lineNum = 0;

    /* Add the empty tag, which is for untagged aliases */
    getTagNumber("", 0);
    getTagNumber(ALL_TAG_STR, 3);
    allocString(&stringBlock, "", 0);

    /* read the list of aliases */
    while (validParse) {
        validParse = FALSE;

        /* Read non-empty lines that don't start with a space character. */
        while (T_FileStream_readLine(in, lastLine, MAX_LINE_SIZE) != NULL) {
            lastLineSize = chomp(lastLine);
            if (lineSize == 0 || (lastLineSize > 0 && isspace((int)*lastLine))) {
                uprv_strcpy(line + lineSize, lastLine);
                lineSize += lastLineSize;
            } else if (lineSize > 0) {
                validParse = TRUE;
                break;
            }
            lineNum++;
        }

        if (validParse || lineSize > 0) {
            if (isspace((int)*line)) {
                fprintf(stderr, "%s:%d: error: cannot start an alias with a space\n", path, lineNum-1);
                exit(U_PARSE_ERROR);
            } else if (line[0] == '{') {
                if (!standardTagsUsed && line[lineSize - 1] != '}') {
                    fprintf(stderr, "%s:%d: error: alias needs to start with a converter name\n", path, lineNum);
                    exit(U_PARSE_ERROR);
                }
                addOfficialTaggedStandards(line, lineSize);
                standardTagsUsed = TRUE;
            } else {
                if (standardTagsUsed) {
                    parseLine(line);
                }
                else {
                    fprintf(stderr, "%s:%d: error: alias table needs to start a list of standard tags\n", path, lineNum);
                    exit(U_PARSE_ERROR);
                }
            }
            /* Was the last line consumed */
            if (lastLineSize > 0) {
                uprv_strcpy(line, lastLine);
                lineSize = lastLineSize;
            }
            else {
                lineSize = 0;
            }
        }
        lineNum++;
    }
}
int Zmatrix_Scan::scanInZmatrix(){
    stringstream output;
    int numOfLines=0;
    ifstream zmatrixScanner(fileName.c_str());

    if( !zmatrixScanner.is_open() )
        return -1;
    else {
        string line; 
    while( zmatrixScanner.good() )
    {
        numOfLines++;
        getline(zmatrixScanner,line);

        Molecule workingMolecule;

        //check if it is a commented line,
        //or if it is a title line
        try{
            if(line.at(0) != '#' && numOfLines > 1)
            parseLine(line,numOfLines);
        }
        catch(std::out_of_range& e){}

        if (startNewMolecule){
            Atom* atomArray;
            Bond* bondArray;
            Angle* angleArray;
            Dihedral* dihedralArray;
            
            atomArray = (Atom*) malloc(sizeof(Atom) * atomVector.size());
            bondArray = (Bond*) malloc(sizeof(Bond) * bondVector.size());
            angleArray = (Angle*) malloc(sizeof(Angle) * angleVector.size());
            dihedralArray = (Dihedral*) malloc(sizeof(Dihedral) * dihedralVector.size());

            for (int i = 0; i < atomVector.size(); i++){
                atomArray[i] = atomVector[i];
            }
            for (int i = 0; i < bondVector.size(); i++){
                bondArray[i] = bondVector[i];
            }
            for (int i = 0; i < angleVector.size(); i++){
                angleArray[i] = angleVector[i];
            }
            for (int i = 0; i < dihedralVector.size(); i++){
                dihedralArray[i] = dihedralVector[i];
            }

            moleculePattern.push_back(createMolecule(-1, atomArray, angleArray, bondArray, dihedralArray, 
                 atomVector.size(), angleVector.size(), bondVector.size(), dihedralVector.size()));

            atomVector.clear();
            bondVector.clear();
            angleVector.clear();
            dihedralVector.clear();

            startNewMolecule = false;
        } 
    }

    zmatrixScanner.close();
	 
    }

    return 0;
}
Example #23
0
void ConsoleDialog::onStyleNeeded(SCNotification* notification)
{
    idx_t startPos = (idx_t)callScintilla(SCI_GETENDSTYLED);
    idx_t startLine = (idx_t)callScintilla(SCI_LINEFROMPOSITION, startPos);
    idx_t endPos = (idx_t)notification->position;
    idx_t endLine = (idx_t)callScintilla(SCI_LINEFROMPOSITION, endPos);


    LineDetails lineDetails;
    for(idx_t lineNumber = startLine; lineNumber <= endLine; ++lineNumber)
    {
        lineDetails.lineLength = (size_t)callScintilla(SCI_GETLINE, lineNumber);

        if (lineDetails.lineLength > 0)
        {
            lineDetails.line = new char[lineDetails.lineLength + 1];
            callScintilla(SCI_GETLINE, lineNumber, reinterpret_cast<LPARAM>(lineDetails.line));
            lineDetails.line[lineDetails.lineLength] = '\0';
            lineDetails.errorLevel = EL_UNSET;
            
            
            if (parseLine(&lineDetails))
            {
                startPos = (idx_t)callScintilla(SCI_POSITIONFROMLINE, lineNumber);

                // Check that it's not just a file called '<console>'
                if (strncmp(lineDetails.line + lineDetails.filenameStart, "<console>", lineDetails.filenameEnd - lineDetails.filenameStart))
                {
					int mask, style;
					switch(lineDetails.errorLevel)
					{
						case EL_WARNING:
							mask = 0x04;
							style = 0x04;
							break;

						case EL_ERROR:
							mask = 0x01;
							style = 0x01;
							break;

						case EL_UNSET:
						case EL_INFO:
						default:
							mask = 0x00;
							style = 0x00;
							break;
					}

					if (lineDetails.filenameStart > 0)
					{
						callScintilla(SCI_STARTSTYLING, startPos, mask);
						callScintilla(SCI_SETSTYLING, lineDetails.filenameStart, style);
					}


                    callScintilla(SCI_STARTSTYLING, startPos + lineDetails.filenameStart, mask | 0x02);
                    callScintilla(SCI_SETSTYLING, lineDetails.filenameEnd - lineDetails.filenameStart, style | 0x02);
					
					if (lineDetails.lineLength > lineDetails.filenameEnd)
					{
						callScintilla(SCI_STARTSTYLING, startPos + lineDetails.filenameEnd, mask);
						callScintilla(SCI_SETSTYLING, lineDetails.lineLength - lineDetails.filenameEnd, style);
					}


                }
            }

            delete[] lineDetails.line;
            
        }
    }

    // ensure that everything is set as styled (just move the endStyled variable on to the requested position)
    callScintilla(SCI_STARTSTYLING, notification->position, 0x0);

}
Example #24
0
static void * parseConfig( const char *param, void *_initial_config, int level, const char *name )
{
    CacheConfig *pInitConfig = (CacheConfig *)_initial_config;
    CacheConfig *pConfig = new CacheConfig;
    if (!pConfig)
        return NULL;
    
    pConfig->inherit(pInitConfig);
    if (!param)
        return (void *)pConfig;
    
    long val = parseLine( param, "enableCache", -1, 1, -1 );
    if ( val != -1 )
        pConfig->setConfigBit( CACHE_ENABLED, val );
    val = parseLine( param, "qsCache", -1, 1, -1 );
    if ( val != -1 )
        pConfig->setConfigBit( CACHE_QS_CACHE, val );
    val = parseLine( param, "reqCookieCache", -1, 1, -1 );
    if ( val != -1 )
        pConfig->setConfigBit( CACHE_REQ_COOKIE_CACHE, val );
    val = parseLine( param, "respCookieCache", -1, 1, -1 );
    if ( val != -1 )
        pConfig->setConfigBit( CACHE_RESP_COOKIE_CACHE, val );
    val = parseLine( param, "ignoreReqCacheCtrl", -1, 1, -1 );
    if ( val != -1 )
        pConfig->setConfigBit( CACHE_IGNORE_REQ_CACHE_CTRL_HEADER, val );
    val = parseLine( param, "ignoreRespCacheCtrl", -1, 1, -1 );
    if ( val != -1 )
        pConfig->setConfigBit( CACHE_IGNORE_RESP_CACHE_CTRL_HEADER, val );
    val = parseLine( param, "expireInSeconds", -1, INT_MAX, -1 );
    if ( val != -1 )
    {
        pConfig->setDefaultAge( val );
        pConfig->setConfigBit( CACHE_MAX_AGE_SET, 1 );
    }
    val = parseLine( param, "maxStaleAge", -1, INT_MAX, -1 );
    if ( val != -1 )
    {
        pConfig->setMaxStale( val );
        pConfig->setConfigBit( CACHE_STALE_AGE_SET, 1 );
    }
    val = parseLine( param, "enablePrivateCache", -1, 1, -1 );
    if ( val != -1 )
        pConfig->setConfigBit( CACHE_PRIVATE_ENABLED, val );

    val = parseLine( param, "privateExpireInSeconds", -1, INT_MAX, -1 );
    if ( val != -1 )
    {
        pConfig->setPrivateAge( val );
        pConfig->setConfigBit( CACHE_PRIVATE_AGE_SET, 1 );
    }
    
    //In context level, do not parse and use this parameter
    int valLen = 0;
    const char *p = parseLineStr( param, "storagepath", valLen );
    if (p && valLen > 0)
    {
        char *pBak = new char[valLen + 1];
        strncpy(pBak, p, valLen);
        pBak[valLen] = 0x00;
        p = pBak;
        
        if (level != LSI_CONTEXT_LEVEL)
        {
            char pTmp[max_file_len]  = {0};
            char cachePath[max_file_len]  = {0};
            char defaultCachePath[max_file_len]  = {0};
            
            //check if contains $
            if (strchr(p, '$'))
            {
                int ret = g_api->expand_current_server_varible( level, p, pTmp, max_file_len);
                if (ret >= 0)
                {
                    p = pTmp;
                    valLen = ret;
                }
                else
                {
                    g_api->log(NULL, LSI_LOG_ERROR, "[%s]parseConfig failed to expand_current_server_varible[%s], default will be in use.\n",
                                   ModuleNameString, p);
                    
                    delete []pBak;
                    return (void *)pConfig;
                }
            }
            
            if (p[0] != '/') 
                strcpy(cachePath, g_api->get_server_root());
            strcpy(defaultCachePath, g_api->get_server_root());
            strncat(cachePath, p, valLen);
            strncat(defaultCachePath, CACHEMODULEROOT, strlen(CACHEMODULEROOT));
            
            if (createCachePath(cachePath, 0755) == -1)
            {
                g_api->log(NULL, LSI_LOG_ERROR, "[%s]parseConfig failed to create directory [%s].\n",
                                   ModuleNameString, cachePath);
            }
            else
            {
                matchDirectoryPermissions(defaultCachePath, cachePath);
                pConfig->setStoragePath(p, valLen);
                g_api->log(NULL, LSI_LOG_DEBUG, "[%s]parseConfig setStoragePath [%s] for level %d[name: %s].\n",
                                   ModuleNameString, cachePath, level, name);
            }
        }
        else
            g_api->log( NULL, LSI_LOG_INFO, "[%s]context [%s] shouldn't have 'storagepath' parameter.\n", 
                ModuleNameString, name);

        delete []pBak;
    }
    
    return (void *)pConfig;
}
Example #25
0
void plainconf::parseLine(const char *fileName, int lineNumber,
                          const char *sLine)
{
    const int MAX_NAME_LENGTH = 4096;
    char name[MAX_NAME_LENGTH] = {0};
    char value[MAX_NAME_LENGTH] = {0};
    const char *attr = NULL;

    XmlNode *pNode = NULL;
    XmlNode *pCurNode = (XmlNode *)gModuleList.back();
    const char *p = sLine;
    const char *pEnd = sLine + strlen(sLine);

    bool bNameSet = false;

    for (; p < pEnd; ++p)
    {
        //"{" is a beginning of a block only if it is the last char of a line
        if (*p == '{' && pEnd - p == 1)
        {
            if (strlen(name) > 0)
            {
                const char *pRealname = getRealName(name);

                if (pRealname)
                {
                    pNode = new XmlNode;
                    pNode->init(pRealname, &attr);

                    //Remove space in the end of the value such as "module cache  {", value will be "cache"
                    removeSpace(value, 1);

                    if (strlen(value) > 0)
                        pNode->setValue(value, strlen(value));

                    pCurNode->addChild(pNode->getName(), pNode);
                    gModuleList.push_back(pNode);
                    pCurNode = pNode;
                    clearNameAndValue(name, value);
                    break;
                }
                else
                {
                    logToMem(LOG_LEVEL_ERR,
                             "parseline find block name [%s] is NOT keyword in %s:%d", name, fileName,
                             lineNumber);
                    break;
                }
            }
            else
            {
                logToMem(LOG_LEVEL_ERR,
                         "parseline found '{' without a block name in %s:%d", fileName, lineNumber);
                break;
            }
        }

        else if (*p == '}' && p == sLine)
        {
            if (gModuleList.size() > 1)
            {
                gModuleList.pop_back();
                clearNameAndValue(name, value);

                if (*(p + 1))
                {
                    ++p;
                    trimWhiteSpace(&p);
                    parseLine(fileName, lineNumber, p);
                    break;
                }
            }
            else
            {
                logToMem(LOG_LEVEL_ERR, "parseline found more '}' in %s:%d", fileName,
                         lineNumber);
                clearNameAndValue(name, value);
                break;
            }
        }
        else if ((*p == ' ' || *p == '\t') && value[0] == 0)
        {
            bNameSet = true;
            continue;
        }
        else
        {
            if (!bNameSet)
                strcatchr(name, *p, MAX_NAME_LENGTH);
            else
                strcatchr(value, *p, MAX_NAME_LENGTH);
        }
    }

    if (name[0] != 0)
    {
        const char *pRealname = getRealName(name);

        if (pRealname)
        {
            assert(pNode == NULL);
            pNode = new XmlNode;
            pNode->init(pRealname, &attr);

            if (strlen(value) > 0)
                pNode->setValue(value, strlen(value));

            pCurNode->addChild(pNode->getName(), pNode);
        }
        else
        {
            //There is no special case in server level
            //if (memcmp(pCurNode->getName(), SERVER_ROOT_XML_NAME, sizeof(SERVER_ROOT_XML_NAME) - 1) != 0)
            saveUnknownItems(fileName, lineNumber, pCurNode, name, value);
            //else
            //    logToMem(LOG_LEVEL_ERR, "%s Server level find unknown keyword [%s], ignored.", SERVER_ROOT_XML_NAME, name );
        }
    }
}
Example #26
0
Bool TERMWINDOWMEMBER parseLine(char *line)
    {
    int i, j, k;
    char *words[128];
    char newline[82];
    char done;

    const int count = parse_it(words, line);

    i = -1;

    while (++i < count)
        {
        switch (tolower(*words[i++]))
            {
            case 'd':
                {
                if (debug)
                    {
                    OC.ansiattr = cfg.wattr;
                    cPrintf(getdbmsg(6), words[i], words[i + 1], words[i + 2]);
                    OC.ansiattr = cfg.attr;
                    cPrintf(spc);
                    }
                else
                    {
                    cPrintf(getmsg(433));
                    }

                const protocols *theProt = GetProtocolByKey(words[i][0], TRUE);

                if (!theProt)
                    {
                    return (FALSE);
                    }

                wxrcv(words[i + 1], words[i + 2], theProt);

                i += 2;
                break;
                }

            case 'p':
                {
                if (debug)
                    {
                    OC.ansiattr = cfg.wattr;
                    cPrintf(getdbmsg(7), words[i]);
                    OC.ansiattr = cfg.attr;
                    cPrintf(spc);
                    }
                else
                    {
                    cPrintf(getmsg(433));
                    }

                netpause(atoi(words[i]) * 100);
                break;
                }

            case 'r':
                {
                if (debug)
                    {
                    OC.ansiattr = cfg.wattr;
                    cPrintf(getdbmsg(8), words[i], words[i+1], words[i+2]);
                    OC.ansiattr = cfg.attr;
                    cPrintf(spc);
                    }
                else
                    {
                    cPrintf(getmsg(433));
                    }

                k = atoi(words[i+2]);

                for (done = FALSE, j = 0; j < k && !done; j++)
                    {
                    if (debug)
                        {
                        OC.ansiattr = cfg.wattr;
                        cPrintf(getdbmsg(9), words[i]);
                        OC.ansiattr = cfg.attr;
                        cPrintf(spc);
                        }
                    else
                        {
                        cPrintf(getmsg(433));
                        }

                    if (!wait_for(words[i], node->GetWaitTimeout()))
                        {
                        if (debug)
                            {
                            OC.ansiattr = cfg.wattr;
                            cPrintf(getdbmsg(10), words[i+1]);
                            OC.ansiattr = cfg.attr;
                            cPrintf(spc);
                            }
                        else
                            {
                            cPrintf(getmsg(433));
                            }

                        CommPort->OutString(words[i + 1], node->GetOutputPace());
                        }
                    else
                        {
                        done = TRUE;
                        }
                    }

                i += 2;

                if (!done)
                    {
                    return (FALSE);
                    }

                break;
                }

            case 's':
                {
                if (debug)
                    {
                    OC.ansiattr = cfg.wattr;
                    cPrintf(getdbmsg(10), words[i]);
                    OC.ansiattr = cfg.attr;
                    cPrintf(spc);
                    }
                else
                    {
                    cPrintf(getmsg(433));
                    }

                CommPort->OutString(words[i], node->GetOutputPace());
                break;
                }

            case 'u':
                {
                if (debug)
                    {
                    OC.ansiattr = cfg.wattr;
                    cPrintf(getdbmsg(11), words[i], words[i + 1],
                            words[i + 2]);
                    OC.ansiattr = cfg.attr;
                    cPrintf(spc);
                    }
                else
                    {
                    cPrintf(getmsg(433));
                    }

                const protocols *theProt = GetProtocolByKey(words[i][0],
                        TRUE);

                if (!theProt)
                    {
                    return (FALSE);
                    }

                wxsnd(words[i + 1], words[i + 2], theProt, 0);

                i += 2;
                break;
                }

            case 'w':
                {
                if (debug)
                    {
                    OC.ansiattr = cfg.wattr;
                    cPrintf(getdbmsg(9), words[i]);
                    OC.ansiattr = cfg.attr;
                    cPrintf(spc);
                    }
                else
                    {
                    cPrintf(getmsg(433));
                    }

                if (!wait_for(words[i], node->GetWaitTimeout()))
                    {
                    return (FALSE);
                    }

                break;
                }

            case '!':
                {
                RunApplication(words[i], NULL, TRUE, TRUE);
                break;
                }

            case '@':
                {
                FILE *file;

                if ((file = fopen(words[i], FO_R)) != NULL)
                    {
                    while (fgets(newline, 80, file))
                        {
                        if (!parseLine(newline))
                            {
                            fclose(file);
                            return (FALSE);
                            }
                        }

                    fclose(file);
                    }
                else
                    {
                    return (FALSE);
                    }

                break;
                }

            default:
                {
                OC.ansiattr = (uchar)(cfg.cattr | 128);
                cPrintf(getnetmsg(52), words[i-1], words[i]);
                OC.ansiattr = cfg.attr;
                cPrintf(spc);
                break;
                }
            }
        }

    return (TRUE);
    }