Esempio n. 1
0
File: main.c Progetto: 11mariom/ekg2
static char *logs_prepare_path(session_t *session, const char *logs_path, const char *uid, time_t sent) {
	char *uidtmp, datetime[5];
	struct tm *tm = NULL;
	string_t buf;

	if (!logs_path)
		return NULL;

	buf = string_init(NULL);

	while (*logs_path) {
		if ((char)*logs_path == '%' && (logs_path+1) != NULL) {
			switch (*(logs_path+1)) {
				case 'S':	string_append_n(buf, session ? session->uid : "_null_", -1);
						break;
				case 'P':	string_append_n(buf, config_profile ? config_profile : "_default_", -1);
						break;
				case 'u':	uidtmp = xstrdup(get_uid(session, uid));
						goto attach; /* avoid code duplication */
				case 'U':	uidtmp = xstrdup(get_nickname(session, uid));
attach:
						if (!uidtmp) uidtmp = xstrdup(uid);

						if (xstrchr(uidtmp, '/'))
							*(xstrchr(uidtmp, '/')) = 0; // strip resource
						string_append_n(buf, uidtmp ? uidtmp : uid, -1);
						xfree(uidtmp);
						break;
				case 'Y':	if (!tm) tm = localtime(&sent);
							snprintf(datetime, 5, "%4d", tm->tm_year+1900);
						string_append_n(buf, datetime, 4);
						break;
				case 'M':	if (!tm) tm = localtime(&sent);
							snprintf(datetime, 3, "%02d", tm->tm_mon+1);
						string_append_n(buf, datetime, 2);
						break;
				case 'D':	if (!tm) tm = localtime(&sent);
							snprintf(datetime, 3, "%02d", tm->tm_mday);
						string_append_n(buf, datetime, 2);
						break;
				default:	string_append_c(buf, *(logs_path+1));
			};

			logs_path++;
		} else if (*logs_path == '~' && (*(logs_path+1) == '/' || *(logs_path+1) == '\0')) {
			string_append_n(buf, home_dir, -1);
			//string_append_c(buf, '/');
		} else
			string_append_c(buf, *logs_path);
		logs_path++;
	};

	// sanityzacja sciezki - wywalic "../", zamienic znaki spec. na inne
	// zamieniamy szkodliwe znaki na minusy, spacje na podkreslenia
	// TODO
	xstrtr(buf->str, ' ', '_');

	return string_free(buf, 0);
}
Esempio n. 2
0
/*
 * Look for the cgroup in a specific cgroup namespace that owns
 * a particular pid
 *
 * returned values:
 *  - XCGROUP_ERROR
 *  - XCGROUP_SUCCESS
 */
int xcgroup_ns_find_by_pid(xcgroup_ns_t* cgns, xcgroup_t* cg, pid_t pid)
{
	int fstatus = SLURM_ERROR;
	char file_path[PATH_MAX];
	char* buf;
	size_t fsize;
	char* p;
	char* e;
	char* entry;
	char* subsys;

	/* build pid cgroup meta filepath */
	if (snprintf(file_path, PATH_MAX, "/proc/%u/cgroup",
		      pid) >= PATH_MAX) {
		debug2("unable to build cgroup meta filepath for pid=%u : %m",
		       pid);
		return XCGROUP_ERROR;
	}

	/*
	 * read file content
	 * multiple lines of the form :
	 * num_mask:subsystems:relative_path
	 */
	fstatus = _file_read_content(file_path, &buf, &fsize);
	if (fstatus == XCGROUP_SUCCESS) {
		fstatus = XCGROUP_ERROR;
		p = buf;
		while ((e = xstrchr(p, '\n')) != NULL) {
			*e='\0';
			/* get subsystems entry */
			subsys = xstrchr(p, ':');
			p = e + 1;
			if (subsys == NULL)
				continue;
			subsys++;
			/* get relative path entry */
			entry = xstrchr(subsys, ':');
			if (entry == NULL)
				continue;
			*entry='\0';
			/* check subsystem versus ns one */
			if (xstrcmp(cgns->subsystems, subsys) != 0) {
				debug("skipping cgroup subsys %s(%s)",
				      subsys, cgns->subsystems);
				continue;
			}
			entry++;
			fstatus = xcgroup_load(cgns, cg, entry);
			break;
		}
		xfree(buf);
	}

	return fstatus;
}
Esempio n. 3
0
char rot13c(char c)
{
	char u[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	char l[] = "abcdefghijklmnopqrstuvwxyz";
	char *p;

	if ((p = xstrchr(u, c)) != NULL)
		return u[((p-u) + 13) % 26];
	else if ((p = xstrchr(l, c)) != NULL)
		return l[((p-l) + 13) % 26];
	else
		return c;
}
Esempio n. 4
0
void test_chrfn(void) {
	char	*c1, *p1;
	int	c;
	char	*num, *low, *upc, *gra, *wsp, *pun;
	char	alpha[128], alnum[128], xnum[128];

	pr("strchr");
	c1 = "...............X1..............X2";
	p1 = strchr(c1, 'X');
	if (!p1 || *p1 != 'X' || p1[1] != '1') fail("strchr-1");
	if (strchr(c1, 'Z')) fail("strchr-2");

	pr("strrchr");
	p1 = strrchr(c1, 'X');
	if (!p1 || *p1 != 'X' || p1[1] != '2') fail("strrchr-1");
	if (strrchr(c1, 'Z')) fail("strchr-2");

	pr("is*");
	num = "0123456789";
	low = "abcdefghijklmnopqrstuvwxyz";
	upc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	wsp = "\t\v\f\n\r ";
	pun = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~";
	strcpy(alpha, low);
	strcat(alpha, upc);
	strcpy(alnum, alpha);
	strcat(alnum, num);
	strcpy(xnum, num);
	strcat(xnum, "abcdefABCDEF");
	for (c=0; c<128; c++) {
		if (isalnum(c) && !strchr(alnum, c)) fail("isalnum-1");
		if (isalpha(c) && !strchr(alpha, c)) fail("isalpha-1");
		if (iscntrl(c) && c > 31 && c < 127) fail("iscrntl-1");
		if (isdigit(c) && !strchr(num, c)) fail("isdigit-1");
		if (isgraph(c) && c < 33 && c > 126) fail("isgraph-1");
		if (islower(c) && !strchr(low, c)) fail("islower-1");
		if (isprint(c) && (c < 32 || c > 126)) fail("isprint-1");
		if (ispunct(c) && !strchr(pun, c)) fail("ispunct-1");
		if (isspace(c) && !strchr(wsp, c)) fail("isspace-1");
		if (isupper(c) && !strchr(upc, c)) fail("isupper-1");
		if (isxdigit(c) && !strchr(xnum, c)) fail("isxdigit-1");
		if (!isalnum(c) && xstrchr(alnum, c)) fail("isalnum-2");
		if (!isalpha(c) && xstrchr(alpha, c)) fail("isalpha-2");
		if (!iscntrl(c) && (c < 32 || c > 126)) fail("iscrntl-2");
		if (!isdigit(c) && xstrchr(num, c)) fail("isdigit-2");
		if (!isgraph(c) && c > 32 && c < 127) fail("isgraph-2");
		if (!islower(c) && xstrchr(low, c)) fail("islower-2");
		if (!isprint(c) && c > 31 && c < 127) fail("isprint-2");
		if (!ispunct(c) && xstrchr(pun, c)) fail("ispunct-2");
		if (!isspace(c) && xstrchr(wsp, c)) fail("isspace-2");
		if (!isupper(c) && xstrchr(upc, c)) fail("isupper-2");
		if (!isxdigit(c) && xstrchr(xnum, c)) fail("isxdigit-2");
		if (isupper(c) && !islower(tolower(c))) fail("tolower-1");
		if (islower(c) && tolower(toupper(c)) != c) fail("tolower-2");
		if (islower(c) && !isupper(toupper(c))) fail("toupper-1");
		if (isupper(c) && toupper(tolower(c)) != c) fail("toupper-2");
	}
}
Esempio n. 5
0
/*
 * variable_add()
 *
 * dodaje zmienn± do listy zmiennych.
 *
 *  - plugin - opis wtyczki, która obs³uguje zmienn±,
 *  - name - nazwa,
 *  - type - typ zmiennej,
 *  - display - czy i jak ma wy¶wietlaæ,
 *  - ptr - wska¼nik do zmiennej,
 *  - notify - funkcja powiadomienia,
 *  - map - mapa warto¶ci,
 *  - dyndisplay - funkcja sprawdzaj±ca czy wy¶wietliæ zmienn±.
 *
 * zwraca 0 je¶li siê nie uda³o, w przeciwnym wypadku adres do strutury.
 */
variable_t *variable_add(plugin_t *plugin, const char *name, int type, int display, void *ptr, variable_notify_func_t *notify, variable_map_t *map, variable_display_func_t *dyndisplay) {
	variable_t *v;
	char *__name;

	if (!name)
		return NULL;

	if (plugin && !xstrchr(name, ':'))
		__name = saprintf("%s:%s", plugin->name, name);
	else
		__name = xstrdup(name);

	v = xmalloc(sizeof(variable_t));
	v->name		= __name;
	v->name_hash	= variable_hash(__name);
	v->type		= type;
	v->display	= display;
	v->ptr		= ptr;
	v->notify	= notify;
	v->map		= map;
	v->dyndisplay	= dyndisplay;
	v->plugin	= plugin;

	variables_add(v);
	return v;
}
Esempio n. 6
0
/* Return 1 on success, 0 on failure to find a stepid in the string */
static int _parse_stepid(const char *jobid_str, uint32_t *out_stepid)
{
	char *ptr, *job, *step;
	long stepid;

	job = xstrdup(jobid_str);
	ptr = xstrchr(job, '.');
	if (ptr == NULL) {
		/* did not find a period, so no step ID in this string */
		xfree(job);
		return 0;
	} else {
		step = ptr + 1;
	}

	stepid = strtol(step, &ptr, 10);
	if (!xstring_is_whitespace(ptr)) {
		fprintf(stderr, "\"%s\" does not look like a stepid\n", step);
		xfree(job);
		return 0;
	}

	*out_stepid = (uint32_t) stepid;
	xfree(job);
	return 1;
}
Esempio n. 7
0
static int cut_email(const char *in_buf, char *out_buf)
{
	int i, j;

	if (lstrlen(in_buf) < 3)
		return 1;

	for (i=0; in_buf[i] && (isspace(in_buf[i]) || !isemailchar(in_buf[i])); i++);
	for (; in_buf[i] && xstrchr(BEGINEND_INV, in_buf[i]); i++);

	for (j=0; in_buf[i]; i++) {
		if (in_buf[i] == '@') break;
		if (!isemailchar(in_buf[i])) continue;
		out_buf[j++] = tolower(in_buf[i]);
	}
	if (in_buf[i] != '@') return 1;
	while (in_buf[i] == '@') i++;
	out_buf[j] = 0;

	TRIM_END(out_buf);

	out_buf[j++] = '@';
	for (; in_buf[i]; i++) {
		if (!isemailchar(in_buf[i])) continue;
		if ((out_buf[j-1] == '.') && (in_buf[i] == '.')) continue;
		out_buf[j++] = tolower(in_buf[i]);
	}
	out_buf[j] = 0;

	TRIM_END(out_buf);

	if ((lstrlen(out_buf) < 3) || (out_buf[0] == '@'))
		return 1;
	return 0;
}
Esempio n. 8
0
char *xindex(const char *s, int c)
{
#ifdef NO_POSIX_SYSTEM
	return xstrchr(s, c);
#else
	return index(fix(s), c);
#endif
}
Esempio n. 9
0
static BINDING_FUNCTION(binding_window_kill)
{
    /* rfc2811: "Channels names are strings (beginning with a '&', '#', '+' or '!' character)..." */
    const char *pfx = "&#+!";
    char * ptr;
    ptr = xstrstr(window_current->target, "irc:");
    if (ptr && ptr == window_current->target && xstrchr(pfx, ptr[4]) && !config_kill_irc_window ) {
        print("cant_kill_irc_window");
        return;
    }
    command_exec(window_current->target, window_current->session, ("/window kill"), 0);
}
Esempio n. 10
0
int irc_autorejoin(session_t *s, int when, char *chan) {
	irc_private_t *j;
	string_t st;
	window_t *w;
	char *chanprefix;
	int rejoin;

#if 1	/* there's no need of doing it, already checked by irc_onkick_handler() or if it goes through irc_c_init() it's even better. */
	if (!s || !(j = s->priv) || (s->plugin != &irc_plugin))
		return -1;
#endif
	chanprefix = SOP(_005_CHANTYPES);
	rejoin = session_int_get(s, "REJOIN");

	if (!(rejoin&(1<<(when))))
		return -1;

	switch (when) {
		case IRC_REJOIN_CONNECT:
			st = string_init(NULL);
			for (w = windows; w; w = w->next) {
				if (!w->target || w->session != s)			/* check if sessions match and has w->target */
					continue;

				if (valid_plugin_uid(s->plugin, w->target) != 1)	/* check if window is correct for irc: */
					continue;

				if (!xstrchr(chanprefix, (w->target)[4]))		/* check if this is channel.. */
					continue;

				if (st->len)
					string_append_c(st, ',');
				if ((w->target)[4] == '!') {
					string_append_c(st, '!');
					string_append(st, w->target + 10);
				} else {
					string_append(st, w->target + 4);
				}
			}
			if (st->len)
				irc_write(s, "JOIN %s\r\n", st->str);
			string_free(st, 1);
			break;

		case IRC_REJOIN_KICK:
			irc_write(s, "JOIN %s\r\n", chan);
			break;

		default:
			return -1;
	}
	return 0;
}
Esempio n. 11
0
File: misc.c Progetto: hiciu/ekg2
static void irc_parse_ident_host(char *identhost, char **ident, char **host)  {
	char	*tmp;

	xfree(*ident);
	xfree(*host);
	if ((tmp = xstrchr(identhost, '@'))) {
		*ident = xstrndup(identhost, tmp-identhost);
		*host  = xstrdup(tmp+1);
	} else {
		*ident = xstrdup(identhost);
		*host = NULL;
	}
}
Esempio n. 12
0
static const char *xmsg_dirfix(const char *path)
{
	char *buf = (char*) prepare_pathf(NULL); /* steal the buffer */
	
	if (strlcpy(buf, path, PATH_MAX) >= PATH_MAX) { /* buffer too small */
		xdebug2(DEBUG_ERROR, "Buffer too small for: in = %s, len = %d, PATH_MAX = %d", path, xstrlen(path), PATH_MAX);
		return NULL;
	}

	/* if path starts with slash, we leave it as is,
	 * otherwise we convert # to / */
	if (*buf != '/') {
		char *p;

		for (p = xstrchr(buf, '#'); p; p = xstrchr(p+1, '#'))
			*p = '/';
	}

	xdebug("in: %s, out: %s", path, buf);

	return buf;
}
Esempio n. 13
0
PXMLNode xmlGetItem(PXMLNode x,const wchar_t *szPath)
{
  const wchar_t *s;
  if(!x)return NULL;
  if(*szPath==L'/')
  {
    while(x->pParent)x=x->pParent;
    szPath++;
  }
  for(;;)
  {
    s=xstrchr(szPath,L'/');
    if(!s)return (PXMLNode)hashGet(x->hChildren,szPath);
    //*s=0;
    x=(PXMLNode)hashGetEx(x->hChildren,szPath,(int)(s-szPath));
    //*s='/';
    if(!x)return NULL;
    szPath=s+1;
  }
}
Esempio n. 14
0
PXMLNode xmlGetItem(PXMLNode x,pchar szPath)
{
  pchar s;
  if(!x)return NULL;
  if(*szPath=='/')
  {
    while(x->pParent)x=x->pParent;
    szPath++;
  }
  for(;;)
  {
    s=xstrchr(szPath,'/');
    if(!s)return hashGet(x->hChildren,szPath);
    //*s=0;
    x=hashGetEx(x->hChildren,szPath,s-szPath);
    //*s='/';
    if(!x)return NULL;
    szPath=s+1;
  }
}
Esempio n. 15
0
static void _parse_jobid_stepid(char *jobid_str)
{
	char *ptr, *job, *step;
	long jobid, stepid;

	verbose("jobid/stepid string = %s\n", jobid_str);
	job = xstrdup(jobid_str);
	ptr = xstrchr(job, '.');
	if (ptr == NULL) {
		error("Did not find a period in the step ID string");
		_usage();
		xfree(job);
		exit(error_exit);
	} else {
		*ptr = '\0';
		step = ptr + 1;
	}

	jobid = slurm_xlate_job_id(job);
	if (jobid == 0) {
		error("\"%s\" does not look like a jobid", job);
		_usage();
		xfree(job);
		exit(error_exit);
	}

	stepid = strtol(step, &ptr, 10);
	if (!xstring_is_whitespace(ptr)) {
		error("\"%s\" does not look like a stepid", step);
		_usage();
		xfree(job);
		exit(error_exit);
	}

	opt.jobid = (uint32_t) jobid;
	opt.stepid = (uint32_t) stepid;

	xfree(job);
}
Esempio n. 16
0
/* Return 1 on success, 0 on failure to find a jobid in the string */
static int _parse_jobid(const char *jobid_str, uint32_t *out_jobid)
{
	char *ptr, *job;
	long jobid;

	job = xstrdup(jobid_str);
	ptr = xstrchr(job, '.');
	if (ptr != NULL) {
		*ptr = '\0';
	}

	jobid = strtol(job, &ptr, 10);
	if (!xstring_is_whitespace(ptr)) {
		fprintf(stderr, "\"%s\" does not look like a jobid\n", job);
		xfree(job);
		return 0;
	}

	*out_jobid = (uint32_t) jobid;
	xfree(job);
	return 1;
}
Esempio n. 17
0
File: main.c Progetto: hiciu/ekg2
static logs_log_t *logs_log_new(const char *session, const char *target, gboolean raw) {
	logs_log_t *ll;
	log_format_t format;
	char *uid, *tmp;

	if (LOG_FORMAT_NONE == (format = raw ? LOG_FORMAT_RAW : logs_log_format(session_find(session))))
		return NULL;

	if (!(uid = g_strdup(get_uid_any(session_find(session), target))))
		uid = g_strdup(target);
	if ((tmp = xstrchr(uid, '/')))
		*tmp = '\0';		// strip resource

	ll = logs_log_find(session, uid, raw);

	if (ll) {
		g_free(uid);
		return ll;
	}

	// Create new
	ll = xmalloc(sizeof(logs_log_t));
	ll->session = g_strdup(session);
	ll->uid = uid;
	ll->format = format;
	ll->fname = logs_prepare_fname(ll);

	g_ptr_array_add(logs_logs, ll);

	if (ll->format == LOG_FORMAT_IRSSI && xstrlen(IRSSI_LOG_EKG2_OPENED)) {
		logs_open_file(ll);
		logs_irssi_sysmsg(ll, prepare_timestamp_format(IRSSI_LOG_EKG2_OPENED, time(NULL)));
	}

	debug("[logs] log_new s=%s uid=%s ff=%d logs_log_t %x\n", __(session), __(uid), ll->format, ll);

	return ll;
}
Esempio n. 18
0
PXMLNode xmlCreateItem(void* Pool,PXMLNode x,pchar szPath)
{
  pchar s;
  if(!x)return NULL;
  if(*szPath=='/')
  {
    while(x->pParent)x=x->pParent;
    szPath++;
  }
  for(;;)
  {
    s=xstrchr(szPath,'/');
    if(!s)
    {
      return xmlCreateChild(Pool,x,szPath);
    }
    *s=0;
    x=xmlCreateChild(Pool,x,szPath);
    x->eType=xmlNode;
    *s='/';
    szPath=s+1;
  }
}
Esempio n. 19
0
PXMLNode xmlCreateItem(void* Pool,PXMLNode x,const wchar_t *szPath)
{
  const wchar_t *s;
  if(!x)return NULL;
  if(*szPath==L'/')
  {
    while(x->pParent)x=x->pParent;
    szPath++;
  }
  for(;;)
  {
    s=xstrchr(szPath,L'/');
    if(!s)
    {
      return xmlCreateChild(Pool,x,szPath);
    }
    *((wchar_t *)s)=0;
    x=xmlCreateChild(Pool,x,szPath);
    x->eType=xmlNode;
    *((wchar_t *)s)=L'/';
    szPath=s+1;
  }
}
Esempio n. 20
0
int xmlParse(void* Pool,PXMLNode x,pchar src,int flags)
{
  int sz=xstrlen(src);
  int i,st,n;
  xchar str[256];
  PXMLNode stack[256];
  int stackpos=0;
  PXMLNode p=x,c;
  PHashLink l;
  PXMLNode chlds=NULL;
  if(!sz)return 0;

  for(i=0;i<sz;i++)
  {
    if(xmlIsSpace(src[i]))continue;
    if(src[i]=='<' && src[i+1]=='!' && src[i+2]=='-' && src[i+3]=='-' && sz-i>4)
    {
      i+=4;
      st=i;
      while((src[i]!='-' || src[i+1]!='-' || src[i+2]!='>') && sz-i>3)i++;
      i+=3;
      if(sz-i<3)return 0;
      c=xmlNewChild(Pool,p,xmlComment);
      c->szCont=xstrndup(Pool,src+st,i-st-3);
      if(chlds)chlds->pNext=c;
      else p->pChildren=c;
      chlds=c;
      continue;
    }
    if(src[i]=='<')
    {
      i++;
      if(src[i]=='/')
      {
        i++;
        st=i;
        i=xmlGetWordEnd(src,i);
        if(i==-1)return 0;
        i=xmlSkipSpace(src,i);CHK;
        if(src[i]!='>')return 0;
        n=i-st;
        if(!xstrncmp(p->szName,src+st,n))return 0;
        //i++;
        p=p->pParent;
        if(p->eType==xmlRoot)return 1;
        stackpos--;
        chlds=stack[stackpos];
        continue;
      }
      if(wc[(xuchar)src[i]])
      {
        st=i;
        i=xmlGetWordEnd(src,i);CHK;
        c=xmlNewChild(Pool,p,xmlLeaf);
        if(p->eType!=xmlRoot)p->eType=xmlNode;
        n=i-st;
        if(n>255)n=255;
        xstrncpy(str,src+st,n);
        if(p->hChildren==NULL)p->hChildren=hashNew(Pool);
        l=hashAdd(p->hChildren,str,c);
        c->szName=l->szKey;
        if(chlds)chlds->pNext=c;
        else p->pChildren=c;
        chlds=c;
        i=xmlParseTag(Pool,c,&p,src,i);
        if(i==0)return 0;
        if(p==c)
        {
          stack[stackpos]=chlds;
          stackpos++;
          chlds=NULL;
        }
        i=xmlSkipSpace(src,i);CHK;
        st=i;
        i=xmlSkipTill(src,i,'<');CHK;
        if(i>st)
        {
          p->szCont=xmlSubst(xstrndup(Pool,src+st,i-st));
        }
        i--;
        continue;
      }
      if(src[i]=='!' || src[i]=='?')
      {
        st=i+1;
        if(src[i+1]=='[')
        {
          if(xstrncmp(src+i,"![CDATA[",8))
          {
            pchar p=src+i+8;
            while((p=xstrchr(p,']')))
            {
              if(p[1]==']' && p[2]=='>')break;
            }
            if(p)i=p-src+2;
          }else i=xmlSkipTill(src,i,'>');
        }else
        {
          i=xmlSkipTill(src,i,'>');
        }
        if(i==-1)return 0;
        c=xmlNewChild(Pool,p,src[st-1]=='!'?xmlExcl:xmlQuest);
        c->szCont=xstrndup(Pool,src+st,i-st);
        if(chlds)chlds->pNext=c;
        else p->pChildren=c;
        chlds=c;
        continue;
      }
    }else
    {
      st=i;
      i=xmlSkipTill(src,i,'<');CHK;
      c=xmlNewChild(Pool,p,xmlContent);
      c->szCont=xmlSubst(xstrndup(Pool,src+st,i-st));
      if(chlds)chlds->pNext=c;
      else p->pChildren=c;
      chlds=c;
      i--;
    }
  }
  return 1;
}
Esempio n. 21
0
File: main.c Progetto: 11mariom/ekg2
	/* items == -1 display all */
static int logs_buffer_raw_display(const char *file, int items) {
	struct buffer **bs = NULL;
	struct buffer *b;
	char *beg = NULL, *profile = NULL, *sesja = NULL, *target = NULL;

	int item = 0;
	int i;

	session_t *s;
	window_t *w;

	if (!file) return -1;
	if (!items) return 0;

	/* i'm weird, let's search for logs/__internal__ than check if there are smth after it... & check if there are two '/'	*/
	if ((beg = xstrstr(file, "logs/__internal__")) && xstrlen(beg) > 19 && xstrchr(beg+18, '/') && xstrchr(beg+18, '/') != xstrrchr(beg+18, '/')) {
		profile = beg + 18;
		sesja	= xstrchr(profile, '/')+1;
		target	= xstrchr(sesja, '/')+1;
	}
	debug("[logs_buffer_raw_display()] profile: 0x%x sesja: 0x%x target: 0x%x\n", profile, sesja, target);

	if (!profile || !sesja || !target) return -1;

	profile = (xstrcmp(target, "_default_"))	? xstrndup(profile, sesja-profile-1) : NULL;
	sesja	= (xstrcmp(target, "_null_"))		? xstrndup(sesja, target-sesja-1) : NULL;
	target	= xstrdup(target);
	debug("[logs_buffer_raw_display()] profile: %s sesja: %s target: %s\n", __(profile), __(sesja), __(target));

	/* search for session+window */
	s = session_find(sesja);
	w = window_find_s(s, target);


	debug("[logs_buffer_raw_display()] s:0x%x; w:0x%x;\n", s, w);

	if (!w)
		w = window_current;

	if (w) w->lock++;

	for (b = buffer_lograw.data; b; b = b->next) {
		if (!xstrcmp(b->target, file)) {
			/* we asume that (b->ts < (b->next)->ts, it's quite correct unless other plugin do this trick... */
			if (items == -1) { 
				logs_print_window(s, w, b->line, b->ts);
			} else {
				bs		= (struct buffer **) xrealloc(bs, (item+2) * sizeof(struct buffer *));
				bs[item + 1]	= NULL;
				bs[item]	= b;
			}
			item++;
		}
	}
	if (bs) for (i = item < items ? 0 : item-items; i < item; i++) 
		logs_print_window(s, w, bs[i]->line, bs[i]->ts);

	if (w) {
		w->lock--;
		query_emit(NULL, "ui-window-refresh");
	}

	xfree(bs);

	xfree(profile);
	xfree(sesja);
	xfree(target);
	return item;
}
Esempio n. 22
0
void InfoDrivers()
{
	HMODULE hPSAPI = LoadLibraryA("psapi.dll");
	if (NULL != hPSAPI)
	{
		pfnEnumDeviceDrivers EnumDeviceDrivers = (pfnEnumDeviceDrivers) GetProcAddress(hPSAPI, "EnumDeviceDrivers");
		pfnGetDeviceDriverNameA GetDeviceDriverBaseNameA = (pfnGetDeviceDriverNameA) GetProcAddress(hPSAPI, "GetDeviceDriverBaseNameA");
		pfnGetDeviceDriverNameA GetDeviceDriverFileNameA = (pfnGetDeviceDriverNameA) GetProcAddress(hPSAPI, "GetDeviceDriverFileNameA");
		if (NULL != EnumDeviceDrivers && NULL != GetDeviceDriverBaseNameA && NULL != GetDeviceDriverFileNameA)
		{
			LPVOID * drivers = NULL;
			DWORD needed = 0;
			EnumDeviceDrivers(NULL, 0, &needed);
			drivers = (LPVOID*) malloc(needed);

			if (EnumDeviceDrivers(drivers, needed, &needed))
			{
				DWORD i;
				char windir[NtfsMaxPath] = {0};
				if (!GetWindowsDirectoryA(windir, NtfsMaxPath))
				{
					xstrcat(windir, NtfsMaxPath, "C:\\Windows");
				}
				ConsoleIOPrint("Drivers : \n");
				for (i = 0; i < needed / sizeof(LPVOID); ++i)
				{
					char name[NtfsMaxPath] = {0};
					
					if (GetDeviceDriverFileNameA(drivers[i], name, NtfsMaxPath) || GetDeviceDriverBaseNameA(drivers[i], name, NtfsMaxPath))
					{
						VersionInfo info;
						char full[NtfsMaxPath] = {0};
						char * path = name;
						if (0 == memcmp(path, "\\??\\", 4))
						{
							path += 4;
						}
						if (0 == memcmp(path, "\\SystemRoot\\", xstrlen("\\SystemRoot\\")))
						{
							xstrcat(full, NtfsMaxPath, windir);
							xstrcat(full, NtfsMaxPath, path + xstrlen("\\SystemRoot\\") - 1);
						}
						else if (0 == memcmp(path, "\\WINDOWS\\", xstrlen("\\WINDOWS\\")) ||
							0 == memcmp(path, "\\Windows\\", xstrlen("\\Windows\\")))
						{
							xstrcat(full, NtfsMaxPath, windir);
							xstrcat(full, NtfsMaxPath, path + xstrlen("\\WINDOWS\\") - 1);
						}
						else
						{
							if (NULL == xstrchr(path, '\\'))
							{
								xstrcat(full, NtfsMaxPath, windir);
								xstrcat(full, NtfsMaxPath, "\\system32\\drivers\\");
								xstrcat(full, NtfsMaxPath, path);
							}
							else
							{
								xstrcat(full, NtfsMaxPath, path);
							}
						}
						GetVersionInfo(full, &info);
						ConsoleIOPrintFormatted("%s, %s, %s, %s\n", full, info.FileDescription, info.CompanyName, info.ProductVersion);
					}
				}
			}
		}
		FreeLibrary(hPSAPI);
	}
}
Esempio n. 23
0
File: misc.c Progetto: hiciu/ekg2
static void irc_access_parse(session_t *s, channel_t *chan, people_t *p, int flags) {
	userlist_t *ul;

	if (!s || !chan || !p)
		return;

#define dchar(x) debug("%c", x);

	for (ul = s->userlist; ul; ul = ul->next) {
		userlist_t *u = ul;
		ekg_resource_t *r = NULL, *rl;

		int i, j;

		if (!p->ident || !p->host) continue;

		if (xstrncmp(u->uid, "irc:", 4)) continue;	/* check for irc: */

		for (rl = u->resources; rl; rl = rl->next) {
			r = rl;

			if (r->priv_data == p) {
				const char *tmp = &(u->uid[4]);

				/* fast forward move.. */
				if (!(tmp = xstrchr(tmp, '!')) || !(tmp = xstrchr(tmp, '@')) || !(tmp = xstrchr(tmp, ':'))) {
					debug_error("%s:%d INTERNAL ERROR\n", __FILE__, __LINE__);
					goto next3;
				}
				tmp++;
				i = (tmp - u->uid);
				debug("irc, checkchan: %s\n", tmp);
				goto skip_identhost_check;
				break;	/* never here */
			}
		}
		r = NULL;
/* parse nick! */
		for (i = 4, j = 0; (u->uid[i] != '\0' && u->uid[i] != '!'); i++, j++) {
			dchar(u->uid[i]);

			if (u->uid[i] != p->ident[j]) {
				if (u->uid[i] == '*') j += do_sample_wildcard_match(&u->uid[i+1], &p->ident[j], '!');
				else if (u->uid[i] == '?') continue;
				else goto next;
			}
		} if (!u->uid[i]) goto next;
		dchar('!');
		i++;

/* parse ident@ */
		for (j = 0; (u->uid[i] != '\0' && u->uid[i] != '@'); i++, j++) {
			dchar(u->uid[i]);

			if (u->uid[i] != p->nick[j]) {
				if (u->uid[i] == '*') j += do_sample_wildcard_match(&u->uid[i+1], &p->ident[j], '@');
				else if (u->uid[i] == '?') continue;
				else goto next;
			}
		} if (!u->uid[i]) goto next;
		dchar('@');
		i++;

/* parse host: */
		for (j = 0; (u->uid[i] != '\0' && u->uid[i] != ':'); i++, j++) {
			dchar(u->uid[i]);

			if (u->uid[i] != p->host[j]) {
				if (u->uid[i] == '*') j += do_sample_wildcard_match(&u->uid[i+1], &p->ident[j], ':');
				else if (u->uid[i] == '?') continue;
				else goto next;
			}
		} if (!u->uid[i]) goto next;
		dchar('\n');
		i++;

		debug_error("irc_access_parse() %s!%s@%s MATCH with %s\n", p->ident, p->nick, p->host, u->uid+4);

skip_identhost_check:
/* let's rock with channels */
		{
			char **arr = array_make(&u->uid[i], ",", 0, 1, 0);

			int ismatch = 0;


			for (i=0; arr[i]; i++) {
				int k;
				debug_error("CHAN%d: %s: ", i, arr[i]);

				for (j = 0, k = 4 /* skip irc: */; arr[i][j]; j++, k++) {
					if (arr[i][j] != chan->name[k]) {
						if (arr[i][j] == '*') k += do_sample_wildcard_match(&arr[i][j+1], &chan->name[k], '\0');
						else if (arr[i][j] == '?') continue;
						else goto next2;
					}
				}
				if (chan->name[k] != '\0')
					goto next2;

				ismatch = 1;
				debug_error("MATCH\n");
				break;
next2:
				debug_error("NOT MATCH\n");
				continue;

			}
			g_strfreev(arr);

			if (!ismatch) continue;
		}
		if (!r) {
			char *tmp = irc_uid(p->nick);
			r = userlist_resource_add(u, tmp, 0);
			g_free(tmp);

			r->status	= EKG_STATUS_AVAIL;
			r->descr	= xstrdup(chan->name+4);
			r->priv_data	= p;

			if (u->status != EKG_STATUS_AVAIL) {
				xfree(u->descr);
				u->status	= EKG_STATUS_AVAIL;
				u->descr	= xstrdup("description... ?");
				query_emit(NULL, "userlist-changed", &(s->uid), &(u->uid));
			}
		} else {
			string_t str = string_init(r->descr);

			string_append_c(str, ',');
			string_append(str, chan->name+4);

			xfree(r->descr); r->descr = string_free(str, 0);
		}

		/* tutaj ladnie by wygladalo jakbysmy wywolali protocol-status.. ale jednak to jest b. kiepski pomysl */
		debug_error("USER: 0x%x PERMISION GRANTED ON CHAN: 0x%x\n", u, chan);
		continue;

next:
		dchar('\n');
		debug_error("irc_access_parse() %s!%s@%s NOT MATCH with %s\n", p->ident, p->nick, p->host, u->uid+4);
next3:
		continue;
	}
#undef dchar
}
Esempio n. 24
0
unsigned char *
sas_alias_form(struct sas_info *sip, const unsigned char *form, 
	       const unsigned char *cf,
	       const unsigned char *gw,
	       const unsigned char *pos)
{
  unsigned char *tmp = malloc(strlen((const char *)form)+1), *s, *atmp;
  struct sas_map *maps;
  int i, alen, postdet_flag;

  if (verbose)
    sas_debug = 1;

  xstrcpy(tmp,form);
  for (i = 1, s = tmp; *s; ++s)
    {
      if (*s == '-')
	++i;
      else if ((*s == '}' && s[1]  && s[1] != '-') /* predet */
	       || (*s == '{' && s > tmp && s[-1] != '-') /* postdet */)
	++i;
    }

  maps = malloc((i+1)*sizeof(struct sas_map));
  i = postdet_flag = 0;
  s = tmp;
  do
    {
      if (*s == '{')
	{
	  maps[i].det = (postdet_flag ? 1 : -1);
	  *s++ = '\0';
	  maps[i].v = s;
	  s = xstrchr(s,'}');
	  if (s)
	    {
	      *s++ = '\0';
	      if (*s == '-')
		{
		  *s++ = '\0';
		  postdet_flag = 0;
		}
	      else if (*s == '{')
		postdet_flag = (maps[i].det == 1 ? 1 : 0);
	      else
		postdet_flag = 0;
	      ++i;
	    }
	  else
	    {
	      /* unclosed determinative will be warned about elsewhere */
	      return tmp;
	    }
	}
      else
	{
	  maps[i].det = 0;
	  maps[i++].v = s;
	  while (*s && *s != '-' && *s != '{')
	    ++s;
	  if (*s == '-')
	    *s++ = '\0';
	  else if (*s == '{')
	    postdet_flag = 1;
	  /* else *s == '\0', do nothing */
	}
    }
  while (*s);

  maps[i].v = NULL;

  for (alen = i = 0; maps[i].v; ++i)
    {
      maps[i].a = alias(sip,maps,i,cf,gw,pos);
      alen += xstrlen(maps[i].a) + 3; /* leave space for {}- regardless of detflag */
    }

  atmp = malloc(alen+1);

  for (i = 0, *atmp = '\0'; maps[i].v; ++i)
    {
      if (maps[i].det)
	{
	  if (maps[i].det > 0 && maps[i+1].v && maps[i+1].det != 1 && maps[i+1].v[0] != '\\')
	    sprintf((char*)atmp+xstrlen(atmp),"{%s}-",maps[i].a);
	  else
	    sprintf((char*)atmp+xstrlen(atmp),"{%s}",maps[i].a);
	}
      else
	{
	  xstrcat(atmp,maps[i].a);
	  if (maps[i+1].v && maps[i+1].det <= 0)
	    xstrcat(atmp,"-");
	}
    }

  if (verbose)
    {
      if (cf)
	{
	  if (strcmp((char*)form,(char*)atmp))
	    fprintf(stderr,"sas: aliasing %s under %s[%s]%s => %s\n",
		    form,cf,gw,(char*)(pos?pos:(unsigned char*)""), atmp);
	  else
	    fprintf(stderr,"sas: no alias for %s under %s[%s]%s\n",
		    form,cf,gw,(char*)(pos?pos:(unsigned char*)""));
	}
      else
	{
	  if (strcmp((char*)form,(char*)atmp))
	    fprintf(stderr,"sas: dumb aliasing %s => %s\n", form, atmp);
	  else
	    fprintf(stderr,"sas: no dumb alias for %s\n", form);
	}
    }

  free(maps);

  if ((s = hash_find(sip->post,atmp)))
    {
      if (xstrlen(s) > xstrlen(atmp))
	atmp = realloc(atmp,xstrlen(s)+1);
      if (verbose)
	fprintf(stderr,"sas: post-alias forces %s => %s\n", atmp, s);
      xstrcpy(atmp,s);
    }

  free(tmp);
  return atmp;
}
Esempio n. 25
0
/*
 * watch_handle_line()
 *
 * obs³uga deskryptorów przegl±danych WATCH_READ_LINE.
 */
void watch_handle_line(watch_t *w)
{
	char buf[1024], *tmp;
	int ret, res = 0;
	int (*handler)(int, int, const char *, void *) = w->handler;

	if (!w || w->removed == -1)
		return;	/* watch is running in another thread / context */

	w->removed = -1;
#ifndef NO_POSIX_SYSTEM
	ret = read(w->fd, buf, sizeof(buf) - 1);
#else
	ret = recv(w->fd, buf, sizeof(buf) - 1, 0);
	if (ret == -1 && WSAGetLastError() == WSAENOTSOCK) {
		printf("recv() failed Error: %d, using ReadFile()", WSAGetLastError());
		res = ReadFile(w->fd, &buf, sizeof(buf)-1, &ret, NULL);
		printf(" res=%d ret=%d\n", res, ret);
	}
	res = 0;
#endif

	if (ret > 0) {
		buf[ret] = 0;
		string_append(w->buf, buf);
#ifdef NO_POSIX_SYSTEM
		printf("RECV: %s\n", buf);
#endif
	}

	if (ret == 0 || (ret == -1 && errno != EAGAIN))
		string_append_c(w->buf, '\n');

	while ((tmp = xstrchr(w->buf->str, '\n'))) {
		size_t strlen = tmp - w->buf->str;		/* get len of str from begining to \n char */
		char *line = xstrndup(w->buf->str, strlen);	/* strndup() str with len == strlen */

		/* we strndup() str with len == strlen, so we don't need to call xstrlen() */
		if (strlen > 1 && line[strlen - 1] == '\r')
			line[strlen - 1] = 0;

		if ((res = handler(0, w->fd, line, w->data)) == -1) {
			xfree(line);
			break;
		}

		string_remove(w->buf, strlen + 1);

		xfree(line);
	}

	/* je¶li koniec strumienia, lub nie jest to ci±g³e przegl±danie,
	 * zwolnij pamiêæ i usuñ z listy */
	if (res == -1 || ret == 0 || (ret == -1 && errno != EAGAIN) || w->removed == 1) {
		int fd = w->fd;
		w->removed = 0;

		watch_free(w);
		close(fd);
		return;
	} 
	w->removed = 0;
}
Esempio n. 26
0
File: misc.c Progetto: hiciu/ekg2
int irc_parse_line(session_t *s, const char *l)
{
	static GString *strbuf = NULL;
	irc_private_t *j = s->priv;
	int	i, c=0, ecode, n_params;
	char	*p, *cmd, *colon2, **args = NULL, **pfxcmd = NULL;

	gchar *buf;
	int	len;

	if (G_UNLIKELY(!strbuf))
		strbuf = g_string_new(l);
	else
		g_string_assign(strbuf, l);

	irc_convert_in(j, strbuf);
	buf = strbuf->str;
	len = strbuf->len;

	query_emit(NULL, "irc-parse-line", &s->uid, &buf);

	p=buf;
	if(!p)
		return -1;
/*
Each IRC message may consist of up to three main parts: the prefix
(optional), the command, and the command parameters (of which there
may be up to 15).  The prefix, command, and all parameters are
separated by one (or more) ASCII space character(s) (0x20).

The presence of a prefix is indicated with a single leading ASCII
colon character (':', 0x3b), which must be the first character of the
message itself.  There must be no gap (whitespace) between the colon
and the prefix.
*/
	/* GiM: In fact this is probably not needed, but just in case...  */
	for (i=0; i<len; i++) if (buf[i]=='\n' || buf[i]=='\r') buf[i]='\0';

	if ((colon2=xstrstr(p, " :")))
		*colon2 = '\0';

	args = array_make(OMITCOLON(p), " ", 0, 1, 0);

	if (colon2) {
		*colon2 = ' ';
		array_add(&args, xstrdup(colon2+2));
	}

#define prefix pfxcmd[0]
#define pfx_nick pfxcmd[1]
#define pfx_ihost pfxcmd[2]
#define cmdname pfxcmd[3]

	/* prefix is optional... */
	if (':' != *buf) {
		array_add(&pfxcmd, g_strdup(""));	// prefix
		array_add(&pfxcmd, g_strdup(""));	// pfx_nick
		array_add(&pfxcmd, g_strdup(""));	// pfx_ihost
	} else {
		array_add(&pfxcmd, array_shift(&args));						// prefix
		p = xstrchr(pfxcmd[0], '!');
		array_add(&pfxcmd, p ? g_strndup(pfxcmd[0], p-pfxcmd[0]) : g_strdup(""));	// pfx_nick
		array_add(&pfxcmd, p ? g_strdup(p+1) : g_strdup(""));				// pfx_ihost
	}

	cmd = array_shift(&args);
	array_add(&pfxcmd, cmd);		// cmdname

	/* debug only nasty hack ;> */
#ifdef GDEBUG
	/* mg: well, it's not the exact data sent, but color is needed indeed */
	i=0;
	if (*pfxcmd[0]) debug_iorecv("[%s]", pfxcmd[0]);
	debug_iorecv("[%s]", cmd);
	while (args[i] != NULL) debug_iorecv("[%s]",args[i++]);
	debug_iorecv("\n");
#endif

	n_params = g_strv_length(args);
	if (xstrlen(cmd) > 1) {
		if(!gatoi(cmd, &ecode)) {
			/* for scripts */
			char *emitname = saprintf("irc-protocol-numeric %s", cmd);
			if ((query_emit(NULL, "irc-protocol-numeric", &s->uid, &ecode, &args) == -1) ||
			    (query_emit(NULL, emitname, &s->uid, &args) == -1))
			{
				xfree(emitname);
				g_strfreev(pfxcmd);
				g_strfreev(args);
				return -1;
			}
			xfree(emitname);

			c=0;
			while(irccommands[c].type != -1) {
				if (irccommands[c].type == 1 && irccommands[c].num == ecode) {
					if (irccommands[c].min_params > n_params) {
						debug_error("[irc] parse_line() Not enough parameters! cmd=%s, n=%d, min=%d\n",
								cmd, n_params, irccommands[c].min_params);
					} else
					/* I'm sending c not ecode!!!! */
					if ((*(irccommands[c].handler))(s, j, c, pfxcmd, args) == -1 ) {
						debug_error("[irc] parse_line() error while executing handler!\n");
					}
					/* GiM: XXX I don't expect more,
					 * then one handler on list... */
					break;
				}
				c++;
			}
#ifdef GDEBUG
			if (irccommands[c].type == -1) {
				debug("trying default handler\n");
				if ((*(irccommands[0].handler))(s, j, 0, pfxcmd, args) == -1 ) {
					debug("[irc] parse_line() error while executing handler!\n");
				}

			}
#endif
		} else {
			c=0;
			while(irccommands[c].type != -1) {
				if (irccommands[c].type == 0 && !xstrcmp(irccommands[c].comm, cmd)) {
					if (irccommands[c].min_params > n_params) {
						debug_error("[irc] parse_line() Not enough parameters! cmd=%s, n=%d, min=%d\n",
								cmd, n_params, irccommands[c].min_params);
					} else
					/* dj: instead of  ecode,    c; */
					if ((*(irccommands[c].handler))(s, j, c, pfxcmd, args) == -1 ) {
						debug_error("[irc] parse_line() error while executing handler!\n");
					}
					break;
				}
				c++;
			}
		}
	}

	g_strfreev(pfxcmd);
	g_strfreev(args);
	return 0;
}
Esempio n. 27
0
static COMMAND(sniff_command_connect) {
	struct bpf_program fp;
	char errbuf[PCAP_ERRBUF_SIZE] = { 0 };
	pcap_t *dev;
	const char *filter;
	char *device;
	char *tmp;

	filter = session_get(session, "filter");

	if (session_connected_get(session)) {
		printq("already_connected", session_name(session));
		return -1;
	}

	if (session->uid[6] != '/') {
		if ((tmp = xstrchr(session->uid+6, ':')))
			device = xstrndup(session->uid+6, tmp-(session->uid+6));
		else	device = xstrdup(session->uid+6);

		dev = pcap_open_live(device, SNAPLEN, PROMISC, 1000, errbuf);
	} else {
		device = xstrdup(session->uid+6);
		dev = pcap_open_offline(device, errbuf);
	}

	if (!dev) {
		debug_error("Couldn't open dev: %s (%s)\n", device, errbuf);
		printq("conn_failed", errbuf, session_name(session));
		xfree(device);
		return -1;
	}

	if (pcap_setnonblock(dev, 1, errbuf) == -1) {
		debug_error("Could not set device \"%s\" to non-blocking: %s\n", device, errbuf);
		pcap_close(dev);
		xfree(device);
		return -1;
	}

	xfree(device);
	if (filter && *filter) {
		if (pcap_compile(dev, &fp, (char *) filter, 0, 0 /*net*/) == -1) {
			debug_error("Couldn't parse filter %s: %s\n", filter, pcap_geterr(dev));
			pcap_close(dev);
			return -1;
		}

		if (pcap_setfilter(dev, &fp) == -1) {
			debug_error("Couldn't install filter %s: %s\n", filter, pcap_geterr(dev));
			pcap_close(dev);
			return -1;
		}
		/* pcap_freecode(&fp); */
	}

	session->priv = dev;
	
	switch (pcap_datalink(dev)) {
		case DLT_LINUX_SLL:
			watch_add_session(session, pcap_fileno(dev), WATCH_READ, sniff_pcap_read_SLL);
			break;

		case DLT_EN10MB:
			watch_add_session(session, pcap_fileno(dev), WATCH_READ, sniff_pcap_read_EN10MB);
			break;

		default:
			debug_error("_connect() unk: %s\n", pcap_datalink_val_to_name(pcap_datalink(dev)));
			watch_add_session(session, pcap_fileno(dev), WATCH_READ, sniff_pcap_read);
	}
	

	session->status = EKG_STATUS_AVAIL;
	protocol_connected_emit(session);
	return 0;
}
Esempio n. 28
0
int _file_read_uint32s(char* file_path, uint32_t** pvalues, int* pnb)
{
	int rc;
	int fd;

	size_t fsize;
	char* buf;
	char* p;

	uint32_t* pa=NULL;
	int i;

	/* check input pointers */
	if (pvalues == NULL || pnb == NULL)
		return XCGROUP_ERROR;

	/* open file for reading */
	fd = open(file_path, O_RDONLY, 0700);
	if (fd < 0) {
		debug2("%s: unable to open '%s' for reading : %m",
			__func__, file_path);
		return XCGROUP_ERROR;
	}

	/* get file size */
	fsize =_file_getsize(fd);
	if (fsize == -1) {
		close(fd);
		return XCGROUP_ERROR;
	}

	/* read file contents */
	buf = (char*) xmalloc((fsize+1)*sizeof(char));
	do {
		rc = read(fd, buf, fsize);
	} while (rc < 0 && errno == EINTR);
	close(fd);
	buf[fsize]='\0';

	/* count values (splitted by \n) */
	i=0;
	if (rc > 0) {
		p = buf;
		while (xstrchr(p, '\n') != NULL) {
			i++;
			p = xstrchr(p, '\n') + 1;
		}
	}

	/* build uint32_t list */
	if (i > 0) {
		pa = (uint32_t*) xmalloc(sizeof(uint32_t) * i);
		p = buf;
		i = 0;
		while (xstrchr(p, '\n') != NULL) {
			sscanf(p, "%u", pa+i);
			p = xstrchr(p, '\n') + 1;
			i++;
		}
	}

	/* free buffer */
	xfree(buf);

	/* set output values */
	*pvalues = pa;
	*pnb = i;

	return XCGROUP_SUCCESS;
}
Esempio n. 29
0
struct sas_map *
sas_map_form(const unsigned char *form, int *maplen)
{
  unsigned char *tmp = NULL, *s = NULL;
  struct sas_map *maps;
  int i, postdet_flag;

  if (!form)
    return NULL;

  tmp = malloc(strlen((const char *)form)+1);

  if (verbose)
    sas_debug = 1;

  xstrcpy(tmp,form);
  for (i = 1, s = tmp; *s; ++s)
    {
      if (*s == '-')
	++i;
      else if ((*s == '}' && s[1]  && s[1] != '-') /* predet */
	       || (*s == '{' && s > tmp && s[-1] != '-') /* postdet */)
	++i;
    }

  maps = malloc((i+1)*sizeof(struct sas_map));
  i = postdet_flag = 0;
  s = tmp;
  do
    {
      if (*s == '{')
	{
	  maps[i].det = (postdet_flag ? 1 : -1);
	  *s++ = '\0';
	  maps[i].v = s;
	  s = xstrchr(s,'}');
	  if (s)
	    {
	      *s++ = '\0';
	      if (*s == '-')
		{
		  *s++ = '\0';
		  postdet_flag = 0;
		}
	      else if (*s == '{')
		postdet_flag = (maps[i].det == 1 ? 1 : 0);
	      else
		postdet_flag = 0;
	      ++i;
	    }
	  else
	    {
	      /* FIXME? Warn about missing } ? */
	      goto ret;
	    }
	}
      else
	{
	  maps[i].det = 0;
	  maps[i++].v = s;
	  while (*s && *s != '-' && *s != '{')
	    ++s;
	  if (*s == '-')
	    *s++ = '\0';
	  else if (*s == '{')
	    postdet_flag = 1;
	  /* else *s == '\0', do nothing */
	}
    }
  while (*s);

 ret:
  maps[i].v = NULL;
  if (maplen)
    *maplen = i;

  return maps;
}
Esempio n. 30
0
int
main(int argc, char **argv) {
#else
int
xpath_locator(int argc, char **argv) {
#endif

    if (argc < 2) {
        fprintf(stderr, "Need to specify an input filename.\n"
            "Usage: xpath_locator file.xml xpath1 xpath2 ...\n");
        exit(1);
    }
    char *xml_filename = argv[1];

    num_xpaths = argc - 2;

    xpath_finders = (XPathFinder *) mmalloc(num_xpaths * sizeof(XPathFinder));

    for (int xpath_num = 0; xpath_num < num_xpaths; ++xpath_num) {
        xmlChar *xpath_expr = (xmlChar *) argv[xpath_num + 2];
        XPathFinder *xpath_finder = &xpath_finders[xpath_num];
        xpath_finder->original = new_string(xpath_expr);
        xpath_finder->current_level = 0;
        xpath_finder->line_number = 0;
        xpath_finder->column_number = 0;


        escape_uri_slashes(xpath_expr, TRUE);
        int num_segs = xpath_finder->num_segs = count_chars(xpath_expr, '/');

        XPathSegFinder *seg_finders = 
            (XPathSegFinder *) mmalloc(num_segs * sizeof(XPathSegFinder));
        xpath_finder->seg_finders = seg_finders;

        /* Extract each XPath segment */
        xmlChar *seg = xstrtok(xpath_expr, "/");
        int seg_num = 0;
        while (seg != NULL) {
            XPathSegFinder *seg_finder = &seg_finders[seg_num];
            seg_finder->count = 0;

            escape_uri_slashes(seg, FALSE);
            seg_finder->original = new_string(seg);

            // Get the element local name
            xmlChar *lns = starts_with(seg, (const xmlChar *) "*:") ? seg + 2 : seg;
            const xmlChar *bracket = xstrchr(seg, '[');
            if (!bracket) 
                xpath_error(xpath_num, xpath_finder, seg_num, "No bracket found");
            int local_name_len = bracket - lns;
            xmlChar *local_name = seg_finder->local_name = 
                new_string_n(lns, local_name_len);

            if (starts_with(bracket + 1, (const xmlChar *) "namespace-uri()=")) {
                const xmlChar *ns_start = bracket + 18;
                const xmlChar *ns_end = xstrchr(ns_start, '\'');
                if (!ns_end) 
                    xpath_error(xpath_num, xpath_finder, seg_num, 
                        "No end to the namespace URI");
                seg_finder->namespace_uri = new_string_n(ns_start, ns_end - ns_start);
                bracket = xstrchr(ns_end, '[');
                if (!bracket) 
                    xpath_error(xpath_num, xpath_finder, seg_num, "No position found");
            }
            else {
                seg_finder->namespace_uri = NULL;
            }

            const xmlChar *pos_start = bracket + 1;
            const xmlChar *pos_end = xstrchr(pos_start, ']');
            if (!pos_end) 
                xpath_error(xpath_num, xpath_finder, seg_num, "No closing bracket found");
            size_t pos_str_len = pos_end - pos_start;
            char pos_str[10];
            strncpy(pos_str, (const char *) pos_start, pos_str_len);
            pos_str[pos_str_len] = 0;
            seg_finder->position = strtol(pos_str, NULL, 10);
            if (seg_finder->position <= 0) 
                xpath_error(xpath_num, xpath_finder, seg_num, "Bad position argument");

            seg = xstrtok(NULL, "/");
            seg_num++;
        }
    }


    // Initialize default handler structure for SAX 2
    xmlSAXVersion(handlers, 2);
    handlers->startElementNs = my_startElementNs;
    handlers->endElementNs = my_endElementNs;

    parser_level = 0;  // [c] parser_level is safe
    int res = xmlSAXUserParseFile(handlers, NULL, xml_filename);

    // Output the results
    for (int xpath_num = 0; xpath_num < num_xpaths; ++xpath_num) {
        XPathFinder *xpath_finder = &xpath_finders[xpath_num];
        printf("%d:%d\n", xpath_finder->line_number, xpath_finder->column_number);
    }    


    for (int xpath_num = 0; xpath_num < num_xpaths; ++xpath_num) {
        XPathFinder *xpath_finder = &xpath_finders[xpath_num];
        int num_segs = xpath_finder->num_segs;
        XPathSegFinder *seg_finders = xpath_finder->seg_finders;
        for (int seg_num = 0; seg_num < num_segs; ++seg_num) {
            XPathSegFinder *seg_finder = &seg_finders[seg_num];
            ffree(seg_finder->original);
            ffree(seg_finder->local_name);
            ffree(seg_finder->namespace_uri);
        }

        ffree(xpath_finder->seg_finders);
        ffree(xpath_finder->original);
    }
    ffree(xpath_finders);

    return 0;
}