Esempio n. 1
0
void update_dirfile(const char * dir, const char * name, const char * user){
  dirscan scan = {0};
  ensure_directory("shares/");
  {
    char * dir_filename = fmtstr("shares/%s.dir", name);
    size_t size0;
    void * buf = read_file_to_buffer(dir_filename, &size0);
    if(buf != NULL){
      logd("Size: %i\n", size0);
      scan = dirscan_from_buffer(buf);
      dealloc(buf);
    }
    logd("SCAN: %i\n", scan.cnt);
    udpc_dirscan_update(dir, &scan, false);
    logd("SCAN2: %i\n", scan.cnt);
    size_t size = 0;
    buf = dirscan_to_buffer(scan,&size);
    
    write_buffer_to_file(buf, size, dir_filename);
    dealloc(buf);
  }
  
  {
    void * buffer = NULL;
    size_t cnt = 0;
    udpc_pack_string(dir, &buffer, &cnt);
    udpc_pack_string(name, &buffer, &cnt);
    udpc_pack_string(user, &buffer, &cnt);
    char * shareinfo_filename = fmtstr("shareinfo/%s", name);
    FILE * f = fopen(shareinfo_filename, "w");
    fwrite(buffer, 1, cnt, f);
    fclose(f);
    dealloc(shareinfo_filename);
  }
  
  char * bin_filename = fmtstr("shares/%s.bin", name);
  size_t s = 0;
  void * b = dirscan_to_buffer(scan, &s);
  FILE * f = fopen(bin_filename, "w");
  fwrite(b, 1, s, f);
  fclose(f);
  dealloc(bin_filename);
  
  char * filename = fmtstr("shares/%s.json", name);
  FILE * jsonfile = fopen(filename, "w");
  fprintf(jsonfile, "{\"dir\": \"%s\", \"files\": [\n", dir);
  for(size_t i = 0; i < scan.cnt; i++){
    fprintf(jsonfile, "{ \"path\": \"%s\", \"md5\":\"", scan.files[i]);
    udpc_fprintf_md5(jsonfile, scan.md5s[i]);
    if(i != scan.cnt -1){
      fprintf(jsonfile, "\"},\n");
    }else{
      fprintf(jsonfile, "\"}\n");
    }
  }
  fprintf(jsonfile, "]}\n");
  fclose(jsonfile);
  dealloc(filename);
}
Esempio n. 2
0
STATIC void
synexpect(int token)
{
	char msg[64];

	if (token >= 0) {
		fmtstr(msg, 64, "%s unexpected (expecting %s)",
			tokname[lasttoken], tokname[token]);
	} else {
		fmtstr(msg, 64, "%s unexpected", tokname[lasttoken]);
	}
	synerror(msg);
}
Esempio n. 3
0
/*
 * Expand arithmetic expression.
 */
static char *
expari(char *p, int flag, struct worddest *dst)
{
	char *q, *start;
	arith_t result;
	int begoff;
	int quoted;
	int adj;

	quoted = *p++ == '"';
	begoff = expdest - stackblock();
	p = argstr(p, 0, NULL);
	STPUTC('\0', expdest);
	start = stackblock() + begoff;

	q = grabstackstr(expdest);
	result = arith(start);
	ungrabstackstr(q, expdest);

	start = stackblock() + begoff;
	adj = start - expdest;
	STADJUST(adj, expdest);

	CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
	fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
	adj = strlen(expdest);
	STADJUST(adj, expdest);
	if (!quoted)
		reprocess(expdest - adj - stackblock(), flag, VSNORMAL, 0, dst);
	return p;
}
Esempio n. 4
0
static bool add_connection(web_context * ctx, const char * name,
			   const char * service, const char * path ){
  size_t * size = &ctx->connection_cnt;
  connection** conns = &ctx->active_connections;
  size_t presize = *size;
  if(get_connection_by_name(ctx, name) != NULL){
    ERROR("Name already used by other connection\n");
    return false;
  }
  *conns = realloc(*conns, sizeof(connection) * (presize + 1));
  (*conns)[presize] = (connection){ fmtstr("%s", name), fmtstr("%s", service), fmtstr("%s",path), (iron_process){0}};
  *size += 1;
  const char * args[] = {"share", service, path};
  ASSERT(0 == iron_process_run("./share", args, &conns[presize]->share_proc));
  return true;	   
}
Esempio n. 5
0
File: var.c Progetto: 0xffea/MINIX3
void
initvar(void)
{
	char ppid[20];
	const struct varinit *ip;
	struct var *vp;
	struct var **vpp;

	for (ip = varinit ; (vp = ip->var) != NULL ; ip++) {
		if ((vp->flags & VEXPORT) == 0) {
			vpp = hashvar(ip->text);
			vp->next = *vpp;
			*vpp = vp;
			vp->text = ip->text;
			vp->flags = ip->flags;
			vp->func = ip->func;
		}
	}
	/*
	 * PS1 depends on uid
	 */
	if ((vps1.flags & VEXPORT) == 0) {
		vpp = hashvar("PS1=");
		vps1.next = *vpp;
		*vpp = &vps1;
		vps1.text = geteuid() ? "PS1=$ " : "PS1=# ";
		vps1.flags = VSTRFIXED|VTEXTFIXED;
	}
	if ((vppid.flags & VEXPORT) == 0) {
		fmtstr(ppid, sizeof(ppid), "%d", (int)getppid());
		setvarsafe("PPID", ppid, 0);
	}
}
Esempio n. 6
0
/*
 * Expand arithmetic expression.
 * Note that flag is not required as digits never require CTLESC characters.
 */
static char *
expari(char *p)
{
	char *q, *start;
	arith_t result;
	int begoff;
	int quoted;
	int adj;

	quoted = *p++ == '"';
	begoff = expdest - stackblock();
	p = argstr(p, 0);
	removerecordregions(begoff);
	STPUTC('\0', expdest);
	start = stackblock() + begoff;

	q = grabstackstr(expdest);
	result = arith(start);
	ungrabstackstr(q, expdest);

	start = stackblock() + begoff;
	adj = start - expdest;
	STADJUST(adj, expdest);

	CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
	fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
	adj = strlen(expdest);
	STADJUST(adj, expdest);
	if (!quoted)
		recordregion(begoff, expdest - stackblock(), 0);
	return p;
}
Esempio n. 7
0
char * get_exe_path(){

  char pBuf[100];
  int bytes = GetModuleFileName(NULL, pBuf, array_count(pBuf)));
  ASSERT(bytes > 0);
 return fmtstr("%s",pBuf);
#else
char * get_exe_path(){
  char szTmp[32];
  char pBuf[100];
  memset(pBuf,0,sizeof(pBuf));
  sprintf(szTmp, "/proc/%d/exe", getpid());
  int bytes = readlink(szTmp, pBuf, 100);
  ASSERT(bytes > 0);
  return fmtstr("%s", pBuf);
#endif
}
Esempio n. 8
0
char *strsignal(int sig)
{
	static char buf[19];

	if ((unsigned)sig < NSIG && sys_siglist[sig])
		return (char *)sys_siglist[sig];
	fmtstr(buf, sizeof(buf), "Signal %d", sig);
	return buf;
}
Esempio n. 9
0
/*
 * Expand arithmetic expression.  Backup to start of expression,
 * evaluate, place result in (backed up) result, adjust string position.
 */
void
expari(int flag)
{
	char *p, *start;
	intmax_t result;
	int adjustment;
	int begoff;
	int quotes = flag & (EXP_FULL | EXP_CASE);
	int quoted;

	/*	ifsfree(); */

	/*
	 * This routine is slightly over-complicated for
	 * efficiency.  First we make sure there is
	 * enough space for the result, which may be bigger
	 * than the expression if we add exponentation.  Next we
	 * scan backwards looking for the start of arithmetic.  If the
	 * next previous character is a CTLESC character, then we
	 * have to rescan starting from the beginning since CTLESC
	 * characters have to be processed left to right.
	 */
/* SPACE_NEEDED is enough for all digits, plus possible "-", plus 2 (why?) */
#define SPACE_NEEDED ((sizeof(intmax_t) * CHAR_BIT + 2) / 3 + 1 + 2)
	CHECKSTRSPACE((int)(SPACE_NEEDED - 2), expdest);
	USTPUTC('\0', expdest);
	start = stackblock();
	p = expdest - 1;
	while (*p != CTLARI && p >= start)
		--p;
	if (*p != CTLARI)
		error("missing CTLARI (shouldn't happen)");
	if (p > start && *(p-1) == CTLESC)
		for (p = start; *p != CTLARI; p++)
			if (*p == CTLESC)
				p++;

	if (p[1] == '"')
		quoted=1;
	else
		quoted=0;
	begoff = p - start;
	removerecordregions(begoff);
	if (quotes)
		rmescapes(p+2);
	result = arith(p+2);
	fmtstr(p, SPACE_NEEDED, "%"PRIdMAX, result);

	while (*p++)
		;

	if (quoted == 0)
		recordregion(begoff, p - 1 - start, 0);
	adjustment = expdest - p + 1;
	STADJUST(-adjustment, expdest);
}
Esempio n. 10
0
/*
 * Expand arithmetic expression.  Backup to start of expression,
 * evaluate, place result in (backed up) result, adjust string position.
 */
void
expari(shinstance *psh, int flag)
{
	char *p, *start;
	int result;
	int begoff;
	int quotes = flag & (EXP_FULL | EXP_CASE);
	int quoted;

	/*	ifsfree(); */

	/*
	 * This routine is slightly over-complicated for
	 * efficiency.  First we make sure there is
	 * enough space for the result, which may be bigger
	 * than the expression if we add exponentation.  Next we
	 * scan backwards looking for the start of arithmetic.  If the
	 * next previous character is a CTLESC character, then we
	 * have to rescan starting from the beginning since CTLESC
	 * characters have to be processed left to right.
	 */
#if INT_MAX / 1000000000 >= 10 || INT_MIN / 1000000000 <= -10
#error "integers with more than 10 digits are not supported"
#endif
	CHECKSTRSPACE(psh, 12 - 2, psh->expdest);
	USTPUTC(psh, '\0', psh->expdest);
	start = stackblock(psh);
	p = psh->expdest - 1;
	while (*p != CTLARI && p >= start)
		--p;
	if (*p != CTLARI)
		error(psh, "missing CTLARI (shouldn't happen)");
	if (p > start && *(p-1) == CTLESC)
		for (p = start; *p != CTLARI; p++)
			if (*p == CTLESC)
				p++;

	if (p[1] == '"')
		quoted=1;
	else
		quoted=0;
	begoff = (int)(p - start);
	removerecordregions(psh, begoff);
	if (quotes)
		rmescapes(psh, p+2);
	result = arith(psh, p+2);
	fmtstr(p, 12, "%d", result);

	while (*p++)
		;

	if (quoted == 0)
		recordregion(psh, begoff, (int)(p - 1 - start), 0);
	result = (int)(psh->expdest - p + 1);
	STADJUST(psh, -result, psh->expdest);
}
Esempio n. 11
0
char *
errmsg(e, action) {
      struct errname const *ep;
      static char buf[12];

      for (ep = errormsg ; ep->errcode ; ep++) {
	    if (ep->errcode == e && (ep->action & action) != 0)
		  return ep->msg;
      }
      fmtstr(buf, sizeof buf, "error %d", e);
      return buf;
}
Esempio n. 12
0
/*
 * Expand arithmetic expression.  Backup to start of expression,
 * evaluate, place result in (backed up) result, adjust string position.
 */
void
expari(int flag)
{
	char *p, *q, *start;
	arith_t result;
	int begoff;
	int quotes = flag & (EXP_FULL | EXP_CASE | EXP_REDIR);
	int quoted;

	/*
	 * This routine is slightly over-complicated for
	 * efficiency.  First we make sure there is
	 * enough space for the result, which may be bigger
	 * than the expression.  Next we
	 * scan backwards looking for the start of arithmetic.  If the
	 * next previous character is a CTLESC character, then we
	 * have to rescan starting from the beginning since CTLESC
	 * characters have to be processed left to right.
	 */
	CHECKSTRSPACE(DIGITS(result) - 2, expdest);
	USTPUTC('\0', expdest);
	start = stackblock();
	p = expdest - 2;
	while (p >= start && *p != CTLARI)
		--p;
	if (p < start || *p != CTLARI)
		error("missing CTLARI (shouldn't happen)");
	if (p > start && *(p - 1) == CTLESC)
		for (p = start; *p != CTLARI; p++)
			if (*p == CTLESC)
				p++;

	if (p[1] == '"')
		quoted=1;
	else
		quoted=0;
	begoff = p - start;
	removerecordregions(begoff);
	if (quotes)
		rmescapes(p+2);
	q = grabstackstr(expdest);
	result = arith(p+2);
	ungrabstackstr(q, expdest);
	fmtstr(p, DIGITS(result), ARITH_FORMAT_STR, result);
	while (*p++)
		;
	if (quoted == 0)
		recordregion(begoff, p - 1 - start, 0);
	result = expdest - p + 1;
	STADJUST(-result, expdest);
}
Esempio n. 13
0
/*
 * Expand arithmetic expression.
 * Note that flag is not required as digits never require CTLESC characters.
 */
static char *
expari(char *p)
{
    char *q, *start;
    arith_t result;
    int begoff;
    int quoted;
    int c;
    int nesting;
    int adj;

    quoted = *p++ == '"';
    begoff = expdest - stackblock();
    argstr(p, 0);
    removerecordregions(begoff);
    STPUTC('\0', expdest);
    start = stackblock() + begoff;

    q = grabstackstr(expdest);
    result = arith(start);
    ungrabstackstr(q, expdest);

    start = stackblock() + begoff;
    adj = start - expdest;
    STADJUST(adj, expdest);

    CHECKSTRSPACE((int)(DIGITS(result) + 1), expdest);
    fmtstr(expdest, DIGITS(result), ARITH_FORMAT_STR, result);
    adj = strlen(expdest);
    STADJUST(adj, expdest);
    if (!quoted)
        recordregion(begoff, expdest - stackblock(), 0);
    nesting = 1;
    while (nesting > 0) {
        c = *p++;
        if (c == CTLESC)
            p++;
        else if (c == CTLARI)
            nesting++;
        else if (c == CTLENDARI)
            nesting--;
        else if (c == CTLVAR)
            p++; /* ignore variable substitution byte */
        else if (c == '\0')
            return p - 1;
    }
    return p;
}
Esempio n. 14
0
void
init() {

      /* from input.c: */
      {
	      basepf.nextc = basepf.buf = basebuf;
      }

      /* from trap.c: */
      {
	      signal(SIGCHLD, SIG_DFL);
      }

      /* from output.c: */
      {
#ifdef USE_GLIBC_STDIO
	      initstreams();
#endif
      }

      /* from var.c: */
      {
	      char **envp;
	      static char ppid[32] = "PPID=";
	      const char *p;
	      struct stat st1, st2;

	      initvar();
	      for (envp = environ ; *envp ; envp++) {
		      if (strchr(*envp, '=')) {
			      setvareq(*envp, VEXPORT|VTEXTFIXED);
		      }
	      }

	      fmtstr(ppid + 5, sizeof(ppid) - 5, "%ld", (long) getppid());
	      setvareq(ppid, VTEXTFIXED);

	      p = lookupvar("PWD");
	      if (p)
		      if (*p != '/' || stat(p, &st1) || stat(".", &st2) ||
			  st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino)
			      p = 0;
	      setpwd(p, 0);
      }
}
Esempio n. 15
0
void parse_args(char * argv[], int cnt){
  exec_path = get_exe_path();
  for(int i = 1; i < cnt; i++){
    char * arg = argv[i];
    bool is_test = strcmp(arg,"--test") == 0;
    if(is_test){
      run_test = true;
      continue;
    }
    bool compile_out = strcmp(arg,"--compile-out") == 0;
    if(compile_out){
      i++;
      c_compile_out = fmtstr("%s",argv[i]);
      continue;
    }
    file_to_run = argv[i];
  }
}
Esempio n. 16
0
/* ---------------------------  calculate elapsed time ------------------- */
elapsed_time( int mode, char *timebuf )
{
	//int		tottime ;			/* store total time */
	int		hrs ;
	int		min ;
	int		sec ;

	if ( Fm.fc_eltimet[mode] == 0)
		return(0);
	else
	{
		hrs = Fm.fc_eltimet[mode] / 3600;
		sec = Fm.fc_eltimet[mode] % 3600;
		min = sec / 60;
		sec %= 60;
		fmtstr(timebuf,"%d:%02d:%02d",hrs,min,sec);
	}
	return(1);
}
Esempio n. 17
0
static CMPIString *
get_exc_trace(const CMPIBroker* broker)
{
  VALUE exception = rb_gv_get("$!"); /* get last exception */
  VALUE reason = rb_funcall(exception, rb_intern("to_s"), 0 );
  VALUE trace = rb_gv_get("$@"); /* get last exception trace */
  VALUE backtrace;
  char* tmp;
  CMPIString *result;

  if (NIL_P(exception)) {
    return NULL;
  }
  backtrace = rb_funcall(trace, rb_intern("join"), 1, rb_str_new("\n\t", 2));
  tmp = fmtstr("%s\n\t%s", StringValuePtr(reason), StringValuePtr(backtrace)); 
  result = broker->eft->newString(broker, tmp, NULL); 
  free(tmp);
  return result;
}
Esempio n. 18
0
File: jobs.c Progetto: 0xffea/MINIX3
int
bgcmd(int argc, char **argv)
{
	char s[64];
	struct job *jp;

	do {
		jp = getjob(*++argv);
		if (jp->jobctl == 0)
			error("job not created under job control");
		if (jp->state == JOBDONE)
			continue;
		restartjob(jp);
		jp->foreground = 0;
		fmtstr(s, 64, "[%td] ", jp - jobtab + 1);
		out1str(s);
		out1str(jp->ps[0].cmd);
		out1c('\n');
	} while (--argc > 1);
	return 0;
}
Esempio n. 19
0
int web_main(void * _ed, struct MHD_Connection * con, const char * url,
		      const char * method, const char * version,
		      const char *upload_data, size_t * upload_data_size,
		     void ** con_cls){
  UNUSED(url); UNUSED(version); UNUSED(upload_data); UNUSED(upload_data_size);
  UNUSED(method); UNUSED(con_cls); UNUSED(_ed);
  const char * file = "page.html";

  bool style_loc = strcmp((char *) url + 1, "style.css") == 0;
  if(style_loc)
    file = "style.css";
  else if(0 == strcmp((char *) url + 1, (char *) "favicon.png"))
    file = "favicon.png";
  
  char fnamebuffer[100];
  logd("'%s' %s %s %i\n", url, method, version, upload_data_size);
  logd("File: %s\n", file);
  if(url == strstr(url, "/sharesinfo")){
    // Send back json code describing all the available shares.

    file = "shareinfo_data";
    
    dirscan dir = scan_directories("shareinfo");
    
    FILE * outfile = fopen(file, "w");
    fprintf(outfile, "[");
    for(size_t i = 0; i < dir.cnt; i++){
      logd("looking in: %s\n", dir.files[i]);
      char fnamebuffer2[100];
      sprintf(fnamebuffer2, "shareinfo/%s", dir.files[i]);
      void * rdbuffer = read_file_to_string(fnamebuffer2);
      ASSERT(rdbuffer != NULL);
      void *ptr = rdbuffer;
      char * dirname = udpc_unpack_string(&ptr);
      char * name = udpc_unpack_string(&ptr);
      char * user = udpc_unpack_string(&ptr);
      fprintf(outfile, "{\"path\": \"%s\", \"name\":\"%s\", \"user\":\"%s\"}%s\n",dirname, name, user, (i == dir.cnt -1) ? "" : ",");
      dealloc(rdbuffer);
    }
    fprintf(outfile, "]");
    fclose(outfile);
    dirscan_clean(&dir);
  }else if(url == strstr(url,"/shares/")){
    // fetch the active shares item inside the shares folder
    
    char * shareid = (char *) url + strlen("/shares/");
    logd("Shareid: %s\n", shareid);
    char * shareinfo_filename = fmtstr("shareinfo/%s", shareid);
    void * buffer = read_file_to_string(shareinfo_filename);
    if(buffer == NULL)
      goto error;
    void * bufptr = buffer;
    char * dir = udpc_unpack_string(&bufptr);
    char * name = udpc_unpack_string(&bufptr);
    char * user = udpc_unpack_string(&bufptr);
    service_descriptor sd;
    if(!udpc_get_service_descriptor(user, &sd)){
      logd("Unable to parse service name: '%s'\n", user);
      dealloc(buffer);
      goto error;
    }

    logd("path: %s, name: %s, user: %s\n", dir, name, user);
    update_dirfile(dir, name, user);
    sprintf(fnamebuffer, "shares/%s.json", name);
    dealloc(buffer);
    logd("Sending: %s\n", fnamebuffer);
    file = fnamebuffer;
  }
  if(strcmp(url, "/add_share") == 0){ 
    const char * path = MHD_lookup_connection_value(con, MHD_GET_ARGUMENT_KIND, "path");
    const char * name = MHD_lookup_connection_value(con, MHD_GET_ARGUMENT_KIND, "name");
    const char * user = MHD_lookup_connection_value(con, MHD_GET_ARGUMENT_KIND, "user");
    logd("path: %s, name: %s, user: %s\n", path, name, user);
    if(path == NULL || name == NULL || user == NULL){
      goto error;
    }
    service_descriptor sd;
    if(!udpc_get_service_descriptor(user, &sd)){
      logd("Unable to parse service name: '%s'\n", user);
      goto error;
    }
    logd("Service descriptor seems ok \n");
    ensure_directory("shareinfo/");
    char * sharepath = fmtstr("shareinfo/%s", name);
    struct stat filest;
    stat(sharepath, &filest);
    dealloc(sharepath);
    
    if(S_ISREG(filest.st_mode)){
      logd("File exists!\n");
    }else{
      struct stat dirst;
      stat(path, &dirst);
      if(!S_ISDIR(dirst.st_mode)){
	logd("Dir does not exist.. creating a new one..\n");
	int path_len = strlen(path);
	if(path[path_len] !='/'){
	  char * npath = fmtstr("%s/", path);
	  ensure_directory(npath);
	  dealloc(npath);
	}else{
	  ensure_directory(path);
	}
      }
      logd("Updating dirfile!\n");
      update_dirfile(path, name, user);
      logd("Done..\n");
    }
    const char * r = "\"OK\"";
    struct MHD_Response * response = MHD_create_response_from_data(strlen(r),
								   (void *) r,
								   0,
								   MHD_NO);
    int ret = MHD_queue_response(con, MHD_HTTP_OK, response);
    MHD_destroy_response(response);
    return ret;
  }

  size_t filesize = 0;
  void * pg = read_file_to_buffer(file, &filesize);
  struct MHD_Response * response = MHD_create_response_from_data(filesize,
					   pg,
					   1,
					   MHD_NO);
  int ret = MHD_queue_response(con, MHD_HTTP_OK, response);
  MHD_destroy_response(response);
  return ret;

 error:;
  const char * error_str = "<html><body>400</body></html>";
  response = MHD_create_response_from_data(strlen(error_str) + 1,
					   (void *) error_str,
					   0,
					   MHD_NO);
  ret = MHD_queue_response(con, MHD_HTTP_BAD_REQUEST, response);
  MHD_destroy_response(response);
  return ret;
}
Esempio n. 20
0
// вызываем функцию на lua
// указываем тип входящих аргументов через d(oble),i(nteger),s(tring)
// символ > отделяет аргументы входащих от результата
//void call_va(lua_State *L, const char *func, const char *sig, ...) {
//int cbsdlua_funccmd(const char *func, const char *sig, ...) {
int cbsdlua_funccmd(int argc, char **argv) {
//const char *func, const char *sig, ...) {
	char *func=argv[1];
	char *sig=argv[2];

	int narg, nres, npos;
	lua_getglobal(L,func);

//	out2fmt_flush("func: %s\n", func);

	//push args
	for (narg=0; *sig; narg++ ) {
		npos=3 + narg; // 3 -$0, func, sig
		luaL_checkstack(L, 1, "too many arguments");
		switch (*sig++) {
			case 'd': /* double */
//				lua_pushnumber(L, va_arg(vl,double));
				break;
			case 'i': /* integer */
				lua_pushinteger(L, atoi(argv[npos]));
				break;
			case 's': /* string */
				lua_pushstring(L, argv[npos]);
				break;
			case '>': /* end of argument */
				goto endargs;
			default:
				cbsdlua_error(L,"invalid option (%c)", *(sig - 1 ));
		}
	}

	endargs:

	nres=strlen(sig);
	if (lua_pcall(L, narg, nres, 0)!= 0)
		cbsdlua_error(L, "error calling '%s': %s",func, lua_tostring(L,-1));

	//get result
	nres = -nres;
	while (*sig) {
		switch (*sig++) {
			case 'd': {
				int isnum;
				double n = lua_tonumberx(L, nres, &isnum);
				if (!isnum)
					cbsdlua_error(L,"wrong result type");
//				*va_arg(vl, double *) = n;
				break;
			}
			case 'i': {
				int isnum;
				int n = lua_tointegerx(L, nres, &isnum);
				if (!isnum)
					cbsdlua_error(L,"wrong result type");
//				*va_arg(vl, int *) = n;
//				out2fmt_flush("LUA Return for %s: %d\n", argv[npos], n);
				char str[100];
				fmtstr(str, sizeof(str), "%d", n);
				setvarsafe(argv[npos],str, 0);
				break;
			}
			case 's': {
				const char *s = lua_tostring(L, nres);
				if (s == NULL)
					cbsdlua_error(L,"wrong result type");
//				*va_arg(vl, const char **) = s;
//				out2fmt_flush("LUA Return for %s: %s\n", argv[npos], s);
				setvarsafe(argv[npos],s, 0);
				break;
			}
			default:
				cbsdlua_error(L,"invalid option (%c)", *(sig - 1 ));
		}
	nres++;
	}

	return 0;
}
Esempio n. 21
0
static int
getopts(char *optstr, char *optvar, char **optfirst, char ***optnext,
    char **optptr)
{
	char *p, *q;
	char c = '?';
	int done = 0;
	int ind = 0;
	int err = 0;
	char s[10];
	const char *newoptarg = NULL;

	if ((p = *optptr) == NULL || *p == '\0') {
		/* Current word is done, advance */
		if (*optnext == NULL)
			return 1;
		p = **optnext;
		if (p == NULL || *p != '-' || *++p == '\0') {
atend:
			ind = *optnext - optfirst + 1;
			*optnext = NULL;
			p = NULL;
			done = 1;
			goto out;
		}
		(*optnext)++;
		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
			goto atend;
	}

	c = *p++;
	for (q = optstr; *q != c; ) {
		if (*q == '\0') {
			if (optstr[0] == ':') {
				s[0] = c;
				s[1] = '\0';
				newoptarg = s;
			}
			else
				out2fmt_flush("Illegal option -%c\n", c);
			c = '?';
			goto out;
		}
		if (*++q == ':')
			q++;
	}

	if (*++q == ':') {
		if (*p == '\0' && (p = **optnext) == NULL) {
			if (optstr[0] == ':') {
				s[0] = c;
				s[1] = '\0';
				newoptarg = s;
				c = ':';
			}
			else {
				out2fmt_flush("No arg for -%c option\n", c);
				c = '?';
			}
			goto out;
		}

		if (p == **optnext)
			(*optnext)++;
		newoptarg = p;
		p = NULL;
	}

out:
	if (*optnext != NULL)
		ind = *optnext - optfirst + 1;
	*optptr = p;
	if (newoptarg != NULL)
		err |= setvarsafe("OPTARG", newoptarg, 0);
	else {
		INTOFF;
		err |= unsetvar("OPTARG");
		INTON;
	}
	fmtstr(s, sizeof(s), "%d", ind);
	err |= setvarsafe("OPTIND", s, VNOFUNC);
	s[0] = c;
	s[1] = '\0';
	err |= setvarsafe(optvar, s, 0);
	if (err) {
		*optnext = NULL;
		*optptr = NULL;
		flushall();
		exraise(EXERROR);
	}
	return done;
}
Esempio n. 22
0
File: jobs.c Progetto: 0xffea/MINIX3
STATIC void
showjob(struct job *jp, pid_t pid, int sformat, int lformat)
{
	char s[64];
	struct procstat *ps;
	struct job *j;
	int col, curr, i, jobno, prev, procno;
	char c;

	procno = jp->nprocs;
	jobno = jp - jobtab + 1;
	curr = prev = 0;
#if JOBS
	if ((j = getcurjob(NULL)) != NULL) {
		curr = j - jobtab + 1;
		if ((j = getcurjob(j)) != NULL)
			prev = j - jobtab + 1;
	}
#endif
	for (ps = jp->ps ; ; ps++) {	/* for each process */
		if (sformat) {
			out1fmt("%d\n", (int)ps->pid);
			goto skip;
		}
		if (!lformat && ps != jp->ps && pid == 0)
			goto skip;
		if (pid != 0 && pid != ps->pid)
			goto skip;
		if (jobno == curr && ps == jp->ps)
			c = '+';
		else if (jobno == prev && ps == jp->ps)
			c = '-';
		else
			c = ' ';
		if (ps == jp->ps)
			fmtstr(s, 64, "[%d] %c ", jobno, c);
		else
			fmtstr(s, 64, "    %c ", c);
		out1str(s);
		col = strlen(s);
		if (lformat) {
			fmtstr(s, 64, "%d ", (int)ps->pid);
			out1str(s);
			col += strlen(s);
		}
		s[0] = '\0';
		if (ps != jp->ps) {
			*s = '\0';
		} else if (ps->status == -1) {
			strcpy(s, "Running");
		} else if (WIFEXITED(ps->status)) {
			if (WEXITSTATUS(ps->status) == 0)
				strcpy(s, "Done");
			else
				fmtstr(s, 64, "Done (%d)",
				    WEXITSTATUS(ps->status));
		} else {
#if JOBS
			if (WIFSTOPPED(ps->status)) 
				i = WSTOPSIG(ps->status);
			else
#endif
				i = WTERMSIG(ps->status);
			if ((i & 0x7F) < _NSIG && strsiglist(i & 0x7F))
				scopy(strsiglist(i & 0x7F), s);
			else
				fmtstr(s, 64, "Signal %d", i & 0x7F);
			if (WCOREDUMP(ps->status))
				strcat(s, " (core dumped)");
		}
		out1str(s);
		col += strlen(s);
		do {
			out1c(' ');
			col++;
		} while (col < 30);
		out1str(ps->cmd);
		out1c('\n');
skip:		if (--procno <= 0)
			break;
	}
}
Esempio n. 23
0
/* *********************************************************************** */
edit_out()
{
	int		i,j;
	int		rdl;
	int		totins;			/* get total inserts */
	int		totdel;			/* get total deletes */
	unsigned char fmtwk[9];
	unsigned char timebuf[9];
	unsigned char *pnmwk;

	/* make sure we read the beginning */
	fileseek( Infile, (long)0 ) ;

	/* read into fci struct */
	if ( (rdl = fileread(Infile,&Fm,FCINSIZE) ) <=0)
	{
		disperr("COULD NOT READ %s",Pathbuf);
		return(-1);
	}
	
	charfill(&Bi,sizeof (Bi),' ');
	strncpy_s(Bi.drtdir, sizeof(Bi.drtdir), Fm.fc_drtdir, FILENMSZ);
	strncpy_s(Bi.dname, sizeof(Bi.dname), Fm.fc_dname, FILENMSZ);
	strncpy_s(Bi.dbtch, sizeof(Bi.dbtch), Fm.fc_dbtch, FILENMSZ);
	strncpy_s(Bi.frtdir, sizeof(Bi.frtdir), Fm.fc_frtdir, FILENMSZ);
	strncpy_s(Bi.fname, sizeof(Bi.fname), Fm.fc_fname, FILENMSZ);

	for( i=0 ; i < MAXMODES ; i++ )
	{
		Bi.stat[i] = Status[Fm.fc_stat[i]] ;
		Bi.dopen[i] = Fm.fc_dopen[i] ;
	}

	for( i=0 ; i < MAXIO ; i++ )
	{
		fmtstr(fmtwk,"%02d",Fm.fc_ioiter[i]);
		strncpy_s(Bi.ioiter[i], sizeof(Bi.ioiter[i]), fmtwk, 2);

		if( Fm.fc_iouid[i] > 0 )
		{
			fmtstr( fmtwk, "%03d", Fm.fc_iouid[i] ) ;
			strncpy_s(Bi.iouid[i], sizeof(Bi.iouid[i]), fmtwk, 3);
			if( ( pnmwk = getusrnam( Fm.fc_iouid[i] ) ) != (char *)ERRCODE )
			{
				strncpy_s(Bi.iouname[i], sizeof(Bi.iouname[i]), pnmwk, NMSZ);
			}
			else
			{
				charfill(Bi.iouname[i],NMSZ,'*');
			}
		}
		else
		{
			charfill(Bi.iouid[i],3,'*');
			charfill(Bi.iouname[i],NMSZ,'*');
		}
		Bi.iostatus[i] = Fm.fc_iostatus[i];
	}

	for (i=0; i< MAXMODES;i++)
	{
		fmtstr(fmtwk,"%05d",Fm.fc_rcntt[i]);
		strncpy_s(Bi.rcntt[i], sizeof(Bi.rcntt[i]), fmtwk, 5);

		fmtstr(fmtwk,"%05d",Fm.fc_dcntt[i]);
		strncpy_s(Bi.dcntt[i], sizeof(Bi.dcntt[i]), fmtwk, 5);

		fmtstr(fmtwk,"%08d",Fm.fc_kscntt[i]);
		strncpy_s(Bi.kscntt[i], sizeof(Bi.kscntt[i]), fmtwk, 8);

		fmtstr(fmtwk,"%08d",Fm.fc_kscnttf[i]);
		strncpy_s(Bi.kscnttf[i], sizeof(Bi.kscnttf[i]), fmtwk, 8);

		fmtstr(fmtwk,"%05d",Fm.fc_ercntt[i]);
		strncpy_s(Bi.ercntt[i], sizeof(Bi.ercntt[i]), fmtwk, 5);

		fmtstr(fmtwk,"%08d",Fm.fc_ekscntt[i]);
		strncpy_s(Bi.ekscntt[i],sizeof(Bi.ekscntt[i]) , fmtwk, 8);

		/* error k.s.count of function key */
		fmtstr(fmtwk,"%08d",Fm.fc_ekscnttf[i]);
		strncpy_s(Bi.ekscnttf[i], sizeof(Bi.ekscnttf[i]), fmtwk, 8);

		/* total flag count */
		fmtstr(fmtwk,"%05d",Fm.fc_flgcntt[i]);
		strncpy_s(Bi.flgcntt[i], sizeof(Bi.flgcntt[i]), fmtwk, 5);

		if (Fm.fc_fstime[i] == 0)
			charfill(Bi.fstime[i],24,'*');
		else
			timetostr(Fm.fc_fstime[i],Bi.fstime[i]);

		if (Fm.fc_strtime[i] == 0)
			charfill(Bi.strtime[i],24,'*');
		else
			timetostr(Fm.fc_strtime[i],Bi.strtime[i]);

		if (Fm.fc_lstime[i] == 0)
			charfill(Bi.lstime[i],24,'*');
		else
			timetostr(Fm.fc_lstime[i],Bi.lstime[i]);

		if (elapsed_time(i,timebuf) )   /* calculate total elapsed time */
			strncpy_s(Bi.eltimet[i], sizeof(Bi.eltimet[i]), timebuf, 8);
		else
			charfill(Bi.eltimet[i],8,'*');
	}

	/* # inserts, # deletes */
	totins = Fm.fc_mins[0] + Fm.fc_mins[1];	/* total inserts */
	totdel = Fm.fc_mdel[0] + Fm.fc_mdel[1];	/* total deletes */
	fmtstr(Bi.mins,"%05d",totins);
	fmtstr(Bi.mdel,"%05d",totdel);

	totins = Fm.fc_mdins[0] + Fm.fc_mdins[1];	/* total doc inserts */
	totdel = Fm.fc_mddel[0] + Fm.fc_mddel[1];	/* total doc deletes */
	fmtstr(Bi.mdins,"%05d",totins);
	fmtstr(Bi.mddel,"%05d",totdel);

	for (i=0; i< MAXMODES;i++)
	{
		for (j=0 ;j < MAXUSER;j++)
		{
			if (Fm.fc_muid[j][i] > 0)
		   {
			   fmtstr(fmtwk,"%03d",Fm.fc_muid[j][i]);
			   strncpy_s(Bi.muid[j][i], sizeof(Bi.muid[j][i]), fmtwk, 3);
			   if ( (pnmwk=getusrnam(Fm.fc_muid[j][i]) ) != (char *)ERRCODE)
				{
					strncpy_s(Bi.muidname[j][i], sizeof(Bi.muidname[j][i]), pnmwk, NMSZ);
				}
			     else
				{
					charfill(Bi.muidname[j][i],NMSZ,'*');
				}
			}
			else
			{
				charfill(Bi.muid[j][i],3,'*');
				charfill(Bi.muidname[j][i],NMSZ,'*');
			}
		}
	}

	Bi.sysfile = Fm.fc_sysfile;

	for (i=0; i< MAXMODES;i++)
	{
		fmtstr(fmtwk,"%05d",Fm.fc_iter[i]);
		strncpy_s(Bi.iter[i], sizeof(Bi.iter[i]), fmtwk, 5);
	}

	for (i=0; i< MAXIO;i++)
	{
		fmtstr(fmtwk,"%05d",Fm.fc_iositer[i]);
		strncpy_s(Bi.iositer[i], sizeof(Bi.iositer[i]), fmtwk, 5);

		fmtstr(fmtwk,"%05d",Fm.fc_iorcnt[i]);
		strncpy_s(Bi.iorcnt[i], sizeof(Bi.iorcnt[i]), fmtwk, 5);

		fmtstr(fmtwk,"%05d",Fm.fc_iodcnt[i]);
		strncpy_s(Bi.iodcnt[i], sizeof(Bi.iodcnt[i]), fmtwk, 5);

		if ( Fm.fc_iostime[i] == 0)
			charfill(Bi.iostime[i],24,'*');
		else
			timetostr(Fm.fc_iostime[i],Bi.iostime[i]);

		if (Fm.fc_ioetime[i] == 0)
			charfill(Bi.ioetime[i],24,'*');
		else
			timetostr(Fm.fc_ioetime[i],Bi.ioetime[i]);

		fmtstr(fmtwk,"%05d",Fm.fc_iopen[i]);
		strncpy_s(Bi.iopen[i], sizeof(Bi.iopen[i]), fmtwk, 5);
	}

	Bi.endmark= ' ';
	filewrite(BATCH_infof,&Bi,sizeof (Bi));
	filewrite(BATCH_infof,"\n",1);
	return( 0 ) ;
}
static int 
TargetCall(WsXmlDocH doc, PyObject* instance, 
                 const char* opname, int nargs, ...)
{
    va_list vargs; 
    PyObject *pyargs = NULL; 
    PyObject *pyfunc = NULL; 
    PyObject *result = NULL; 
    WsmanStatus status;
    wsman_status_init(&status);

    pyargs = PyTuple_New(nargs); 
    pyfunc = PyObject_GetAttrString(instance, opname); 
    if (pyfunc == NULL)
    {
        PyErr_Print(); 
        PyErr_Clear(); 
        char* str = fmtstr("Python module does not contain \"%s\"", opname); 
        debug("%s", str); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;

        free(str); 
        goto cleanup; 
    }
    if (! PyCallable_Check(pyfunc))
    {
        char* str = fmtstr("Python module attribute \"%s\" is not callable", 
                opname); 
        debug("%s", str); 
	status.fault_code = WSA_ENDPOINT_UNAVAILABLE;
	status.fault_detail_code = 0;
        free(str); 
        goto cleanup; 
    }
    
    va_start(vargs, nargs); 
    int i; 
    for (i = 0; i < nargs; ++i)
    {
        PyObject* arg = va_arg(vargs, PyObject*); 
        if (arg == NULL)
        {
            arg = Py_None; 
            Py_IncRef(arg); 
        }
        PyTuple_SET_ITEM(pyargs, i, arg); 
    }
    va_end(vargs); 
    result = PyObject_CallObject(pyfunc, pyargs);
    if (PyErr_Occurred())
    {
        status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
        PyErr_Clear(); 
        goto cleanup; 
    }

    if (! PyTuple_Check(result) || 
            (PyTuple_Size(result) != 2 && PyTuple_Size(result) != 1))
    {
        TARGET_THREAD_BEGIN_ALLOW;
        status.fault_msg = fmtstr("Python function \"%s\" didn't return a two-tuple", opname); 
	status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
    }
    PyObject* code = PyTuple_GetItem(result, 0);
    PyObject* detail = Py_None; 
    if (PyTuple_Size(result) == 2)
    {
        detail = PyTuple_GetItem(result, 1); 
    }

    if (! PyInt_Check(code) || (! PyInt_Check(detail) && detail != Py_None))
    {
        TARGET_THREAD_BEGIN_ALLOW;
        status.fault_msg = fmtstr("Python function \"%s\" didn't return a {<int>, <int>) two-tuple", opname); 
	status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
        TARGET_THREAD_END_ALLOW; 
        goto cleanup; 
    }
    status.fault_code = PyInt_AsLong(code); 
    if (detail == Py_None)
    {
	status.fault_code = WSMAN_INTERNAL_ERROR;
	status.fault_detail_code = 0;
    }
    else
    {
        status.fault_detail_code = PyInt_AsLong(detail);
    }
cleanup:
    if (status.fault_code != WSMAN_RC_OK)
      wsman_generate_fault( doc, status.fault_code, status.fault_detail_code, status.fault_msg );
    Py_DecRef(pyargs);
    Py_DecRef(pyfunc);
    Py_DecRef(result);
 
    return status.fault_code != WSMAN_RC_OK; 
}
Esempio n. 25
0
static void
showjob(struct job *jp, int mode)
{
	char s[64];
	char statestr[64];
	struct procstat *ps;
	struct job *j;
	int col, curr, i, jobno, prev, procno;
	char c;

	procno = (mode == SHOWJOBS_PGIDS) ? 1 : jp->nprocs;
	jobno = jp - jobtab + 1;
	curr = prev = 0;
#if JOBS
	if ((j = getcurjob(NULL)) != NULL) {
		curr = j - jobtab + 1;
		if ((j = getcurjob(j)) != NULL)
			prev = j - jobtab + 1;
	}
#endif
	ps = jp->ps + jp->nprocs - 1;
	if (jp->state == 0) {
		strcpy(statestr, "Running");
#if JOBS
	} else if (jp->state == JOBSTOPPED) {
		while (!WIFSTOPPED(ps->status) && ps > jp->ps)
			ps--;
		if (WIFSTOPPED(ps->status))
			i = WSTOPSIG(ps->status);
		else
			i = -1;
		if (i > 0 && i < sys_nsig && sys_siglist[i])
			strcpy(statestr, sys_siglist[i]);
		else
			strcpy(statestr, "Suspended");
#endif
	} else if (WIFEXITED(ps->status)) {
		if (WEXITSTATUS(ps->status) == 0)
			strcpy(statestr, "Done");
		else
			fmtstr(statestr, 64, "Done(%d)",
			    WEXITSTATUS(ps->status));
	} else {
		i = WTERMSIG(ps->status);
		if (i > 0 && i < sys_nsig && sys_siglist[i])
			strcpy(statestr, sys_siglist[i]);
		else
			fmtstr(statestr, 64, "Signal %d", i);
		if (WCOREDUMP(ps->status))
			strcat(statestr, " (core dumped)");
	}

	for (ps = jp->ps ; ; ps++) {	/* for each process */
		if (mode == SHOWJOBS_PIDS || mode == SHOWJOBS_PGIDS) {
			out1fmt("%d\n", (int)ps->pid);
			goto skip;
		}
		if (mode != SHOWJOBS_VERBOSE && ps != jp->ps)
			goto skip;
		if (jobno == curr && ps == jp->ps)
			c = '+';
		else if (jobno == prev && ps == jp->ps)
			c = '-';
		else
			c = ' ';
		if (ps == jp->ps)
			fmtstr(s, 64, "[%d] %c ", jobno, c);
		else
			fmtstr(s, 64, "    %c ", c);
		out1str(s);
		col = strlen(s);
		if (mode == SHOWJOBS_VERBOSE) {
			fmtstr(s, 64, "%d ", (int)ps->pid);
			out1str(s);
			col += strlen(s);
		}
		if (ps == jp->ps) {
			out1str(statestr);
			col += strlen(statestr);
		}
		do {
			out1c(' ');
			col++;
		} while (col < 30);
		if (mode == SHOWJOBS_VERBOSE) {
			out1str(ps->cmd);
			out1c('\n');
		} else
			printjobcmd(jp);
skip:		if (--procno <= 0)
			break;
	}
}
Esempio n. 26
0
static void
showjob(struct output *out, struct job *jp, int mode)
{
	int procno;
	int st;
	struct procstat *ps;
	int col;
	char s[64];

#if JOBS
	if (mode & SHOW_PGID) {
		/* just output process (group) id of pipeline */
		outfmt(out, "%ld\n", (long)jp->ps->pid);
		return;
	}
#endif

	procno = jp->nprocs;
	if (!procno)
		return;

	if (mode & SHOW_PID)
		mode |= SHOW_MULTILINE;

	if ((procno > 1 && !(mode & SHOW_MULTILINE))
	    || (mode & SHOW_SIGNALLED)) {
		/* See if we have more than one status to report */
		ps = jp->ps;
		st = ps->status;
		do {
			int st1 = ps->status;
			if (st1 != st)
				/* yes - need multi-line output */
				mode |= SHOW_MULTILINE;
			if (st1 == -1 || !(mode & SHOW_SIGNALLED) || WIFEXITED(st1))
				continue;
			if (WIFSTOPPED(st1) || ((st1 = WTERMSIG(st1) & 0x7f)
			    && st1 != SIGINT && st1 != SIGPIPE))
				mode |= SHOW_ISSIG;

		} while (ps++, --procno);
		procno = jp->nprocs;
	}

	if (mode & SHOW_SIGNALLED && !(mode & SHOW_ISSIG)) {
		if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE)) {
			TRACE(("showjob: freeing job %d\n", jp - jobtab + 1));
			freejob(jp);
		}
		return;
	}

	for (ps = jp->ps; --procno >= 0; ps++) {	/* for each process */
		if (ps == jp->ps)
			fmtstr(s, 16, "[%ld] %c ",
				(long)(jp - jobtab + 1),
#if JOBS
				jp == jobtab + curjob ? '+' :
				curjob != -1 && jp == jobtab +
					    jobtab[curjob].prev_job ? '-' :
#endif
				' ');
		else
			fmtstr(s, 16, "      " );
		col = strlen(s);
		if (mode & SHOW_PID) {
			fmtstr(s + col, 16, "%ld ", (long)ps->pid);
			     col += strlen(s + col);
		}
		if (ps->status == -1) {
			scopy("Running", s + col);
		} else if (WIFEXITED(ps->status)) {
			st = WEXITSTATUS(ps->status);
			if (st)
				fmtstr(s + col, 16, "Done(%d)", st);
			else
				fmtstr(s + col, 16, "Done");
		} else {
#if JOBS
			if (WIFSTOPPED(ps->status)) 
				st = WSTOPSIG(ps->status);
			else /* WIFSIGNALED(ps->status) */
#endif
				st = WTERMSIG(ps->status);
			st &= 0x7f;
			if (st < NSIG && sys_siglist[st])
				scopyn(sys_siglist[st], s + col, 32);
			else
				fmtstr(s + col, 16, "Signal %d", st);
			if (WCOREDUMP(ps->status)) {
				col += strlen(s + col);
				scopyn(" (core dumped)", s + col,  64 - col);
			}
		}
		col += strlen(s + col);
		outstr(s, out);
		do {
			outc(' ', out);
			col++;
		} while (col < 30);
		outstr(ps->cmd, out);
		if (mode & SHOW_MULTILINE) {
			if (procno > 0) {
				outc(' ', out);
				outc('|', out);
			}
		} else {
			while (--procno >= 0)
				outfmt(out, " | %s", (++ps)->cmd );
		}
		outc('\n', out);
	}
	flushout(out);
	jp->changed = 0;
	if (jp->state == JOBDONE && !(mode & SHOW_NO_FREE))
		freejob(jp);
}
Esempio n. 27
0
STATIC int
getopts(char *optstr, char *optvar, char **optfirst, char ***optnext, char **optpptr)
{
	char *p, *q;
	char c = '?';
	int done = 0;
	int ind = 0;
	int err = 0;
	char s[12];

	if ((p = *optpptr) == NULL || *p == '\0') {
		/* Current word is done, advance */
		if (*optnext == NULL)
			return 1;
		p = **optnext;
		if (p == NULL || *p != '-' || *++p == '\0') {
atend:
			ind = *optnext - optfirst + 1;
			*optnext = NULL;
			p = NULL;
			done = 1;
			goto out;
		}
		(*optnext)++;
		if (p[0] == '-' && p[1] == '\0')	/* check for "--" */
			goto atend;
	}

	c = *p++;
	for (q = optstr; *q != c; ) {
		if (*q == '\0') {
			if (optstr[0] == ':') {
				s[0] = c;
				s[1] = '\0';
				err |= setvarsafe("OPTARG", s, 0);
			} else {
				outfmt(&errout, "Illegal option -%c\n", c);
				(void) unsetvar("OPTARG", 0);
			}
			c = '?';
			goto bad;
		}
		if (*++q == ':')
			q++;
	}

	if (*++q == ':') {
		if (*p == '\0' && (p = **optnext) == NULL) {
			if (optstr[0] == ':') {
				s[0] = c;
				s[1] = '\0';
				err |= setvarsafe("OPTARG", s, 0);
				c = ':';
			} else {
				outfmt(&errout, "No arg for -%c option\n", c);
				(void) unsetvar("OPTARG", 0);
				c = '?';
			}
			goto bad;
		}

		if (p == **optnext)
			(*optnext)++;
		err |= setvarsafe("OPTARG", p, 0);
		p = NULL;
	} else
		err |= setvarsafe("OPTARG", "", 0);
	ind = *optnext - optfirst + 1;
	goto out;

bad:
	ind = 1;
	*optnext = NULL;
	p = NULL;
out:
	*optpptr = p;
	fmtstr(s, sizeof(s), "%d", ind);
	err |= setvarsafe("OPTIND", s, VNOFUNC);
	s[0] = c;
	s[1] = '\0';
	err |= setvarsafe(optvar, s, 0);
	if (err) {
		*optnext = NULL;
		*optpptr = NULL;
		flushall();
		exraise(EXERROR);
	}
	return done;
}
Esempio n. 28
0
void debug_printf(void) {
    char buffer[4096];
    size_t maxlen = sizeof(buffer);

    int fp = GET_REG16(7)+2;
    const char *format = (char*) &memory[GET_WORD(fp)];
    fp += 2;

    char ch;
    long value;
    char *strvalue;
    int min;
    int max;
    int state;
    int flags;
    int cflags;
    size_t currlen;
    
    state = DP_S_DEFAULT;
    currlen = flags = cflags = min = 0;
    max = -1;
    ch = *format++;
    
    while (state != DP_S_DONE) {
	if (ch == '\0') 
	    state = DP_S_DONE;
	
	switch(state) {
	case DP_S_DEFAULT:
	    if (ch == '%') 
		state = DP_S_FLAGS;
	    else 
		dopr_outch (buffer, &currlen, maxlen, ch);
	    ch = *format++;
	    break;
	case DP_S_FLAGS:
	    switch (ch) {
	    case '-':
		flags |= DP_F_MINUS;
		ch = *format++;
		break;
	    case '+':
		flags |= DP_F_PLUS;
		ch = *format++;
		break;
	    case ' ':
		flags |= DP_F_SPACE;
		ch = *format++;
		break;
	    case '#':
		flags |= DP_F_NUM;
		ch = *format++;
		break;
	    case '0':
		flags |= DP_F_ZERO;
		ch = *format++;
		break;
	    default:
		state = DP_S_MIN;
		break;
	    }
	    break;
	case DP_S_MIN:
	    if (isdigit((unsigned char)ch)) {
		min = 10*min + char_to_int (ch);
		ch = *format++;
	    } else if (ch == '*') {
		min = (short) GET_WORD(fp);
		fp += 2;
		ch = *format++;
		state = DP_S_DOT;
	    } else {
		state = DP_S_DOT;
	    }
	    break;
	case DP_S_DOT:
	    if (ch == '.') {
		state = DP_S_MAX;
		ch = *format++;
	    } else { 
		state = DP_S_MOD;
	    }
	    break;
	case DP_S_MAX:
	    if (isdigit((unsigned char)ch)) {
		if (max < 0)
		    max = 0;
		max = 10*max + char_to_int (ch);
		ch = *format++;
	    } else if (ch == '*') {
		min = (short) GET_WORD(fp);
		fp += 2;
		ch = *format++;
		state = DP_S_MOD;
	    } else {
		state = DP_S_MOD;
	    }
	    break;
	case DP_S_MOD:
	    switch (ch) {
	    case 'h':
		cflags = DP_C_SHORT;
		ch = *format++;
		break;
	    case 'l':
		cflags = DP_C_LONG;
		ch = *format++;
		break;
	    default:
		break;
	    }
	    state = DP_S_CONV;
	    break;
	case DP_S_CONV:
	    switch (ch) {
	    case 'd':
	    case 'i':
		if (cflags == DP_C_LONG) {
		    value = ((int) (short) GET_WORD(fp)) << 16
			| GET_WORD(fp+2);
		    fp += 4;
		} else {
		    value = (short) GET_WORD(fp);
		    fp += 2;
		}
		fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
		break;
	    case 'o':
		flags |= DP_F_UNSIGNED;
		if (cflags == DP_C_LONG) {
		    value = ((unsigned int) GET_WORD(fp)) << 16
			| GET_WORD(fp+2);
		    fp += 4;
		} else {
		    value = GET_WORD(fp);
		    fp += 2;
		}
		fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
		break;
	    case 'u':
		flags |= DP_F_UNSIGNED;
		if (cflags == DP_C_LONG) {
		    value = ((unsigned int) GET_WORD(fp)) << 16
			| GET_WORD(fp+2);
		    fp += 4;
		} else {
		    value = GET_WORD(fp);
		    fp += 2;
		}
		fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
		break;
	    case 'X':
		flags |= DP_F_UP;
	    case 'x':
		flags |= DP_F_UNSIGNED;
		if (cflags == DP_C_LONG) {
		    value = ((unsigned int) GET_WORD(fp)) << 16
			| GET_WORD(fp+2);
		    fp += 4;
		} else {
		    value = GET_WORD(fp);
		    fp += 2;
		}
		fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
		break;
	    case 'c':
		dopr_outch (buffer, &currlen, maxlen, 
			    (int)(short)GET_WORD(fp));
		fp += 2;
		break;
	    case 's':
		{
		    int addr = GET_WORD(fp);
		    strvalue = (char*) &memory[addr];
		    if (!addr) 
			strvalue = "(NULL)";
		    if (max == -1) {
			max = strlen(strvalue);
		    }
		    if (min > 0 && max >= 0 && min > max) max = min;
		    fmtstr (buffer, &currlen, maxlen, strvalue, flags, 
			    min, max);
		}
		break;
	    case 'p':
		value = GET_WORD(fp);
		fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
		break;
	    case '%':
		dopr_outch (buffer, &currlen, maxlen, ch);
		break;
	    default:
		/* Unknown, skip */
		break;
	    }
	    ch = *format++;
	    state = DP_S_DEFAULT;
	    flags = cflags = min = 0;
	    max = -1;
	    break;
	case DP_S_DONE:
	    break;
	default:
	    /* hmm? */
	    break; /* some picky compilers need this */
	}
    }
    if (maxlen != 0) {
	if (currlen < maxlen - 1) 
	    buffer[currlen] = '\0';
	else if (maxlen > 0) 
	    buffer[maxlen - 1] = '\0';
    }
    
    printf("Program said: `%s'\n", buffer);
}
static char *
get_exc_trace()
{
    char *tbstr = NULL; 

    PyObject *iostrmod = NULL;
    PyObject *tbmod = NULL;
    PyObject *iostr = NULL;
    PyObject *obstr = NULL;
    PyObject *args = NULL;
    PyObject *newstr = NULL;
    PyObject *func = NULL;
    char* rv = NULL; 

    PyObject *type, *value, *traceback;
    TARGET_THREAD_BEGIN_BLOCK; 
    PyErr_Fetch(&type, &value, &traceback);
    debug("** type %p, value %p, traceback %p", type, value, traceback); 
    PyErr_Print(); 
    PyErr_Clear(); 
    PyErr_NormalizeException(&type, &value, &traceback);
    debug("** type %p, value %p, traceback %p", type, value, traceback); 

    iostrmod = PyImport_ImportModule("StringIO");
    if (iostrmod==NULL)
        TB_ERROR("can't import StringIO");

    iostr = PyObject_CallMethod(iostrmod, "StringIO", NULL);

    if (iostr==NULL)
        TB_ERROR("cStringIO.StringIO() failed");

    tbmod = PyImport_ImportModule("traceback");
    if (tbmod==NULL)
        TB_ERROR("can't import traceback");

    obstr = PyObject_CallMethod(tbmod, "print_exception",
        "(OOOOO)",
        type ? type : Py_None, 
        value ? value : Py_None,
        traceback ? traceback : Py_None,
        Py_None,
        iostr);

    if (obstr==NULL) 
    {
        PyErr_Print(); 
        TB_ERROR("traceback.print_exception() failed");
    }

    Py_DecRef(obstr);

    obstr = PyObject_CallMethod(iostr, "getvalue", NULL);
    if (obstr==NULL) 
        TB_ERROR("getvalue() failed.");

    if (!PyString_Check(obstr))
        TB_ERROR("getvalue() did not return a string");

    debug("%s", PyString_AsString(obstr)); 
    args = PyTuple_New(2);
    PyTuple_SetItem(args, 0, string2target("\n")); 
    PyTuple_SetItem(args, 1, string2target("<br>")); 
    
    func = PyObject_GetAttrString(obstr, "replace"); 
    //newstr = PyObject_CallMethod(obstr, "replace", args); 
    newstr = PyObject_CallObject(func, args); 

    tbstr = PyString_AsString(newstr); 

    rv = fmtstr("plugin:%s", tbstr); 

cleanup:
    PyErr_Restore(type, value, traceback);

    if (rv == NULL)
    {
        rv = tbstr ? tbstr : "";
    }

    Py_DecRef(func);
    Py_DecRef(args);
    Py_DecRef(newstr);
    Py_DecRef(iostr);
    Py_DecRef(obstr);
    Py_DecRef(iostrmod);
    Py_DecRef(tbmod);


    TARGET_THREAD_END_BLOCK; 
    return rv;
}