Exemple #1
0
BIGCAST CHUNKgz (gzFile zip, BIGCAST offset, int chunk, char *position, char *extra, char type)
{
  memset (position, 0, chunk);
  char c, *position2 = position;
  char *x;
  int num = 0;
  if (offset == 0)
  	while (offset < 10 * ONE)
  	{
		c = gzgetc (zip);
		if (c == type)
			break;
		offset++;
  	}
  if (extra != NULL)
  {
  	memcpy (position, extra, strlen (extra));
  	position += strlen (extra);
  }
  free (extra);
  while (((c = gzgetc (zip)) != EOF) && (num < chunk))
  {
  	*position = c;
  	position++;
  	num++;
  }
  x = strrstr (position2, "\n@");
  extra=(char *)calloc(1,(position-x+1)*sizeof(char));
  memcpy(x,extra,position-x+1);
  offset+=(position-x+1);
  return offset;
}
Exemple #2
0
static vString* determineVimFileType (const char *const modeline)
{
	/* considerable combinations:
	   --------------------------
	   ... filetype=
	   ... ft= */

	unsigned int i;
	const char* p;

	const char* const filetype_prefix[] = {"filetype=", "ft="};
	vString* const filetype = vStringNew ();

	for (i = 0; i < ARRAY_SIZE(filetype_prefix); i++)
	{
		if ((p = strrstr(modeline, filetype_prefix[i])) == NULL)
			continue;

		p += strlen(filetype_prefix[i]);
		for ( ;  *p != '\0'  &&  isalnum ((int) *p)  ;  ++p)
			vStringPut (filetype, (int) *p);
		vStringTerminate (filetype);
		break;
	}
	return filetype;
}
//从指定位置之上  寻找类定义的
bool AnalyseClassCallRelation::FindClassObjDefine(const char *pObj, char *pPos, char *pMenStart, char *pMenEnd, string &strObjDefine)
{
	//在函数找到对应的类型 
	char *pTemp = pPos; 
	char *pSearch = NULL;
	char cTemp = *pTemp;
	*pTemp = 0; 
	while((pSearch = strrstr(pMenStart, pObj)) != NULL )
	{
		
		char *pWHead = NULL; 
		char *pWTail = NULL; 
		GetWord(pSearch, pMenStart, pMenEnd, pWHead,  pWTail);
		string strCompleteWord =  GetStr(pWHead, pWTail);
		string strObj = pObj; 
		if( GetStr(pWHead, pWTail) == strObj || strCompleteWord == strObj+';' )
		{
			//找到类定义
			strObjDefine = LastWord(pSearch, pMenStart); 
			*pTemp = cTemp;
			return true; 
		}
		*pTemp = cTemp;
		cTemp = *pSearch;
		*pSearch = 0; 
		pTemp = pSearch;  
	}
	*pTemp = cTemp;
	return  false; 
}
Exemple #4
0
_RIBS_INLINE_ int read_data(struct timeout_handler *timeout_handler, int cfd, struct vmbuf *response, size_t ofs) {
    int res = vmbuf_read(response, cfd);
    if (0 > res) {
        close(cfd);
        return -1;
    }
    *vmbuf_wloc(response) = 0;
    char *data, *line;
    /* Keep reading if
     * 1.you don't see a CRLF
     * OR
     * 2.see a dash and CRLF in the current line
     */
    while ((NULL == strstr((data = vmbuf_data_ofs(response, ofs)), CRLF))
           || ((NULL != strchr((line = strrstr(data, CRLF)), '-')) && (NULL != strstr(line, CRLF)))) {
        if (1 == res)
            sendemail_yield(timeout_handler, cfd);
        if (0 >= (res = vmbuf_read(response, cfd))) {
            LOGGER_PERROR("read");
            close(cfd);
            return -1;
        }
    }
    *vmbuf_wloc(response) = 0;
    return 0;
}
Exemple #5
0
int topic_replace_append(User * u, Channel *c, char *newtopic) {
	char topic[1024], buf[1024], *mtopic;
	ChannelInfo *ci = c->ci;

	if (ci->flags & CI_VERBOTEN) {
		notice_lang(ci->bi->nick, u, CHAN_X_FORBIDDEN, ci->name);
		return MOD_STOP;
	}

	if (!my_check_access(u, ci, CA_TOPIC) && ((ci->flags & CI_TOPICLOCK) || !my_check_access(u, ci, CA_OPDEOPME))) {
		notice_lang(ci->bi->nick, u, PERMISSION_DENIED);
		return MOD_STOP;
	}

	memset(topic, 0, 1024);
	if (ci->last_topic) {
		/* Copy topic up to the last append.. */
		mtopic = strrstr(ci->last_topic, (AppendToTopicDel ? AppendToTopicDel : "||"));
		if (mtopic) {
			memset(buf, 0, 1024);
			strncat(buf, ci->last_topic, mtopic - ci->last_topic);

			if (newtopic)
				snprintf(topic, sizeof(topic), "%s%s %s", buf,
						(AppendToTopicDel ? AppendToTopicDel : "||"), newtopic);
			else
				snprintf(topic, sizeof(topic), "%s", buf);
		} else
			snprintf(topic, sizeof(topic), "%s %s %s", ci->last_topic,
					(AppendToTopicDel ? AppendToTopicDel : "||"), newtopic);
	} else if (newtopic)
		strcpy(topic, newtopic);

	ci->last_topic = *topic ? sstrdup(topic) : NULL;
	strscpy(ci->last_topic_setter, u->nick, NICKMAX);
	ci->last_topic_time = time(NULL);

	if (c->topic) free(c->topic);
	c->topic = *topic ? sstrdup(topic) : NULL;
	strscpy(c->topic_setter, u->nick, NICKMAX);

	if (ircd->topictsbackward) {
		c->topic_time = c->topic_time - 1;
	} else {
		c->topic_time = ci->last_topic_time;
	}

	if (is_services_admin(u) && !check_access(u, ci, CA_TOPIC) &&
			((ci->flags & CI_TOPICLOCK) || !check_access(u, ci, CA_OPDEOPME)))
		alog("%s: %s!%s@%s changed topic of %s as services admin.",
			ci->bi->nick, u->nick, u->username, u->host, c->name);

	anope_cmd_topic(ci->bi->nick, c->name, u->nick, topic, c->topic_time);

	return MOD_CONT;
}
Exemple #6
0
int main()
{
	char text[] = "Ahoj svete!";
	char hledame[] = "svet";

	printf("Text:\"%s\"\nHledame:\"%s\"\nVraceny ukazatel:\"%s\"\n", text,hledame,strrstr(text,hledame));


	return 0;
}
Exemple #7
0
int url_simplematch(const char find[], const char hay[]) {

	const u32 wilds = countwilds(find);

	// Easiest path: no wildcards
	if (!wilds) {
		return strcmp(find, hay) == 0;
	}

	const u32 len = strlen(find);
	u32 i, h = 0;

	for (i = 0; i < len; i++) {
		if (find[i] != '*') {
			if (find[i] != hay[h])
				return 0;
			h++;
		} else {
			// If multiple wildcards in a row, skip to the last
			while (find[i+1] == '*') i++;

			if (i >= len - 1)
				return 1;

			// Wildcard, not last
			const char * const ender = strchrnul(&find[i + 1], '*');
			const u32 dist = ender - &find[i + 1];

			char piece[dist + 1];
			memcpy(piece, &find[i + 1], dist);
			piece[dist] = '\0';

			const char * const lastmatch = strrstr(&hay[h], piece);
			if (!lastmatch)
				return 0;

			// Is backtracking required?
			const char * const firstmatch = strstr(&hay[h], piece);

			// The dist check is to make sure this is not a suffix search
			if (firstmatch != lastmatch && dist != len - i - 1) {
				const u32 move = firstmatch - &hay[h];
				h += move;
			} else {
				const u32 move = lastmatch - &hay[h];
				h += move;
			}
		}
	}

	// We ran out of needle but not hay
	if (h != strlen(hay)) return 0;

	return 1;
}
static int pathname_matches_modname(const char *pathname, const char *modname)
{
	int r;
	char name[MODULE_NAME_LEN];
	const char *fname = bb_get_last_path_component_nostrip(pathname);
	const char *suffix = strrstr(fname, ".ko");
	safe_strncpy(name, fname, suffix - fname + 1);
	replace(name, '-', '_');
	r = (strcmp(name, modname) == 0);
	return r;
}
Exemple #9
0
/** Returns the name of a repo, i.e. "/var/lib/darcs/repos/foo/" -> "foo".
 * @param str path to the repo
 * @return pointer to the reponame string
 */
char *reponame(char *str)
{
	char *ret;
	/* drop the / suffix */
	if(str[strlen(str)-1]=='/')
		str[strlen(str)-1]='\0';
	ret = strrstr(str, "/");
	if (ret!=NULL)
		return(ret);
	else
		return(str);
}
Exemple #10
0
static int pathname_matches_modname(const char *pathname, const char *modname)
{
	const char *fname = bb_get_last_path_component_nostrip(pathname);
	const char *suffix = strrstr(fname, ".ko");
//TODO: can do without malloc?
	char *name = xstrndup(fname, suffix - fname);
	int r;
	replace(name, '-', '_');
	r = (strcmp(name, modname) == 0);
	free(name);
	return r;
}
Exemple #11
0
int main()
{
    // 1.
    printf("%s\n", strrstr("Tohle slovo slovo slovo je krasne.", "slovo"));
    printf("%s\n", strrstr("Tohle slovo slovo slovo je krasne.", "slovo s"));
    printf("%s\n", strrstr("Tohle slovo slovo slovo je krasne.", "ohle")); 
    strrstr("Tohle slovo slovo slovo je krasne.", "Nathan"); 
    printf("%s\n", strrstr("To neni jeptiska! Je to podplukovnik matka Tereza!", "podplukovnik")); 
    printf("%s\n", strrstr("To neni jeptiska! Je to podplukovnik matka Tereza!", "ka")); 
    printf("%s\n", strrstr("To neni jeptiska! Je to podplukovnik matka Tereza!", "ka!")); 
    strrstr("To neni jeptiska! Je to podplukovnik matka Tereza!", "Rimmer");
    
    // 2.
    prvek* test = NULL;
    prvek* z = NULL;
    prvek* milion = NULL;
    int i;
    
    test = pridej(test, 5);
    printf("\n%i \n", vrchol(test));
    test = pridej(test, 14);
    printf("%i \n", vrchol(test));
    test = odeber(test);
    printf("%i \n", vrchol(test));
    test = odeber(test);

    for (i = 1; i < 11; i++)
        z = pridej(z, i);
    while (z != NULL) {
        printf("%i ", vrchol(z));
        z = odeber(z);
    }
    
    for (i = 1; i < 1000000; i++)
        milion = pridej(milion, i);
    for (i = 1; i < 1000000 - 1; i++)
        milion = odeber(milion);
    printf("\nmilion: %i\n", vrchol(milion));
    
    // 3.
    char* vstup = "Ahoj svete 23.";
    char* vystup;
    set(vstup, &vystup);
    printf("\n%s\n", vystup);
    
    
    return 0;
}
Exemple #12
0
int main()
{
    // 1. Porovnání textových řetězců
    char *retezec1 = "abcde", *retezec2 = "ahoj";
    if (porovnej(retezec1, retezec2) == -1) printf("slovo \"%s\" je větší než slovo \"%s\"", retezec2, retezec1);
    else if (porovnej(retezec1, retezec2) == 1) printf("slovo \"%s\" je větší než slovo \"%s\"", retezec1, retezec2);
    else printf("slovo \"%s\" je stejně velké jako slovo \"%s\"", retezec1, retezec2);
    
    // 2. Hledání podřetězce zprava
    char *text = "Ahoj svete!";
    char *hledame = "svet";
    printf("\n%s", strrstr(text, hledame));
    
    return 0;
}
Exemple #13
0
static void near assert_msgarea(char *path, word type, word killbyage,
                                word killbynum, word killskip)
{
  HAREA ha;
  char szPath[PATHLEN];
  char szUp[PATHLEN];

  dword dwKillByNum = killbynum ? (dword)killbynum : (dword)-1L;
  dword dwKillSkip = killskip ? (dword)killskip : (dword)-1L;
  dword dwKillByAge = killbyage ? (dword)killbyage : (dword)-1L;


  strcpy(szPath, path);

  /* Make sure that path does not contain a trailing backslash */

  if (strlen(szPath) > 3)
    Strip_Trailing(szPath, PATH_DELIM);

  if ((ha=MsgOpenArea(szPath, MSGAREA_CRIFNEC, type))==NULL)
  {
    char *p;

    strcpy(szUp, szPath);

    if ((p=strrstr(szUp, ":\\/")) != NULL)
      *p=0;

    if (*szUp && !direxist(szUp))
      makedir(szUp);

    if ((ha=MsgOpenArea(szPath, MSGAREA_CRIFNEC, type))==NULL)
    {
      printf("\a\nError creating area %s!\n", path);
      Compiling(-1,NULL,NULL);
      return;
    }
  }

  /* Set the parameters for a Squish area */

  if (type & MSGTYPE_SQUISH)
    SquishSetMaxMsg(ha, dwKillByNum, dwKillSkip, dwKillByAge);

  MsgCloseArea(ha);
}
Exemple #14
0
int String::IndexOfLast(const String &strNeedle) const
{
	MUTEX_LOCK(str_mutex);

#ifdef SCRATCH_NO_UTF8
	const char* sz = strrstr(this->str_szBuffer, strNeedle);
	if (sz != nullptr) {
		return sz - this->str_szBuffer;
	}
	return -1;
#else
	if (strNeedle.Length() == 0) {
		return -1;
	}

	int len = strNeedle.Length();
	int ret = -1;
	int index = 0;
	int findStart = -1;
	int findIndex = 0;

	int cp;
	void* p = this->str_szBuffer;

	while (true) {
		p = utf8codepoint(p, &cp);
		if (cp == 0) {
			break;
		}
		if (strNeedle[findIndex] == cp) {
			if (findIndex == 0) {
				findStart = index;
			}
			findIndex++;
			if (findIndex == len) {
				ret = findStart;
				findIndex = 0;
			}
		}
		index++;
	}

	return ret;
#endif
}
Exemple #15
0
int ascanf_basename ( ASCB_ARGLIST ) 
{ ASCB_FRAME
  ascanf_Function *s1, *s2= NULL;
	set_NaN(*result);
	ascanf_arg_error= 0;
	if( !args || ascanf_arguments< 1 ){
		ascanf_arg_error= 1;
	}
	else{
		if( !(s1= parse_ascanf_address(args[0], 0, "ascanf_basename", (int) ascanf_verbose, NULL )) || 
			(s1->type== _ascanf_procedure || s1->type== _ascanf_function || (!s1->usage && ascanf_verbose) )
		){
			fprintf( StdErr, " (warning: argument is not a valid string)== " );
		}
		if( s1 && s1->usage ){
		  char *bn= basename(s1->usage), *ext= NULL;
		  ascanf_Function *allocated;
			if( ascanf_arguments> 1 && args[1] &&
				(!(s2= parse_ascanf_address(args[1], 0, "ascanf_basename", (int) ascanf_verbose, NULL )) || 
				(s2->type== _ascanf_procedure || s2->type== _ascanf_function || (!s2->usage && ascanf_verbose) ))
			){
				fprintf( StdErr, " (warning: second argument is not a valid string -- ignored)== " );
				s2= NULL;
			}
			if( s2 ){
				if( (ext= strrstr( bn, s2->usage )) ){
					*ext= '\0';
				}
			}
			if( (allocated= Create_Internal_ascanfString( bn, level )) ){
				*result= take_ascanf_address( allocated );
			}
			else{
				fprintf( StdErr, " (error: could not duplicate basename(%s)=\"%s\": %s)== ", s1->name, bn, serror() );
				ascanf_arg_error= True;
				*result= 0;
			}
			if( ext ){
			  /* if ext!=NULL, then also s2!=NULL */
				*ext= s2->usage[0];
			}
		}
	}
	return(!ascanf_arg_error);
}
Exemple #16
0
int squishtest(char *name)
{
  char temp[PATHLEN];

  FILE *sfd;
  FILE *ifd;
  char *p, *s;

  int x;
  
  p=strrchr(name, '.');
  s=strrstr(name, "/\\");

  if (p && (!s || p > s))
    *p='\0';

  strcpy(temp, name);
  strcat(temp, ".sqd");

  if ((sfd=shfopen(temp, "rb", O_RDONLY | O_BINARY))==NULL)
  {
    printf("error opening data file %s for read.\n",temp);
    exit(1);
  }
  
  strcpy(temp, name);
  strcat(temp,".sqi");

  if ((ifd=shfopen(temp, "rb", O_RDONLY | O_BINARY))==NULL)
  {
    printf("error opening index file %s for read.\n",temp);
    exit(1);
  }
  
  x=sqvalidate(name, sfd, ifd);
  
  fclose(ifd);
  fclose(sfd);
  
  return x;
}
Exemple #17
0
char *
strtrim_s (char *str, const char *left, const char *right)
{
  if (left)
    {
      char *p = strstr (str, left);

      if (p)
        strmove (str, p + strlen (left));
    }

  if (right)
    {
      char *p = strrstr (str, right);

      if (p)
        *p = 0;
    }

  return str;
}
SOL_API int
sol_util_get_rootdir(char *out, size_t size)
{
    char progname[PATH_MAX] = { 0 };
    const char *substr;
    int r;

    r = get_libname(progname, sizeof(progname));
    if (r < 0 || r >= (int)sizeof(progname)) {
        r = get_progname(progname, sizeof(progname));
        if (r < 0 || r >= (int)sizeof(progname))
            return r;
    }

    substr = strrstr(progname, PREFIX);
    if (!substr) {
        return -1;
    }

    r = snprintf(out, size, "%.*s/", (int)(strlen(progname) - strlen(substr)), progname);
    return (r < 0 || r >= (int)size) ? -ENOMEM : r;
}
Exemple #19
0
BIGCAST CHUNKer (gzFile zip, BIGCAST offset, int chunk, char *data, char type)
{
  char c;
  char *pos = NULL;
  int length = 0;
  /*in case the file is zipped, move the satrting point to the start of real data*/
  if (offset == 0)
  	while (offset < 10 * ONE)
    	{
  		c = gzgetc (zip);
		if (c == type)
			break;
		offset++;
  	}
  gzseek (zip, offset, SEEK_SET);
  gzread (zip, data, chunk);
  if (data != NULL)
  	length = strlen (data);
  if (length >= chunk)
  {
  	if (type == '@')
	{
		pos = strrstr (data, "\n+");
		pos = move_start_point (pos - 1);
	}
   	else
	{
		pos = strrchr (data, '>') - 1;
	}
  }
  if (pos)
  {
  	offset += (pos - data);
  	memset (pos, 0, strlen (pos));
  }
  if (length < chunk)
  	offset = -1;
  return offset;
}
Exemple #20
0
int search_makelist( search_t *results, char *url )
{
	int i, size = 8192, j = 0;
	char *s, *s1, *s2, *s3;
	conn_t conn[1];
	double t;
	
	memset( conn, 0, sizeof( conn_t ) );
	
	conn->conf = results->conf;
	t = gettime();
	if( !conn_set( conn, url ) )
		return( -1 );
	if( !conn_init( conn ) )
		return( -1 );
	if( !conn_info( conn ) )
		return( -1 );
	
	strcpy( results[0].url, url );
	results[0].speed = 1 + 1000 * ( gettime() - t );
	results[0].size = conn->size;
	
	s = malloc( size );
	
	sprintf( s, "http://www.filesearching.com/cgi-bin/s?q=%s&w=a&l=en&"
		"t=f&e=on&m=%i&o=n&s1=%lld&s2=%lld&x=15&y=15",
		conn->file, results->conf->search_amount,
		conn->size, conn->size );
	
	conn_disconnect( conn );
	memset( conn, 0, sizeof( conn_t ) );
	conn->conf = results->conf;
	
	if( !conn_set( conn, s ) )
	{
		free( s );
		return( 1 );
	}
	if( !conn_setup( conn ) )
	{
		free( s );
		return( 1 );
	}
	if( !conn_exec( conn ) )
	{
		free( s );
		return( 1 );
	}
	
	while( ( i = read( conn->fd, s + j, size - j ) ) > 0 )
	{
		j += i;
		if( j + 10 >= size )
		{
			size *= 2;
			s = realloc( s, size );
			memset( s + size / 2, 0, size / 2 );
		}
	}

	conn_disconnect( conn );
	
	s1 = strstr( s, "<pre class=list" );
	s1 = strchr( s1, '\n' ) + 1;
	if( strstr( s1, "</pre>" ) == NULL )
	{
		/* Incomplete list					*/
		free( s );
		return( 1 );
	}
	for( i = 1; strncmp( s1, "</pre>", 6 ) && i < results->conf->search_amount && *s1; i ++ )
	{
		s3 = strchr( s1, '\n' ); *s3 = 0;
		s2 = strrstr( s1, "<a href=" ) + 8;
		*s3 = '\n';
		s3 = strchr( s2, ' ' ); *s3 = 0;
		if( strcmp( results[0].url, s2 ) )
		{
			strncpy( results[i].url, s2, MAX_STRING );
			results[i].size = results[0].size;
			results[i].conf = results->conf;
		}
		else
		{
			/* The original URL might show up		*/
			i --;
		}
		for( s1 = s3; *s1 != '\n'; s1 ++ );
		s1 ++;
	}
	
	free( s );
	
	return( i );
}
Exemple #21
0
//replaces all strings named by search with strings named by replace in dest
int strrpl(char **dest, char *search, char *replace, int mode)
{
    char *loc;
    char *temp;
    char *orig;
    char *result;
    int search_len, repl_len, diff;
    int size;
    int count;

    // do nothing if there is not at least one string of "search" in "*dest"
    if(strstr(*dest, search) == NULL)
        return -1;

    search_len = strlen(search);
    repl_len = strlen(replace);
    diff = repl_len - search_len;
    

    //how many strings do we need to replace?
    if(mode == MODE_ALL)
    {
        temp = *dest;
        for(count = 0; (temp = strstr(temp, search)); count++)
            temp += search_len;

    }
    else
        count = 1;


    //length of the new string
    size = strlen(*dest) + (diff*count);

    temp = strdup(*dest);
    orig = temp;

    result = (char*)malloc(size*sizeof(char) +1);
    if(!result)
    {
        free(orig);
        return -1;
    }
    memset(result, 0, size);

    //build the new string
    switch(mode)
    {
        case MODE_ALL:
            while((loc = strstr(temp, search))) 
            {
                strncat(result, temp, loc - temp);
                strcat(result, replace);
                temp = loc + strlen(search);
            }
            //append remaininc characaters (if any)
            if(strlen(temp) > 0)
                strcat(result, temp);
            break;

        case MODE_FIRST:
            loc = strstr(temp, search);
            strncat(result, temp, loc - temp);
            strcat(result, replace);

            temp = loc + strlen(search);
            //append remaining characters 
            if(strlen(temp) > 0)
                strcat(result, temp);
            break;
        case MODE_LAST:
            loc = strrstr(temp, search);
            strncat(result, temp, loc-temp);
            strcat(result, replace);
            
            temp = loc + strlen(search);
            //append remaininc characaters (if any)
            if(strlen(temp) > 0)
                strcat(result, temp);
            
            break;
        default:
            return -1;
    }


    *dest = (char *)realloc(*dest, size*sizeof(char) +1);
    if(!*dest)
    {
        free(result);
        free(orig);
        return -1;
    }

    //save the new string back to orig position in memory
    strcpy(*dest, result);

    free(orig);
    free(result);

    return 0;
}
Exemple #22
0
EAPI Ecore_Exe *
ecore_exe_pipe_run(const char     *exe_cmd,
                   Ecore_Exe_Flags flags,
                   const void     *data)
{
   STARTUPINFO si;
   PROCESS_INFORMATION pi;
   Ecore_Exe_Event_Add *e;
   Ecore_Exe *exe;
   char *ret = NULL;

   exe = calloc(1, sizeof(Ecore_Exe));
   if (!exe)
     return NULL;

   if ((flags & ECORE_EXE_PIPE_AUTO) && (!(flags & ECORE_EXE_PIPE_ERROR))
       && (!(flags & ECORE_EXE_PIPE_READ)))
     /* We need something to auto pipe. */
     flags |= ECORE_EXE_PIPE_READ | ECORE_EXE_PIPE_ERROR;

   exe->flags = flags;
   if (exe->flags & ECORE_EXE_PIPE_READ)
     if (!_ecore_exe_win32_pipes_set(exe))
       goto free_exe;

   if (exe->flags & ECORE_EXE_PIPE_WRITE)
     if (!_ecore_exe_win32_pipes_set(exe))
       goto close_pipes;

   if (exe->flags & ECORE_EXE_PIPE_ERROR)
     if (!_ecore_exe_win32_pipes_set(exe))
       goto close_pipes;

   if ((exe->flags & ECORE_EXE_USE_SH) ||
       ((ret = strrstr(exe_cmd, ".bat")) && (ret[4] == '\0')))
     {
        char buf[PATH_MAX];
        snprintf(buf, PATH_MAX, "cmd.exe /c %s", exe_cmd);
        exe->cmd = strdup(buf);
     }
   else
     exe->cmd = strdup(exe_cmd);

   if (!exe->cmd)
     goto close_pipes;

   ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));

   ZeroMemory(&si, sizeof(STARTUPINFO));
   si.cb = sizeof(STARTUPINFO);
   si.hStdOutput = exe->pipe_read.child_pipe_x;
   si.hStdInput = exe->pipe_write.child_pipe;
   si.hStdError = exe->pipe_error.child_pipe_x;
   si.dwFlags |= STARTF_USESTDHANDLES;

   /* FIXME: gerer la priorite */

   if (!CreateProcess(NULL, exe->cmd, NULL, NULL, EINA_TRUE,
                      run_pri | CREATE_SUSPENDED, NULL, NULL, &si, &pi))
     goto free_exe_cmd;

   /* be sure that the child process is running */
   /* FIXME: This does not work if the child is an EFL-based app */
   /* if (WaitForInputIdle(pi.hProcess, INFINITE) == WAIT_FAILED) */
   /*   goto free_exe_cmd; */

   ECORE_MAGIC_SET(exe, ECORE_MAGIC_EXE);
   exe->process = pi.hProcess;
   exe->process_thread = pi.hThread;
   exe->process_id = pi.dwProcessId;
   exe->thread_id = pi.dwThreadId;
   exe->data = (void *)data;

   if (!(exe->process2 = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_SUSPEND_RESUME | PROCESS_TERMINATE | SYNCHRONIZE,
                                     EINA_FALSE, pi.dwProcessId)))
     goto close_thread;

   exe->h_close = ecore_main_win32_handler_add(exe->process2, _ecore_exe_close_cb, exe);
   if (!exe->h_close) goto close_process2;

   if (ResumeThread(exe->process_thread) == ((DWORD)-1))
     goto close_process2;

   exes = (Ecore_Exe *)eina_inlist_append(EINA_INLIST_GET(exes), EINA_INLIST_GET(exe));

   e = (Ecore_Exe_Event_Add *)calloc(1, sizeof(Ecore_Exe_Event_Add));
   if (!e) goto delete_h_close;

   e->exe = exe;
   ecore_event_add(ECORE_EXE_EVENT_ADD, e,
                   _ecore_exe_event_add_free, NULL);

   return exe;

delete_h_close:
   ecore_main_win32_handler_del(exe->h_close);
close_process2:
   CloseHandle(exe->process2);
close_thread:
   CloseHandle(exe->process_thread);
   CloseHandle(exe->process);
free_exe_cmd:
   free(exe->cmd);
close_pipes:
   _ecore_exe_win32_pipes_close(exe);
free_exe:
   free(exe);
   return NULL;
}
Exemple #23
0
int ascanf_strrstr ( ASCB_ARGLIST ) 
{ ASCB_FRAME_SHORT
  ascanf_Function *s1, *s2, *af;
  static ascanf_Function AF= {NULL};
  static char *AFname= "StrRStr-Static-StringPointer";
	af= &AF;
	if( AF.name ){
	  double oa= af->own_address;
		xfree(af->usage);
		memset( af, 0, sizeof(ascanf_Function) );
		af->own_address= oa;
	}
	else{
		af->usage= NULL;
		af->type= _ascanf_variable;
		af->is_address= af->take_address= True;
		af->is_usage= af->take_usage= True;
		af->internal= True;
		af->name= AFname;
		take_ascanf_address(af);
	}
	af->name= AFname;
	af->type= _ascanf_variable;
	af->is_address= af->take_address= True;
	af->is_usage= af->take_usage= True;
	af->internal= True;

	set_NaN(*result);
	ascanf_arg_error= 0;
	if( !args || ascanf_arguments< 2 ){
		ascanf_arg_error= 1;
	}
	else{
		if( !(s1= parse_ascanf_address(args[0], 0, "ascanf_strrstr", (int) ascanf_verbose, NULL )) || 
			(s1->type== _ascanf_procedure || s1->type== _ascanf_function || !s1->usage)
		){
			if( s1 ){
				fprintf( StdErr, " (warning: 1st argument [%s=%s,\"%s\"] is not a valid string)== ",
					s1->name, ad2str( s1->value, d3str_format, 0), (s1->usage)? s1->usage : "<NULL>"
				);
			}
			else{
				fprintf( StdErr, " (warning: 1st argument is NULL)== " );
			}
		}
		if( !(s2= parse_ascanf_address(args[1], 0, "ascanf_strrstr", (int) ascanf_verbose, NULL )) || 
			(s2->type== _ascanf_procedure || s2->type== _ascanf_function || !s2->usage)
		){
			if( s2 ){
				fprintf( StdErr, " (warning: 2nd argument [%s=%s,\"%s\"] is not a valid string)== ",
					s2->name, ad2str( s2->value, d3str_format, 0), (s2->usage)? s2->usage : "<NULL>"
				);
			}
			else{
				fprintf( StdErr, " (warning: 2nd argument is NULL)== " );
			}
		}
		if( ascanf_SyntaxCheck ){
			  /* When compiling/ checking syntax, we *must* return a safe pointer of the correct type.
			   \ Otherwise, printf[] might complain. NB: this means that the SyntaxCheck field must be
			   \ set in this function's entry in the function table!
			   */
			*result= af->own_address;
		}
		else{
			*result= 0;
			if( s1 && s2 && s1->usage && s2->usage ){
			  char *c= strrstr( s1->usage, s2->usage );
				if( c ){
					xfree( af->usage );
					af->usage= strdup( c );
					*result= af->own_address;
				}
			}
		}
	}
	return(!ascanf_arg_error);
}
Exemple #24
0
void split_recording_timer(void *initial_call)
{
    int zero = 0;
    char *insert_pos;
    char *path;
    char *ext;
    char file_num_str[10];
    static int file_num;
    struct tm *local_time;
    const time_t t = time(NULL);

    if(*((int*)initial_call) == 1)
        file_num = 2;

    // Values < 0 are not allowed
    if(fl_g->input_rec_split_time->value() < 0)
    {
        fl_g->input_rec_split_time->value(0);
        return;
    }

    path = strdup(cfg.rec.path);
    ext = util_get_file_extension(cfg.rec.filename);
    if(ext == NULL)
    {
        print_info("Could not find a file extension in current filename\n"
                "Automatic file splitting is deactivated", 0);
        free(path);
        return;
    }


    snprintf(file_num_str, sizeof(file_num_str), "-%d", file_num);

    insert_pos = strrstr(path, ext);
    strinsrt(&path, file_num_str, insert_pos-1);


    if((next_fd = fl_fopen(path, "rb")) != NULL)
    {
        print_info("Next file ", 0);
        print_info(path, 0);
        print_info("already exists\nbutt keeps recording to current file", 0);
        fclose(next_fd);
        free(path);
        return;
    }

    if((next_fd = fl_fopen(path, "wb")) == NULL)
    {
        fl_alert("Could not open:\n%s", path);
        free(path);
        return;
    }

    print_info("Recording to:", 0);
    print_info(path, 0);

    file_num++;


    next_file = 1;
    free(path);

    local_time = localtime(&t);

    // Make sure that the 60 minutes boundary is not violated in case sync_to_hour == 1
    if((cfg.rec.sync_to_hour == 1) && ((local_time->tm_min + cfg.rec.split_time) > 60))
        Fl::repeat_timeout(60*(60 - local_time->tm_min), &split_recording_timer, &zero);
    else
        Fl::repeat_timeout(60*cfg.rec.split_time, &split_recording_timer, &zero);

}
Exemple #25
0
static boolean loadPathKind (xcmdPath *const path, char* line, char *args[])
{
	const char* backup = line;
	char* off;
	vString *desc;
	kindOption *kind;

	if (line[0] == '\0')
		return FALSE;
	else if (!isblank(line[1]))
	{
		error (WARNING, "[%s] a space after letter is not found in kind description line: %s", args[0], backup);
		return FALSE;
	}

	path->kinds = xRealloc (path->kinds, path->n_kinds + 1, kindOption);
	kind = &path->kinds [path->n_kinds];
	memset (kind, 0, sizeof (*kind));
	kind->enabled = TRUE;
	kind->letter = line[0];
	kind->name = NULL;
	kind->description = NULL;
	kind->referenceOnly = FALSE;
	kind->nRoles = 0;
	kind->roles = NULL;

	verbose ("	kind letter: <%c>\n", kind->letter);

	for (line++; isblank(*line); line++)
		;		/* do nothing */

	if (*line == '\0')
	{
		error (WARNING, "[%s] unexpectedly a kind description line is terminated: %s",
		       args[0], backup);
		return FALSE;
	}

	Assert (!isblank (*line));

	off = strrstr(line, "[off]");
	if (off == line)
	{
		error (WARNING, "[%s] [off] is given but no kind description is found: %s",
		       args[0], backup);
		return FALSE;
	}
	else if (off)
	{
		if (!isblank (*(off - 1)))
		{
			error (WARNING, "[%s] a whitespace must precede [off] flag: %s",
			       args[0], backup);
			return FALSE;
		}
		kind->enabled = FALSE;
		*off = '\0';
	}
	desc = vStringNewInit (line);
	vStringStripTrailing (desc);

	Assert (vStringLength (desc) > 0);

	kind->description = vStringDeleteUnwrap (desc);

	/* TODO: This conversion should be part of protocol. */
	{
	  char *tmp = eStrdup (kind->description);
	  char *c;
	  for (c = tmp; *c != '\0'; c++)
	    {
	      if (*c == ' ' || *c == '\t')
		*c = '_';
	    }
	  kind->name = tmp;
	}

	path->n_kinds += 1;
	return TRUE;
}
Exemple #26
0
int main(const int argc, const char **argv)
{
        int html    = false;
        int verbose = false;

        int i = 0;

        if (argc > 1) {
                for (i = 1; i < argc; ++i) {
                        if (strcmp(argv[i], "-l") == 0 ||  strcmp(argv[i], "--html") == 0) {
                                html = true;
                        } else if (strcmp(argv[i], "-V") == 0 || strcmp(argv[i], "--verbose") == 0) {
                                verbose = true;
                        } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
                                help();
                        } else if (strcmp(argv[i], "-v") == 0 || strcmp(argv[i], "--version") == 0) {
                                version();
                        }
                }
        } else {
                help();
        }

        MODE mode = MODE_UNK;

        int in_match    = false;
        int escaped     = false;
        int html_script = false;

        int matches = 0;
        int delta   = 0;
        int line_no = 0;

        char *c   = NULL;
        char *pos = NULL;

        char line[MAX_LINE+1];
        char tag[256];
        char tag_temp[sizeof(tag)];
        char tag_srch[sizeof(tag)+2];
        char mtype[sizeof(tag)];
        char attribute[sizeof(tag)];
        char attribute_temp[sizeof(attribute)];
        char location[MAX_LINE];
        char location_temp[MAX_LINE];

        *line           =
        *tag            =
        *tag_temp       =
        *mtype          =
        *attribute      =
        *attribute_temp =
        *location       =
        *location_temp  =
            '\0';

        char last_char = '\0';

        for (LOCN_SEARCH(location); fgets(line, MAX_LINE, stdin) != NULL;) {
                ++line_no;
                c = line;
                last_char = '\0';
                while (*c != '\0') {
                        switch (*c) {
                                case '\\':
                                        escaped = true;
                                        ++c;
                                        continue;
                                        break;
                                case ' ':
                                        if (last_char == ' ') {
                                                ++c;
                                                continue;
                                        }
                                        break;
                                case '\n':
                                case '\r':
                                case '\t':
                                        *c = ' ';
                                        break;
                        }

                        if (escaped && in_match) {
                                fputc(*c, stdout);
                        } else {
                                switch (mode) {
                                        case MODE_UNK:
                                                if (*c == '<') {
                                                        MODE_CHANGE(MODE_TAG);
                                                        TAG_RESET();
                                                        break;
                                                } else if (*c == '>') {
                                                        XML_WARNING("Character is not valid");
                                                        if (in_match) {
                                                                fputc(*c, stdout);
                                                        }
                                                } else if (in_match) {
                                                        fputc(*c, stdout);
                                                }
                                                break;

                                        case MODE_TAG:
                                                in_match = false;

                                                if (validNameChar(c)) {
                                                        /* Acceptable characters for tags */
                                                        strchrcat(tag, *c);
                                                } else if (*c == '<') {
                                                        XML_INVALID("New tag is starting within existing tag");
                                                } else if (*c == '>') {
                                                        sprintf(tag_srch, ">%s>", tag);
                                                        if (*tag == '\0') {
                                                                XML_INVALID("Tag is of length zero");
                                                        } else if ((c-line > 1 && *(c-1) == '/') || (html && strstr(HTML_SELFCLOSE, tag_srch) != NULL)) {
                                                                /* Self closing tag */
                                                                sprintf(location_temp, "%s/%s", location, tag);
                                                                LOCN_SEARCH(location_temp);
                                                                MODE_CHANGE(MODE_UNK);
                                                                TAG_RESET();
                                                                in_match = false;

                                                                #ifdef DEBUG
                                                                        fprintf(stderr, "DEBUG: %d,%d\tTag SelfClose: \"%s\"\t\tLocation: \"%s\"\n", line_no, c-line+1, tag, location);
                                                                #endif
                                                        } else {
                                                                pos = strrchr(location, '/');
                                                                /* Compensate for HTML4's block rules */
                                                                if (html && strstr(HTML_BLOCK_LEVEL, tag_srch) != NULL) {
                                                                        if (pos != NULL) {
                                                                                sprintf(tag_srch, ">%s>", pos+1);
                                                                                if (strstr(HTML_INLINE, tag_srch) != NULL) {
                                                                                        /* Block level items cannot start within inline elements */
                                                                                        #ifdef DEBUG
                                                                                                fprintf(stderr, "DEBUG: %d,%d block level elements (%s) cannot start within inline elements (%s)", line_no, c-line+1, tag, pos+1);
                                                                                        #endif
                                                                                        *pos = '\0';
                                                                                } else if (strstr(HTML_EITHER, tag_srch) != NULL) {
                                                                                        strcpy(location_temp, location);
                                                                                        pos = strrchr(location_temp, '/');
                                                                                        if (pos != NULL) {
                                                                                                *pos = '\0';
                                                                                                pos = strrchr(location_temp, '/');
                                                                                                sprintf(tag_srch, ">%s>", pos+1);
                                                                                                if (strstr(HTML_INLINE, tag_srch) != NULL) {
                                                                                                        /* Block level items cannot start within inline elements (and whilst the parent is either, it started inside an inline element and is therefore classed as inline) */
                                                                                                        pos = strrchr(location, '/');
                                                                                                        #ifdef DEBUG
                                                                                                                fprintf(stderr, "DEBUG: %d,%d block level elements (%s) cannot start within inline elements (%s)", line_no, c-line+1, tag, pos+1);
                                                                                                        #endif
                                                                                                        *pos = '\0';
                                                                                                }
                                                                                        }
                                                                                }
                                                                        }
                                                                }

                                                                if (html && pos != NULL && strcmp(pos+1, "script") == 0) {
                                                                        #ifdef DEBUG
                                                                                fprintf(stderr, "DEBUG: Entering HTML Script mode.\n");
                                                                        #endif
                                                                        html_script = true;
                                                                } else if (!html || !html_script) {
                                                                        sprintf(tag_srch, ">%s>", tag);
                                                                        if (html && strstr(HTML_RESTARTING, tag_srch) != NULL && strcmp(pos+1, tag) == 0) {
                                                                                /* Do nothing -- we don't want nesting of <li> et al */
                                                                        } else {
                                                                                /* update location */
                                                                                strcat(location, "/");
                                                                                strcat(location, tag);
                                                                        }
                                                                        LOCN_SEARCH(location);
                                                                        MODE_CHANGE(MODE_UNK);
                                                                        #ifdef DEBUG
                                                                                fprintf(stderr, "DEBUG: %d,%d\tTag Open: \"%s\"\t\tLocation: \"%s\"\n", line_no, c-line+1, tag, location);
                                                                        #endif
                                                                }
                                                                TAG_RESET();
                                                        }
                                                } else if (*c == '/' && delta == 1) {
                                                        MODE_CHANGE(MODE_TAG_END);
                                                } else if (html && html_script) {
                                                        MODE_CHANGE(MODE_UNK);
                                                } else if (*c == '?' && delta == 1) {
                                                        MODE_CHANGE(MODE_TAG_XML_HEAD);
                                                } else if (*c == '!' && delta == 1) {
                                                        MODE_CHANGE(MODE_TAG_COMMENT);
                                                } else if (delta == 0) {
                                                        XML_WARNING("Invalid tag name character");
                                                        if (in_match) {
                                                                fputc('<', stdout);
                                                        }
                                                } else {
                                                        MODE_CHANGE(MODE_ATTR);
                                                }
                                                break;

                                        case MODE_ATTR:
                                                if (validNameChar(c)) {
                                                        /* Acceptable characters for attrs */
                                                        strchrcat(attribute, *c);
                                                } else if (*c == '/') {
                                                        MODE_CHANGE(MODE_TAG);
                                                } else if (*c == '>') {
                                                        MODE_CHANGE(MODE_TAG);
                                                        continue; /* hop */
                                                } else if (*attribute != '\0') {
                                                        MODE_CHANGE(MODE_ATTR_PRE_E);
                                                        continue; /* hop */
                                                }
                                                break;

                                        case MODE_ATTR_PRE_E:
                                                if (*c == ' ') {
                                                        /* Do nothing */
                                                } else if (*c == '=') {
                                                        MODE_CHANGE(MODE_ATTR_POST_E);
                                                } else {
                                                        XML_INVALID("Unexpected character, expecting equals sign");
                                                }
                                                break;

                                        case MODE_ATTR_POST_E:
                                                if (*c == ' ') {
                                                        /* Do nothing */
                                                } else {
                                                        if (*c == '\'') {
                                                                MODE_CHANGE(MODE_ATTR_VAL_SQ);
                                                        } else if (*c == '"') {
                                                                MODE_CHANGE(MODE_ATTR_VAL_DQ);
                                                        } else {
                                                                MODE_CHANGE(MODE_ATTR_VAL);
                                                        }

                                                        sprintf(location_temp, "%s/%s@%s", location, tag, attribute);
                                                        LOCN_SEARCH(location_temp);

                                                        #ifdef DEBUG
                                                                fprintf(stderr, "DEBUG: %d,%d\tAttribute: \"%s\"\t\tLocation: \"%s\"\n", line_no, c-line+1, attribute, location_temp);
                                                        #endif
                                                }
                                                break;

                                        case MODE_ATTR_VAL:
                                                if (*c == '/') {
                                                        ATTR_RESET();
                                                        MODE_CHANGE(MODE_TAG);
                                                } else if (*c == '>') {
                                                        ATTR_RESET();
                                                        MODE_CHANGE(MODE_TAG);
                                                        continue; /* hop */
                                                } else if (*c == ' ') {
                                                        ATTR_RESET();
                                                        MODE_CHANGE(MODE_ATTR);
                                                } else {
                                                        if (in_match) {
                                                                fputc(*c, stdout);
                                                        }
                                                }
                                                break;

                                        case MODE_ATTR_VAL_SQ:
                                                if (*c == '\'') {
                                                        ATTR_RESET();
                                                        MODE_CHANGE(MODE_ATTR);
                                                } else {
                                                        if (in_match) {
                                                                fputc(*c, stdout);
                                                        }
                                                }
                                                break;

                                        case MODE_ATTR_VAL_DQ:
                                                if (*c == '"') {
                                                        ATTR_RESET();
                                                        MODE_CHANGE(MODE_ATTR);
                                                } else {
                                                        if (in_match) {
                                                                fputc(*c, stdout);
                                                        }
                                                }
                                                break;

                                        case MODE_TAG_END:
                                                if (validNameChar(c)) {
                                                        /* Acceptable characters for tags */
                                                        strchrcat(tag, *c);
                                                } else if (*c == '<') {
                                                        XML_INVALID("New tag is starting within existing tag");
                                                } else if (*c == '>') {
                                                        pos = strrchr(location, '/');
                                                        if(pos == NULL) {
                                                                XML_INVALID("Closing of tag \"%s\" before any tags have opened", tag);
                                                        } else if (strcmp(pos+1, tag) == 0) {
                                                                if (html && strcmp(pos+1, "script") == 0) {
                                                                        #ifdef DEBUG
                                                                                fprintf(stderr, "DEBUG: Leaving HTML Script mode.\n");
                                                                        #endif
                                                                        html_script = false;
                                                                }

                                                                *pos = '\0';
                                                                LOCN_SEARCH(location);

                                                                #ifdef DEBUG
                                                                        fprintf(stderr, "DEBUG: %d,%d\tTag Close: \"%s\"\t\tLocation: \"%s\"\n", line_no, c-line+1, tag, location);
                                                                #endif
                                                        } else {
                                                                XML_INVALID("Closing of incorrect tag encountered (expecting \"%s\", got \"%s\")", pos+1, tag);
                                                                #ifdef DEBUG
                                                                        if (html && strcmp(pos+1, "script") != 0) fprintf(stderr, "Suggestion: It may be worth adding the tag \"%s\" to the list of self closing tags\n", pos+1);
                                                                #endif
                                                                /* Search backwards through location and terminate the previous occurrance since some shitfuck clearly screwed up, then LOCN_SEARCH() */
                                                                sprintf(tag_srch, "/%s/", tag);
                                                                pos = strrstr(location, tag_srch);
                                                                if (pos != NULL) {
                                                                        locationSlice(pos);
                                                                        LOCN_SEARCH(location);
                                                                }
                                                        }
                                                        MODE_CHANGE(MODE_UNK);
                                                } else {
                                                        XML_INVALID("Properties detected in ending tag");
                                                }
                                                break;

                                        case MODE_TAG_XML_HEAD:
                                                if (*c == '>') {
                                                        MODE_CHANGE(MODE_UNK);
                                                }
                                                break;

                                        case MODE_TAG_COMMENT:
                                                if (delta == 2 && *c == '[') {
                                                        MODE_CHANGE(MODE_TAG_MARKED);
                                                } else if ((delta == 1 || delta == 2) && *c != '-') {
                                                        MODE_CHANGE(MODE_TAG_FA);
                                                } else if (*c == '>' && c-line > 1 && *(c-2) == '-' && *(c-1) == '-') {
                                                        MODE_CHANGE(MODE_UNK);
                                                }
                                                break;

                                        case MODE_TAG_FA:
                                                if (*c == '>') {
                                                        MODE_CHANGE(MODE_UNK);
                                                }
                                                break;

                                        case MODE_TAG_MARKED:
                                                if (validNameChar(c)) {
                                                        MODE_CHANGE(MODE_TAG_M_TYPE);
                                                        continue; /* hop */
                                                }
                                                break;

                                        case MODE_TAG_M_TYPE:
                                                if (validNameChar(c)) {
                                                        /* Acceptable characters for tags */
                                                        strchrcat(mtype, *c);
                                                } else if (strcmp(mtype, "cdata") == 0) {
                                                        MTYPE_RESET();
                                                        MODE_CHANGE(MODE_CDATA);
                                                        continue; /* hop */
                                                } else {
                                                        MTYPE_RESET();
                                                        MODE_CHANGE(MODE_TAG_M_CONTENT);
                                                }
                                                break;

                                        case MODE_TAG_M_CONTENT:
                                                if (*c == '>' && c-line > 0 && *c == ']') {
                                                        MODE_CHANGE(MODE_UNK);
                                                }
                                                break;

                                        case MODE_CDATA:
                                                if (*c == '[') {
                                                        MODE_CHANGE(MODE_CDATA_CONTENT);
                                                        LOCN_SEARCH(location);
                                                } else {
                                                        XML_INVALID("Invalid CDATA, expecting '['");
                                                }
                                                break;

                                        case MODE_CDATA_CONTENT:
                                                if (*c == ']') {
                                                        MODE_CHANGE(MODE_CDATA_PE);
                                                } else  if (*c == '>' && c-line > 1 && *(c-1) == ']' && *(c-2) == ']') {
                                                        MODE_CHANGE(MODE_UNK);
                                                } else if (in_match) {
                                                        fputc(*c, stdout);
                                                }
                                                break;

                                        case MODE_CDATA_PE:
                                                if (*c == ']') {
                                                        MODE_CHANGE(MODE_TAG_FA);
                                                } else {
                                                        if (in_match) {
                                                                fputc(*c, stdout);
                                                        }
                                                        MODE_CHANGE(MODE_CDATA_CONTENT);
                                                }
                                                break;

                                        default:
                                                fprintf(stderr, "%s:%d Error: An unknown mode was encountered at line %d, character %d ('%c').\n",
                                                        __FILE__, __LINE__, line_no, c-line+1, *c);
                                                exit (1);
                                                break;
                                }
                        }
                        last_char = *c;
                        ++c;
                        ++delta;
                        escaped = false;
                }
        }

        if (*location != '\0') {
                XML_INVALID("Input ended early; location still judged as \"%s\"", location);
        }

        if (matches > 0) fputc('\n', stdout);
        return 0;
}
Exemple #27
0
/* See documentation in header file. */
int ini_parse_file (FILE * file, const struct IniConfig * config, void * user)
{
	/* Uses a fair bit of stack (use heap instead if you need to) */
	char * line;

	char section[MAX_SECTION] = "";
	char prev_name[MAX_NAME] = "";

	char * start;
	char * end;
	char * name;
	char * value;
	char delim = config->delim;
	int lineno = 0;
	int error = 0;

	line = (char *)malloc (INI_MAX_LINE);

	ELEKTRA_LOG_DEBUG ("Allocated memory for line");

	if (!line)
	{
		return -2;
	}

	/* Scan through file line by line */
	while (fgets (line, INI_MAX_LINE, file) != NULL)
	{
		lineno++;
		ELEKTRA_LOG_DEBUG ("Read line %d with content “%s”", lineno, line);

		start = line;
#if INI_ALLOW_BOM
		if (lineno == 1 && (unsigned char)start[0] == 0xEF && (unsigned char)start[1] == 0xBB && (unsigned char)start[2] == 0xBF)
		{
			start += 3;
			config->bomHandler (user, 1);
		}
		else
		{
			config->bomHandler (user, 0);
		}
#endif
		if (*start == '\n')
		{
			if (!config->commentHandler (user, "") && !error) error = lineno;
			continue;
		}
		start = lskip (line);
		if (*start == '\0')
		{
			if (!config->commentHandler (user, "") && !error) error = lineno;
			continue;
		}
		if (isContinuation (line, config) && config->supportMultiline && *prev_name)
		{
			start = line + strlen (config->continuationString);
			if (*start == '"') ++start;
			end = line + (strlen (line) - 1);
			while ((*end != '"') && (!isprint (*end)) && (end > start))
			{
				if (*end == '\n') *end = '\0';
				--end;
			}
			if (*end == '"') *end = '\0';

			if (!config->keyHandler (user, section, prev_name, start, 1) && !error) error = lineno;
		}
		else if (isSection (line))
		{
			ELEKTRA_LOG_DEBUG ("Line contains a section");
			end = line + (strlen (line) - 1);
			while (end > start)
			{
				if (*end == ']') break;
				--end;
			}
			++start;
			if (*end == ']')
			{
				*end = '\0';
				strncpy0 (section, start, sizeof (section));
				*prev_name = '\0';
				ELEKTRA_LOG_DEBUG ("Found section “%s”", section);

				size_t numberBackslashes = 0;
				for (char * endSection = section + strlen (section) - 1; endSection >= section && *endSection == '\\';
				     endSection--)
				{
					numberBackslashes++;
				}
				if (numberBackslashes % 2 != 0)
				{
					ELEKTRA_LOG_WARNING ("Found uneven number of backlashes at end of section");
					error = lineno;
					break;
				}

				if (!config->sectionHandler (user, section) && !error) error = lineno;
			}
			else
			{
				end = line + (strlen (line) - 1);
				if (*end == '\n')
				{
					strncpy0 (section, start, sizeof (section));
					while (fgets (line, INI_MAX_LINE, file))
					{
						end = line + (strlen (line) - 1);
						while ((end > line) && *end != ']')
							--end;
						if (*end == ']')
						{
							*end = '\0';
							strncpy0 (section + strlen (section), line, sizeof (section) - strlen (section));
							*prev_name = '\0';
							if (!config->sectionHandler (user, section) && !error) error = lineno;
							break;
						}
						else
						{
							strncpy0 (section + strlen (section), line, sizeof (section) - strlen (section));
						}
					}
				}
				else
				{
					error = lineno;
				}
			}
		}
		else if (isComment (line))
		{
			start = line;
			end = line + (strlen (line) - 1);
			if (*end == '\n') *end = '\0';
			if (!config->commentHandler (user, start) && !error) error = lineno;
		}
		else
		{
			ELEKTRA_LOG_DEBUG ("Line contains a key");

			char * ptr = start;
			unsigned int assign = 0;
			ELEKTRA_LOG_DEBUG ("Search for delimiter “%c”", delim);
			while (*ptr)
			{
				if (*ptr == delim)
				{
					++assign;
				}
				++ptr;
			}

			if (assign == 1)
			{
				ELEKTRA_LOG_DEBUG ("Found exactly one delimiter");
				name = start;
				end = strchr (start, delim);
				if (*name == '"')
				{
					ELEKTRA_LOG_DEBUG ("Name starts with double quote character");
					++name;
					if (*(end - 2) == '"')
					{
						*(end - 2) = '\0';
					}
					else if (*(end - 1) == '"')
					{
						*(end - 1) = '\0';
					}
					else
					{
						ELEKTRA_LOG_DEBUG ("Did not find closing double quote characters in current line");
						strncpy0 (prev_name, name, sizeof (prev_name));
						while (fgets (line, INI_MAX_LINE, file))
						{
							ELEKTRA_LOG_DEBUG ("Read continuation line with content “%s”", line);
							end = line + (strlen (line) - 1);
							while (end > line && *end != '"')
								--end;
							if (*end == '"')
							{
								ELEKTRA_LOG_DEBUG ("Found closing double quote character");
								*(end++) = '\0';
								strncpy0 (prev_name + strlen (prev_name), line,
									  sizeof (prev_name) - strlen (prev_name));
								break;
							}
							else
							{
								ELEKTRA_LOG_DEBUG ("Found name continuation");
								strncpy (prev_name + strlen (prev_name), line,
									 sizeof (prev_name) - strlen (prev_name));
							}
							ELEKTRA_LOG_DEBUG ("New extended name is “%s”", prev_name);
						}
						name = prev_name;
						ELEKTRA_LOG_DEBUG ("Name of key is “%s”", name);
					}
				}
				if (*end != delim)
				{
					ELEKTRA_LOG_DEBUG ("Search for delimiter in “%s”", end);
					ptr = lskip (end + 1);
					end = strchr (ptr, delim);
					if (end && *end == delim)
					{
						*end = '\0';
						ELEKTRA_LOG_DEBUG ("Found delimiter – New name is “%s”", end);
					}
					else
					{
						ELEKTRA_LOG_WARNING ("Unable to find delimiter");
						error = lineno;
						break;
					}
				}
				else
				{
					*end = '\0';
				}
				if (name != prev_name && end > line)
				{
					rstrip (end - 1);
				}
				value = lskip (end + 1);
				end = find_char_or_comment (value, '\0');
				if (*end == ';') *end = '\0';
				rstrip (value);
				if (*value == '"')
				{
					*(value++) = '\0';
					while ((*end != '"') && !isprint (*end) && end > value)
						--end;
					if (*end == '"') *end = '\0';
				}
				if (prev_name != name) strncpy0 (prev_name, name, sizeof (prev_name));
				if (!config->keyHandler (user, section, name, value, 0) && !error) error = lineno;
			}
			else if (assign == 0)
			{
				ELEKTRA_LOG_DEBUG ("Found no delimiter");
				if (*start == '"')
				{
					ELEKTRA_LOG_DEBUG ("Found initial double quote character");
					++start;
					end = line + (strlen (line) - 1);
					while (end > start && *end != '"')
						--end;
					if (*end == '"' && end != start)
					{
						*end = '\0';
						if (!config->keyHandler (user, section, start, NULL, 0) && !error) error = lineno;
					}
					else
					{
						ELEKTRA_LOG_DEBUG ("Did not find closing double quote character");
						strncpy0 (prev_name, start, sizeof (prev_name));
						while (fgets (line, INI_MAX_LINE, file))
						{
							end = line + (strlen (line) - 1);
							ELEKTRA_LOG_DEBUG ("Read continuation line with content “%s”", line);
							while (end > line && *end != '"')
								--end;
							if (*end == '"')
							{
								ELEKTRA_LOG_DEBUG ("Found closing double quote character");
								*end = '\0';
								strncpy0 (prev_name + strlen (prev_name), line,
									  sizeof (prev_name) - strlen (prev_name));
								break;
							}
							else
							{
								ELEKTRA_LOG_DEBUG ("Found name continuation");
								strncpy (prev_name + strlen (prev_name), line,
									 sizeof (prev_name) - strlen (prev_name));
							}
							ELEKTRA_LOG_DEBUG ("New extended name is “%s”", prev_name);
						}
						name = prev_name;
						ptr = end + 1;
						end = strchr (ptr, '=');
						if (!end) end = strchr (ptr, ':');
						if (!end)
						{
							if (!config->keyHandler (user, section, name, NULL, 0) && !error) error = lineno;
						}
						else
						{
							*end = '\0';
							value = lskip (end + 1);
							if (*value == '"') end = find_char_or_comment (value, '\0');
							if (*end == ';') *end = '\0';
							rstrip (value);
							if (*value == '"' || *(value + 1) == '"')
							{
								if (*value == '"')
									*(value++) = '\0';
								else if (*(value + 1) == '"')
								{
									*(value + 1) = '\0';
									value += 2;
								}
								while ((*end != '"') && !isprint (*end) && end > value)
									--end;
								if (*end == '"') *end = '\0';
							}
							if (prev_name != name) strncpy0 (prev_name, name, sizeof (prev_name));
							if (!config->keyHandler (user, section, name, value, 0) && !error) error = lineno;
						}
					}
				}
				else
				{
					name = rstrip (start);
					strncpy0 (prev_name, name, sizeof (prev_name));
					if (!config->keyHandler (user, section, name, NULL, 0) && !error) error = lineno;
				}
			}
			else
			{
				ELEKTRA_LOG_DEBUG ("Found multiple delimiters");
				ptr = start + 1;
				while (*ptr)
				{
					if (*ptr == delim)
					{
						if (*(ptr + 1) == '"' || *(ptr + 2) == '"' || *(ptr - 1) == '"' || *(ptr - 2) == '"') break;
					}
					++ptr;
				}
				if (*ptr)
				{
					ELEKTRA_LOG_DEBUG ("Found double quote character");
					char tmpDel[4] = { ' ', delim, ' ', '\0' };
					end = strstr (ptr, tmpDel);
					name = NULL;
					if (end)
					{
						// keyname == "=" or " = " where '=' is the delimiter
						if (*(ptr + 1) == '"')
						{
							*(ptr + 1) = '\0';
						}
						else if (*(ptr + 2) == '"')
						{
							*(ptr + 2) = '\0';
						}
						if (*(ptr - 1) == '"')
							*(ptr - 1) = '\0';
						else if (*(ptr - 2) == '"')
							*(ptr - 2) = '\0';
						name = ptr;
					}
					else if (*ptr == delim)
					{
						*ptr = '\0';
						rstrip (start);
						if (*start == '"') ++start;
						if (*(ptr - 1) == '"')
							*(ptr - 1) = '\0';
						else if (*(ptr - 2) == '"')
							*(ptr - 2) = '\0';
						name = start;
					}
					else
					{
						if (!end) end = strrstr (start + 1, tmpDel);
						*end = '\0';
						ptr = end + 2;
						rstrip (start);
						name = start;
					}
					value = ptr + 1;

					end = find_char_or_comment (value, '\0');
					if (*end == ';') *end = '\0';
					rstrip (value);
					if (*value == '"' || *(value + 1) == '"')
					{
						if (*value == '"')
							*(value++) = '\0';
						else if (*(value + 1) == '"')
						{
							*(value + 1) = '\0';
							value += 2;
						}
						while ((*end != '"') && !isprint (*end) && end > value)
							--end;
						if (*end == '"') *end = '\0';
					}
				}
				else
				{
					ELEKTRA_LOG_DEBUG ("Found no double quote character");
					rstrip (start);
					name = start;
					end = strchr (start, delim);
					if (!end)
					{
						ELEKTRA_LOG_DEBUG ("Found no delimiter");
						value = NULL;
					}
					else
					{
						ELEKTRA_LOG_DEBUG ("Found delimiter");
						if (*end == delim) *end = '\0';
						rstrip (end - 1);
						value = lskip (end + 1);
						rstrip (value);
						if (*value == '"')
						{
							*(value++) = '\0';
							while ((*end != '"') && !isprint (*end) && end > value)
								--end;
							if (*end == '"') *end = '\0';
						}
					}
				}
				strncpy0 (prev_name, name, sizeof (prev_name));

				if (!config->keyHandler (user, section, name, value, 0) && !error) error = lineno;
			}
		}

#if INI_STOP_ON_FIRST_ERROR
		if (error) break;
#endif
	}

	free (line);
	return error;
}