Beispiel #1
0
char *getoption_directories(struct directory *dir, char *name) {
    char curpath[256], *bar;
    struct directory *longest = NULL;
    if(!dir)
        return NULL;
    getcwd(curpath, sizeof(curpath) - 1);
    strcat(curpath, "/");
    do {
        bar = malloc(strlen(dir->path) + 2);
        strcpy(bar, dir->path);
        strcat(bar, "/");
        if (!strncmp(curpath, bar, strlen(bar))) {
            if (longest) {
                if ((strlen(bar) > strlen(longest->path) + 1)
                    && (getoption(dir->options, name)))
                    longest = dir;
            } else {
                if (getoption(dir->options, name))
                    longest = dir;
            }
        }
        free(bar);
    } while ((dir = dir->next));
    if (longest)
        return getoption(longest->options, name);
    return NULL;
}
int initparamsinitcell(Option * opts, int optsc) {
  Option optpinitinclump = getoption("pinitinclump", opts, optsc);

  if (nspecies != optpinitinclump.argsc) {
    fprintf(stderr, "Expected %d arguments for option pinitinclump, got %d\n", nspecies, optpinitinclump.argsc);
    return EXIT_FAILURE;
  }

  pinitinclump = malloc(sizeof(double) * nspecies);
  for (int i = 0; i < nspecies; i++) {
    pinitinclump[i] = atof(optpinitinclump.args[i]);
  }

  Option optpinitoutclump = getoption("pinitoutclump", opts, optsc);

  if (nspecies != optpinitoutclump.argsc) {
    fprintf(stderr, "Expected %d arguments for option pinitoutclump, got %d\n", nspecies, optpinitoutclump.argsc);
    return EXIT_FAILURE;
  }

  pinitoutclump = malloc(sizeof(double) * nspecies);
  for (int i = 0; i < nspecies; i++) {
    pinitoutclump[i] = atof(optpinitoutclump.args[i]);
  }

  Option optclumpradius = getoption("clumpradius", opts, optsc);
  clumpradius = atof(optclumpradius.args[0]);

  return EXIT_SUCCESS;
}
Beispiel #3
0
/* createicon
 *
 * Creates an icon resource from its filename
 *
 * usage: luasystray.createicon(<icon description table>)
 *
 * @param 	options 	Systray Icon Description Table:
 *
 * Systray Icon Description Table
 *   resourceid	: resource identifier to load icon from
 *   filename 	: icon filename to load icon from
 *   bitmap 	: true if icon file is a bitmap
 *	 width		: desired width for icon
 *	 height		: desired height for icon
 */
int createIcon(lua_State*L) {
	luaL_checkany(L, 1);
	int type = lua_type(L, 1);

	HMODULE hinstance = 0;
	int imgtype = IMAGE_ICON;

	const char*filename = NULL;
	const char*resourceid = NULL;

	int width = 0;
	int height = 0;
	int bitmap = 0;

	int loadtype = LR_LOADFROMFILE;

	if(type==LUA_TSTRING) {
		filename = lua_tostring(L, 1);
	}

	if(type==LUA_TTABLE) {
		getoption(1, resourceid);
		getoption(1, filename);
		getoption(1, bitmap);
		getoption(1, width);
		getoption(1, height);
	}

	if(bitmap) {
		imgtype = IMAGE_BITMAP;
		width = 0;
		height = 0;
	}

	if(resourceid) {
		loadtype = LR_DEFAULTCOLOR | LR_DEFAULTSIZE;
		hinstance = GetModuleHandleW(NULL);
		filename = resourceid;
	}

	HANDLE img = LoadImageW(
		hinstance,
		_T(filename),
		imgtype,
		width, height,
		loadtype
	);

	if(img) {
		luaL_error(L, "Error loading image");
	}

	lua_settop(L, 0);
	lua_pushlightuserdata(L, img);

	return 1;
}
Beispiel #4
0
/*
** Read, classify, and fill other details about the next option.
** 'psize' is filled with option's size, 'notoalign' with its
** alignment requirements.
** Local variable 'size' gets the size to be aligned. (Kpadal option
** always gets its full alignment, other options are limited by
** the maximum alignment ('maxalign'). Kchar option needs no alignment
** despite its size.
*/
static KOption getdetails (Header *h, size_t totalsize,
                           const char **fmt, int *psize, int *ntoalign) {
  KOption opt = getoption(h, fmt, psize);
  int align = *psize;  /* usually, alignment follows size */
  if (opt == Kpaddalign) {  /* 'X' gets alignment from following option */
    if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
      luaL_argerror(h->L, 1, "invalid next option for option 'X'");
  }
  if (align <= 1 || opt == Kchar)  /* need no alignment? */
    *ntoalign = 0;
  else {
    if (align > h->maxalign)  /* enforce maximum alignment */
      align = h->maxalign;
    if ((align & (align - 1)) != 0)  /* is 'align' not a power of 2? */
      luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
    *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1);
  }
  return opt;
}
int initparamsstochasticity(Option * opts, int optsc){
  Option curopt = getoption("seed", opts, optsc);
  if (curopt.name == NULL) {
    seed = time(NULL);
  } else {
    seed = atoi(curopt.args[0]);
  }

  return EXIT_SUCCESS;
}
Beispiel #6
0
char *getoption_global(char *name)
{
    char *result;
    if ((result = getoption_directories(config_global.directories, name)))
        return result;
    if (config_global.options) {
        if ((result = getoption(config_global.options, name)))
            return result;
    }
    return NULL;
}
Beispiel #7
0
/*
This function attempts to find a option, stored
in memory, by the given name. It searches
global options first, then group options and,
finally, individual user options. If a value
is found for the option, the function returns
a pointer to the value of the option. If no match
is found, an empty string is returned.
-- Jesse
*/
char *config_getoption_reread(char *find_me)
{
    char *return_value;
    static char empty_string = 0;

    return_value = getoption(config_global.options, find_me);
    if (return_value)
       return return_value;

    return &empty_string;
}
Beispiel #8
0
int initparamscaengine(Option * opts, int optsc) {
  Option opttmax = getoption("tmax", opts, optsc);
  if (opttmax.name != NULL) {
    tmax=atof(opttmax.args[0]);
    flag_tmax=true;
  } else {
    tmax=0;
    flag_tmax=false;
  }

  Option optoutputevery = getoption("outputevery", opts, optsc);
  if (optoutputevery.name != NULL) {
    outputevery=atoi(optoutputevery.args[0]);
  } else {
    outputevery=1;
  }

  flag_stable=false;

  return EXIT_SUCCESS;
}
Beispiel #9
0
char *
getoptionvalue(const char *name)
{
	struct option *c;

	if (name == NULL)
		errx(1, "getoptionvalue: invoked with NULL name");
	c = getoption(name);
	if (c != NULL)
		return (c->value);
	errx(1, "getoptionvalue: invoked with unknown option `%s'", name);
	/* NOTREACHED */
}
int initparamsinitgrid(Option * opts, int optsc) {
  Option optinitbase = getoption("initbase", opts, optsc);
  if (nspecies != optinitbase.argsc) {
    fprintf(stderr, "Expected %d arguments for option initbase, got %d\n", nspecies, optinitbase.argsc);
    return EXIT_FAILURE;
  }
  initbase = malloc(sizeof(double) * nspecies);
  for (int i = 0; i < nspecies; i++) {
    initbase[i] = atof(optinitbase.args[i]);
  }

  Option optinitseed = getoption("initseed", opts, optsc);
  if (nspecies != optinitseed.argsc) {
    fprintf(stderr, "Expected %d arguments for option initseed, got %d\n", nspecies, optinitseed.argsc);
    return EXIT_FAILURE;
  }
  initseed = malloc(sizeof(double) * nspecies);
  for (int i = 0; i < nspecies; i++) {
    initseed[i] = atof(optinitseed.args[i]);
  }
  
  return EXIT_SUCCESS;
}
Beispiel #11
0
char *getoption_user(char *name)
{
    char *result;
    struct user *usr;
    if ((usr = config_users)) {
        do {
            if (!strcmp(user, usr->name)) {
                if ((result = getoption_directories(usr->directories, name)))
                    return result;
                if ((result = getoption(usr->options, name)))
                    return result;
            }
        } while ((usr = usr->next));
    }
    return NULL;
}
Beispiel #12
0
char *getoption_group(char *name)
{
    char *result;
    struct group_of_users *grp;
    if ((grp = config_groups)) {
        do {
            if (user_is_in_group(grp) && grp->options) {
                if ((result = getoption_directories(grp->directories, name)))
                    return result;
                if ((result = getoption(grp->options, name)))
                    return result;
            }
        } while ((grp = grp->next));
    }
    return NULL;
}
Beispiel #13
0
/*
 * Generate an rprompt
 */
char *
rprompt(void)
{
	static char	**rprompt;
	static char	  buf[MAXPATHLEN];

	if (rprompt == NULL) {
		struct option *o;

		o = getoption("rprompt");
		if (o == NULL)
			errx(1, "rprompt: no such option `rprompt'");
		rprompt = &(o->value);
	}
	formatbuf(buf, sizeof(buf), *rprompt ? *rprompt : DEFAULTRPROMPT);
	return (buf);
}
Beispiel #14
0
int main(int argc,char **argv)
{
	printf("Http server welcome you!\n");
    tpool_create(10);
	if(1!=argc)
	getoption(argc,argv);//It's hard to learn how to use it  
	if(NULL==_log)
		logfd=open(DEFAULTLOG,O_WRONLY | O_APPEND | O_CREAT);
	else
		logfd=open(_log,O_WRONLY | O_CREAT | O_APPEND);
	
	daytime();
	int sockfd,sockfds;
	if(daemon_check)
		daemons();
    ssl_init(ctx);
    signal(SIGPIPE,SIG_IGN);
	signal(SIGCHLD, SIG_IGN);
	sockfd=make_socket(sockfd);
    sockfds=make_socket_ssl(sockfds);
	if(sockfd<0||sockfds<0)
		errorfunc("sockfd error!");
	int addrlen = 1;  
    setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&addrlen,sizeof(addrlen));//set the port quickly reuse
    setsockopt(sockfds,SOL_SOCKET,SO_REUSEADDR,&addrlen,sizeof(addrlen));
    struct epoll_event events[MAXEVENTS];//question
	int epollfd=epoll_create(MAXEVENTS);
	addfd(epollfd,sockfd,0);
    addfd(epollfd,sockfds,0);
	chdir("/home/wangyao/web");
	while(1)
	{
		int ret=epoll_wait(epollfd,events,MAXEVENTS,-1);//epoll func should be use in here
		if(ret<0)
			errorfunc("epoll_wait error!");
		lt(events,ret,epollfd,sockfd,sockfds);
	}
    close(sockfds);
	close(sockfd);
    close(epollfd);
    sleep(10);
    tpool_destroy();
    SSL_CTX_free(ctx);         
	exit(0);
}
Beispiel #15
0
int		builtin_echo(char *argv[])
{
  int		argp;
  int		ext = 0;
  int		line = 1;
  int		first;

  assert(argv && argv[0]);
  ext = option_is_set(shell->option, "xpg_echo");
  for (getoption(argv, &argp, &line, &ext), first = argp; argv[argp]; ++argp) {
    if (first != argp)
      printf(" ");
    if (ext && !builtin_echo_ext(argv[argp]))
      return fflush(stdout);
    printf("%s", argv[argp]);
  }
  if (line)
    printf("\n");
  return fflush(stdout);
}
Beispiel #16
0
int initparamstransitionengine(Option * opts, int optsc) {
  timestep = atof(getoption("timestep", opts, optsc).args[0]);
  return EXIT_SUCCESS;
}
Beispiel #17
0
/* parse an afpd.conf line. i'm doing it this way because it's
 * easy. it is, however, massively hokey. sample afpd.conf:
 * server:AFPServer@zone -loginmesg "blah blah blah" -nodsi 
 * "private machine"@zone2 -noguest -port 11012
 * server2 -nocleartxt -nodsi
 *
 * NOTE: this ignores unknown options 
 */
int afp_options_parseline(char *buf, struct afp_options *options)
{
    char *c, *opt;

    /* handle server */
    if (*buf != '-' && (c = getoption(buf, NULL)) && (opt = strdup(c)))
        options->server = opt;

    /* parse toggles */
    if (strstr(buf, " -nodebug"))
        options->flags &= ~OPTION_DEBUG;
#ifdef USE_SRVLOC
    if (strstr(buf, " -slp"))
        options->flags &= ~OPTION_NOSLP;
#endif
#ifdef USE_ZEROCONF
    if (strstr(buf, " -nozeroconf"))
        options->flags |= OPTION_NOZEROCONF;
#endif
    if (strstr(buf, " -nouservolfirst"))
        options->flags &= ~OPTION_USERVOLFIRST;
    if (strstr(buf, " -uservolfirst"))
        options->flags |= OPTION_USERVOLFIRST;
    if (strstr(buf, " -nouservol"))
        options->flags |= OPTION_NOUSERVOL;
    if (strstr(buf, " -uservol"))
        options->flags &= ~OPTION_NOUSERVOL;
    if (strstr(buf, " -proxy"))
        options->flags |= OPTION_PROXY;
    if (strstr(buf, " -noicon"))
        options->flags &= ~OPTION_CUSTOMICON;
    if (strstr(buf, " -icon"))
        options->flags |= OPTION_CUSTOMICON;
    if (strstr(buf, " -advertise_ssh"))
        options->flags |= OPTION_ANNOUNCESSH;
    if (strstr(buf, " -noacl2maccess"))
        options->flags &= ~OPTION_ACL2MACCESS;

    /* passwd bits */
    if (strstr(buf, " -nosavepassword"))
        options->passwdbits |= PASSWD_NOSAVE;
    if (strstr(buf, " -savepassword"))
        options->passwdbits &= ~PASSWD_NOSAVE;
    if (strstr(buf, " -nosetpassword"))
        options->passwdbits &= ~PASSWD_SET;
    if (strstr(buf, " -setpassword"))
        options->passwdbits |= PASSWD_SET;

    /* transports */
    if (strstr(buf, " -transall"))
        options->transports = AFPTRANS_ALL;
    if (strstr(buf, " -notransall"))
        options->transports = AFPTRANS_NONE;
    if (strstr(buf, " -tcp"))
        options->transports |= AFPTRANS_TCP;
    if (strstr(buf, " -notcp"))
        options->transports &= ~AFPTRANS_TCP;
    if (strstr(buf, " -ddp"))
        options->transports |= AFPTRANS_DDP;
    if (strstr(buf, " -noddp"))
        options->transports &= ~AFPTRANS_DDP;
    if (strstr(buf, "-client_polling"))
        options->server_notif = 0;

    /* figure out options w/ values. currently, this will ignore the setting
     * if memory is lacking. */

    if ((c = getoption(buf, "-hostname"))) {
        int len = strlen (c);
        if (len <= MAXHOSTNAMELEN) {
            memcpy(options->hostname, c, len);
            options->hostname[len] = 0;
        }
        else
            LOG(log_info, logtype_afpd, "WARNING: hostname %s is too long (%d)",c,len);
    }

    if ((c = getoption(buf, "-defaultvol")) && (opt = strdup(c)))
        options->defaultvol.name = opt;
    if ((c = getoption(buf, "-systemvol")) && (opt = strdup(c)))
        options->systemvol.name = opt;
    if ((c = getoption(buf, "-loginmesg")) && (opt = strdup(c))) {
        int i = 0, j = 0;
        while (c[i]) {
            if (c[i] != '\\') {
                opt[j++] = c[i];
            } else {
                i++;
                if (c[i] == 'n')
                    opt[j++] = '\n';
            }
            i++;
        }
        opt[j] = 0;
        options->loginmesg = opt;
        
    }
    if ((c = getoption(buf, "-guestname")) && (opt = strdup(c)))
        options->guest = opt;
    if ((c = getoption(buf, "-passwdfile")) && (opt = strdup(c)))
        options->passwdfile = opt;
    if ((c = getoption(buf, "-passwdminlen")))
        options->passwdminlen = MIN(1, atoi(c));
    if ((c = getoption(buf, "-loginmaxfail")))
        options->loginmaxfail = atoi(c);
    if ((c = getoption(buf, "-tickleval"))) {
        options->tickleval = atoi(c);
        if (options->tickleval <= 0) {
            options->tickleval = 30;
        }
    }
    if ((c = getoption(buf, "-timeout"))) {
        options->timeout = atoi(c);
        if (options->timeout <= 0) {
            options->timeout = 4;
        }
    }

    if ((c = getoption(buf, "-sleep"))) {
        options->sleep = atoi(c) *120;
        if (options->sleep <= 4) {
            options->sleep = 4;
        }
    }

    if ((c = getoption(buf, "-dsireadbuf"))) {
        options->dsireadbuf = atoi(c);
        if (options->dsireadbuf < 6)
            options->dsireadbuf = 6;
    }

    if ((c = getoption(buf, "-server_quantum")))
        options->server_quantum = strtoul(c, NULL, 0);

    if ((c = getoption(buf, "-volnamelen"))) {
        options->volnamelen = atoi(c);
        if (options->volnamelen < 8) {
            options->volnamelen = 8; /* max mangled volname "???#FFFF" */
        }
        if (options->volnamelen > 255) {
	    options->volnamelen = 255; /* AFP3 spec */
        }
    }

    /* -[no]setuplog <logtype> <loglevel> [<filename>]*/
    c = buf;
    /* Now THIS is hokey! Multiple occurrences are not supported by our current code, */
    /* so I have to loop myself. */
    while (NULL != (c = strstr(c, "-setuplog"))) {
        char *optstr;
        if ((optstr = getoption(c, "-setuplog"))) {
            setuplog(optstr);
            options->logconfig = optstr; /* at least store the last (possibly only) one */
            c += sizeof("-setuplog");
        }
    }

    if ((c = getoption(buf, "-unsetuplog")))
      unsetuplog(c);

#ifdef ADMIN_GRP
    if ((c = getoption(buf, "-admingroup"))) {
        struct group *gr = getgrnam(c);
        if (gr != NULL) {
            options->admingid = gr->gr_gid;
        }
    }
#endif /* ADMIN_GRP */

    if ((c = getoption(buf, "-k5service")) && (opt = strdup(c)))
	options->k5service = opt;
    if ((c = getoption(buf, "-k5realm")) && (opt = strdup(c)))
	options->k5realm = opt;
    if ((c = getoption(buf, "-k5keytab"))) {
	if ( NULL == (options->k5keytab = (char *) malloc(sizeof(char)*(strlen(c)+14)) )) {
		LOG(log_error, logtype_afpd, "malloc failed");
		exit(-1);
	}
	snprintf(options->k5keytab, strlen(c)+14, "KRB5_KTNAME=%s", c);
	putenv(options->k5keytab);
	/* setenv( "KRB5_KTNAME", c, 1 ); */
    }
    if ((c = getoption(buf, "-authprintdir")) && (opt = strdup(c)))
        options->authprintdir = opt;
    if ((c = getoption(buf, "-uampath")) && (opt = strdup(c)))
        options->uampath = opt;
    if ((c = getoption(buf, "-uamlist")) && (opt = strdup(c)))
        options->uamlist = opt;

    if ((c = getoption(buf, "-ipaddr"))) {
#if 0
        struct in_addr inaddr;
        if (inet_aton(c, &inaddr) && (opt = strdup(c))) {
            if (!gethostbyaddr((const char *) &inaddr, sizeof(inaddr), AF_INET))
                LOG(log_info, logtype_afpd, "WARNING: can't find %s", opt);
            options->ipaddr = opt;
        }
        else {
            LOG(log_error, logtype_afpd, "Error parsing -ipaddr, is %s in numbers-and-dots notation?", c);
        }
#endif
        options->ipaddr = strdup(c);
    }

    /* FIXME CNID Cnid_srv is a server attribute */
    if ((c = getoption(buf, "-cnidserver"))) {
        char *p = strrchr(c, ':');
        if (p)
            *p = 0;
        Cnid_srv = strdup(c);
        if (p)
            Cnid_port = strdup(p + 1);
        LOG(log_debug, logtype_afpd, "CNID Server: %s:%s", Cnid_srv, Cnid_port);
    }

    if ((c = getoption(buf, "-port")))
        options->port = strdup(c);
    if ((c = getoption(buf, "-ddpaddr")))
        atalk_aton(c, &options->ddpaddr);
    if ((c = getoption(buf, "-signature")) && (opt = strdup(c)))
        options->signatureopt = opt;

    /* do a little checking for the domain name. */
    if ((c = getoption(buf, "-fqdn"))) {
        char *p = strchr(c, ':');
        if (p)
            *p = '\0';
        if (gethostbyname(c)) {
            if (p)
                *p = ':';
            if ((opt = strdup(c)))
                options->fqdn = opt;
        }
	else {
            LOG(log_error, logtype_afpd, "error parsing -fqdn, gethostbyname failed for: %s", c);
	}
    }

    if ((c = getoption(buf, "-unixcodepage"))) {
    	if ((charset_t)-1  == ( options->unixcharset = add_charset(c)) ) {
            options->unixcharset = CH_UNIX;
            LOG(log_warning, logtype_afpd, "setting Unix codepage to '%s' failed", c);
    	}
	else {
            if ((opt = strdup(c)))
                options->unixcodepage = opt;
	}
    }
	
    if ((c = getoption(buf, "-maccodepage"))) {
    	if ((charset_t)-1 == ( options->maccharset = add_charset(c)) ) {
            options->maccharset = CH_MAC;
            LOG(log_warning, logtype_afpd, "setting Mac codepage to '%s' failed", c);
    	}
	else {
            if ((opt = strdup(c)))
                options->maccodepage = opt;
	}
    }
    
    if ((c = strstr(buf, "-closevol"))) {
        options->closevol= 1;
    }

    if ((c = getoption(buf, "-ntdomain")) && (opt = strdup(c)))
       options->ntdomain = opt;

    if ((c = getoption(buf, "-ntseparator")) && (opt = strdup(c)))
       options->ntseparator = opt;

    if ((c = getoption(buf, "-dircachesize")))
        options->dircachesize = atoi(c);
     
    if ((c = getoption(buf, "-tcpsndbuf")))
        options->tcp_sndbuf = atoi(c);

    if ((c = getoption(buf, "-tcprcvbuf")))
        options->tcp_rcvbuf = atoi(c);

    return 1;
}
Beispiel #18
0
    int main(int argc, char **argv)
    {
        struct sockaddr_in addr;
        int sock_fd, addrlen;

        /* 获得程序工作的参数,如 IP 、端口、监听数、网页根目录、目录存放位置等 */
        getoption(argc, argv);

        if (!host) {
            addrlen = strlen(DEFAULTIP);
            AllocateMemory(&host, addrlen, DEFAULTIP);
        }
        if (!port) {
            addrlen = strlen(DEFAULTPORT);
            AllocateMemory(&port, addrlen, DEFAULTPORT);
        }
        if (!back) {
            addrlen = strlen(DEFAULTBACK);
            AllocateMemory(&back, addrlen, DEFAULTBACK);
        }
        if (!dirroot) {
            addrlen = strlen(DEFAULTDIR);
            AllocateMemory(&dirroot, addrlen, DEFAULTDIR);
        }
        if (!logdir) {
            addrlen = strlen(DEFAULTLOG);
            AllocateMemory(&logdir, addrlen, DEFAULTLOG);
        }

        printf
            ("host=%s port=%s back=%s dirroot=%s logdir=%s %s是后台工作模式(进程ID:%d)\n",
             host, port, back, dirroot, logdir, daemon_y_n?"":"不", getpid());

        /* fork() 两次处于后台工作模式下 */
        if (daemon_y_n) {
            if (fork())
                exit(0);
            if (fork())
                exit(0);
            close(0), close(1), close(2);
            logfp = fopen(logdir, "a+");
            if (!logfp)
                exit(0);
        }

        /* 处理子进程退出以免产生僵尸进程 */
        signal(SIGCHLD, SIG_IGN);

        /* 创建 socket */
        if ((sock_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
            if (!daemon_y_n) {
                prterrmsg("socket()");
            } else {
                wrterrmsg("socket()");
            }
        }

        /* 设置端口快速重用 */
        addrlen = 1;
        setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &addrlen,
                   sizeof(addrlen));

        addr.sin_family = AF_INET;
        addr.sin_port = htons(atoi(port));
        addr.sin_addr.s_addr = inet_addr(host);
        addrlen = sizeof(struct sockaddr_in);
        /* 绑定地址、端口等信息 */
        if (bind(sock_fd, (struct sockaddr *) &addr, addrlen) < 0) {
            if (!daemon_y_n) {
                prterrmsg("bind()");
            } else {
                wrterrmsg("bind()");
            }
        }

        /* 开启临听 */
        if (listen(sock_fd, atoi(back)) < 0) {
            if (!daemon_y_n) {
                prterrmsg("listen()");
            } else {
                wrterrmsg("listen()");
            }
        }
        while (1) {
            int len;
            int new_fd;
            addrlen = sizeof(struct sockaddr_in);
            /* 接受新连接请求 */
            new_fd = accept(sock_fd, (struct sockaddr *) &addr, &addrlen);
            if (new_fd < 0) {
                if (!daemon_y_n) {
                    prterrmsg("accept()");
                } else {
                    wrterrmsg("accept()");
                }
                break;
            }
            bzero(buffer, MAXBUF + 1);
            sprintf(buffer, "连接来自于: %s:%d\n",
                    inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
            if (!daemon_y_n) {
                prtinfomsg(buffer);
            } else {
                wrtinfomsg(buffer);
            }
            /* 产生一个子进程去处理请求,当前进程继续等待新的连接到来 */
            if (!fork()) {
                bzero(buffer, MAXBUF + 1);
                if ((len = recv(new_fd, buffer, MAXBUF, 0)) > 0) {
                    FILE *ClientFP = fdopen(new_fd, "w");
                    if (ClientFP == NULL) {
                        if (!daemon_y_n) {
                            prterrmsg("fdopen()");
                        } else {
                            prterrmsg("fdopen()");
                        }
                    } else {
                        char Req[MAXPATH + 1] = "";
                        sscanf(buffer, "GET %s HTTP", Req);
                        bzero(buffer, MAXBUF + 1);
                        sprintf(buffer, "请求取文件: \"%s\"\n", Req);
                        if (!daemon_y_n) {
                            prtinfomsg(buffer);
                        } else {
                            wrtinfomsg(buffer);
                        }
                        /* 处理用户请求 */
                        GiveResponse(ClientFP, Req);
                        fclose(ClientFP);
                    }
                }
                exit(0);
            }
            close(new_fd);
        }
        close(sock_fd);
        return 0;
    }
Beispiel #19
0
int main(int argc, char **argv)
{
	struct sockaddr_in addr;
	int sock_fd, addrlen;
	
	getoption(argc, argv);

	if (!host) {
		addrlen = strlen(DEFAULTIP);
		AllocateMemory(&host, addrlen, DEFAULTIP);
	}
	if (!port) {
		addrlen = strlen(DEFAULTPORT);
		AllocateMemory(&port, addrlen, DEFAULTPORT);
	}
	if (!back) {
		addrlen = strlen(DEFAULTBACK);
		AllocateMemory(&back, addrlen, DEFAULTBACK);
	}
	if (!dirroot) {
		addrlen = strlen(DEFAULTDIR);
		AllocateMemory(&dirroot, addrlen, DEFAULTDIR);
	}
	if (!logdir) {
		addrlen = strlen(DEFAULTLOG);
		AllocateMemory(&logdir, addrlen, DEFAULTLOG);
	}

	printf
		("host=%s port=%s back=%s dirroot=%s logdir=%s %s daemon mode (pID:%d)\n",
		 host, port, back, dirroot, logdir, daemon_y_n?"":"is not", getpid());

	/* fork() twice for daemon  */
	if (daemon_y_n) {
		if (fork())
		  exit(0);
		if (fork())
		  exit(0);
		close(0), close(1), close(2);
		logfp = fopen(logdir, "a+");
		if (!logfp)
		  exit(0);
	}

	signal(SIGCHLD, SIG_IGN);

	if ((sock_fd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
		if (!daemon_y_n) {
			prterrmsg("socket()");
		} else {
			wrterrmsg("socket()");
		}
	}

	addrlen = 1;
	setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &addrlen,
				sizeof(addrlen));

	addr.sin_family = AF_INET;
	addr.sin_port = htons(atoi(port));
	addr.sin_addr.s_addr = inet_addr(host);
	addrlen = sizeof(struct sockaddr_in);
	
	if (bind(sock_fd, (struct sockaddr *) &addr, addrlen) < 0) {
		if (!daemon_y_n) {
			prterrmsg("bind()");
		} else {
			wrterrmsg("bind()");
		}
	}

	if (listen(sock_fd, atoi(back)) < 0) {
		if (!daemon_y_n) {
			prterrmsg("listen()");
		} else {
			wrterrmsg("listen()");
		}
	}
	while (1) {
		int len;
		int new_fd;
		addrlen = sizeof(struct sockaddr_in);
		
		new_fd = accept(sock_fd, (struct sockaddr *) &addr, &addrlen);
		if (new_fd < 0) {
			if (!daemon_y_n) {
				prterrmsg("accept()");
			} else {
				wrterrmsg("accept()");
			}
			break;
		}
		bzero(buffer, MAXBUF + 1);
		sprintf(buffer, "connection from : %s:%d\n",
					inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
		if (!daemon_y_n) {
			prtinfomsg(buffer);
		} else {
			wrtinfomsg(buffer);
		}
		
		if (!fork()) {
			bzero(buffer, MAXBUF + 1);
			if ((len = recv(new_fd, buffer, MAXBUF, 0)) > 0) {
				FILE *ClientFP = fdopen(new_fd, "w");
				if (ClientFP == NULL) {
					if (!daemon_y_n) {
						prterrmsg("fdopen()");
					} else {
						prterrmsg("fdopen()");
					}
				} else {
					char Req[MAXPATH + 1] = "";
					sscanf(buffer, "GET %s HTTP", Req);
					bzero(buffer, MAXBUF + 1);
					sprintf(buffer, "request file : \"%s\"\n", Req);
					if (!daemon_y_n) {
						prtinfomsg(buffer);
					} else {
						wrtinfomsg(buffer);
					}
					
					GiveResponse(ClientFP, Req);
					fclose(ClientFP);
				}
			}
			exit(0);
		}
		close(new_fd);
	}
	close(sock_fd);
	return 0;
}
Beispiel #20
0
int main(int argc, char *argv[])
{
  FILE *fp;
  int i, pc_init;
  Program pm[50000];
  float x = 0.0;

  fpin = stdin;
  fpout = stdout;

  for(i = 0; i < 32; i++) {
    reg[i].i = 0;
    freg[i].i = 0;
  }

  reg[29].i = 1048575;
  reg[30].i = 65536;
  
  for(i = 0; i < 1048576; i++)
    memory[i].i = 0;

  if((fp = fopen(argv[argc-1],"r")) == NULL) {
    perror("open error");
    return 0;
  }

  load(fp, pm);

  fclose(fp);

  getoption(argc, argv); 

  pc_init = pc;
  while(x < 2*M_PI) {
    freg[12].f = x;
  
    do{
      if(printflag == 1)
        print_instr(pm[pc]);
      
      while((breakflag == 1 && pc == breakpoint) || (stepflag == 1 && stepcount == 0))
        bpoint(pm[pc]);
      
      if(stepcount > 0)
        stepcount--;
      
    } while(exec(pm[pc]) == 0);
    
    fprintf(fpout, "%f %f\n", x, freg[0].f);
    x += 0.01;
    pc = pc_init;
    for(i = 0; i < 32; i++)
      freg[i].i = 0;
  }

  fprintf(stderr, "complete instructions\n");
  print_status();

  fclose(fpin);
  fclose(fpout);

  return 0;
}
Beispiel #21
0
/* Returns 1 on successful execution of the instruction, 0 if there was a fatal
error in execution (due to type-incorrectness, memory allocation, etc.), and
2 if the instruction successfully executed but a RETURN instruction was hit,
which signifies that this line of code should no longer be executed, and
that the calling code (if there is any) should continue to be executed.
Further, a return value of 3 means the instruction was successfully executed,
but it was a CODEEND instruction, which means that this line of code should
no longer be executed and that the calling code should continue to be
executed 
int *offset is a pointer to an integer, where the "offset" of this instruction
will be stored; the offset is the relative address of the next instruction in
the line of code that should be executed. For example, if the instruction is
PUSHFLOAT, *offset will be set to 6, as there are 5 bytes of float encoding
after the instruction, so the interpreter will find the next instruction
6 bytes after this one.  If, however, the instruction is a PUSHTRUE, no post-
instruction option bytes are needed, so *offset will be set to 1, signifying
that the next instruction in line is just the next byte. If an instruction which
calls for the halting of the code was executed (RETURN or CODEEND), then 
*offset will be set to 0, signifying that no more code in this block should
be executed.
char *code is a pointer to the character *following the instruction*.  */
int poe_exec_instr(poe_universe *U, char i, char *code, int *offset)
{
  char opt = getoption(i), instr = getinstr(i);
  poe_table *t;
  switch (instr) {
    /* value/struct creation */
  case PUSHINT:
    *offset += 2+*code; // default 1 + length 1 + length of representation
    return pexec_pushint(U,parse_int(*code,code+1,opt));
    break;
  case PUSHFLOAT:
    *offset += 6;
    return pexec_pushfloat(U,parse_float(code,opt));
    break;
  case PUSHCHAR:
    *offset += 2;
    return pexec_pushchar(U,*code);
    break;
  case PUSHTRUE:
    *offset += 1;
    return pexec_pushtrue(U);
    break;
  case PUSHFALSE:
    *offset += 1;
    return pexec_pushfalse(U);
    break;
  case PUSHUNDEF:
    *offset += 1;
    return pexec_pushundef(U);
    break;
  case PUSHNULL:
    *offset += 1;
    return pexec_pushnull(U);
    break;
  case NEWTAB:
    *offset += 1;
    return pexec_newtab(U);
    break;
  case NEWARR:
    *offset += 1;
    return pexec_newarr(U);
    break;
  case NEWSTR:
    *offset += 1;
    return pexec_newstr(U);
    break;
  case WRITESTR:
    return pexec_writestr(U, code, offset);
    break;
  case PUSHFUNC:
    return pexec_pushfunc(U, code, offset);
    break;
  case PUSHCODE:
    return pexec_pushcode(U, code, offset);
    break;
  case CODEEND:
    return POE_CODEEND;
    break;
  case EXIT:
    return POE_HALT;
    break;
  case ARGENUM:
    return pexec_argenum(U, code, offset);
    break;
    /* operators */
  case ADD:
    *offset += 1;
    return pexec_add(U);
    break;
  case SUB:
    *offset += 1;
    return pexec_sub(U);
    break;
  case MULT:
    *offset += 1;
    return pexec_mult(U);
    break;
  case DIV:
    *offset += 1;
    return pexec_div(U);
    break;
  case MOD:
    *offset += 1;
    return pexec_mod(U);
    break;
  case UNM:
    *offset += 1;
    return pexec_unm(U);
    break;
  case AND:
    *offset += 1;
    return pexec_and(U);
    break;
  case OR:
    *offset += 1;
    return pexec_or(U);
    break;
  case NOT:
    *offset += 1;
    return pexec_not(U);
    break;
  case BAND:
    *offset += 1;
    return pexec_band(U);
    break;
  case BOR:
    *offset += 1;
    return pexec_bor(U);
    break;
  case BXOR:
    *offset += 1;
    return pexec_bxor(U);
    break;
  case BNOT:
    *offset += 1;
    return pexec_bnot(U);
    break;
  case SHR:
    *offset += 1;
    return pexec_shr(U);
    break;
  case SHL:
    *offset += 1;
    return pexec_shl(U);
    break;
  case STRLEN:
    *offset += 1;
    return pexec_strlen(U);
    break;
  case ARRMAX:
    *offset += 1;
    return pexec_arrmax(U);
    break;
  case EQ:
    *offset += 1;
    return pexec_eq(U);
    break;
  case LT:
    *offset += 1;
    return pexec_lt(U);
    break;
  case LE:
    *offset += 1;
    return pexec_le(U);
    break;
  case CALL:
    *offset += 1;
    return pexec_call(U);
    break;
  case SWAP:
    *offset += 1;
    return pexec_swap(U);
    break;
  case RETURN:
    *offset += 1;
    return pexec_return(U);
    break;
  case DEL:
    *offset += 1;
    return pexec_del(U);
    break;
  case DO:
    *offset += 1;
    return pexec_do(U);
    break;
  case COPY:
    *offset += 1;
    return pexec_copy(U);
    break;

    /* manipulating data structures */
  case ARRACC:
    *offset += 1;
    return pexec_arracc(U);
    break;
  case TABACC:
    *offset += 1;
    return pexec_tabacc(U,NULL);
    break;
  case ARRSET:
    *offset += 1;
    return pexec_arrset(U);
    break;
  case TABSET:
    *offset += 1;
    return pexec_tabset(U,NULL);
    break;
  case TABKEEP:
    *offset += strlen(code)+2;
    return pexec_tabkeep(U,code);
  case ARRKEEP:
    *offset += 1;
    return pexec_arrkeep(U);
  case PUSHARGV:
    *offset += 1;
    return pexec_pushargv(U);
    break;
  case PUSHARGC:
    *offset += 1;
    return pexec_pushargc(U);
    break;
  case PUSHRETV:
    *offset += 1;
    return pexec_pushretv(U);
    break;
  case PUSHRETC:
    *offset += 1;
    return pexec_pushretc(U);
    break;
  case ARGV:
    *offset += 1;
    return pexec_argv(U);
    break;
  case ARGC:
    *offset += 1;
    return pexec_argc(U);
    break;
  case RETV:
    *offset += 1;
    return pexec_retv(U);
    break;
  case RETC:
    *offset += 1;
    return pexec_retc(U);
    break;
  case ASS:
    *offset += strlen(code+1)+3;
    return pexec_ass(U,*code,code+1);
    break;
  case GET:
    *offset += strlen(code+1)+3;
    return pexec_get(U,*code,code+1);
    break;
  case GETMETA:
    *offset += 1;
    return pexec_getmeta(U);
    break;
  case SETMETA:
    *offset += 1;
    return pexec_setmeta(U);
    break;
  case GETSUP:
    *offset += 1;
    return pexec_getsup(U);
    break;
  case SETSUP:
    *offset += 1;
    return pexec_setsup(U);
    break;
  case GLOBALS:
    *offset += 1;
    t = U->locals_stack_base[U->locals_stack_index];
    while (t->super_tag==POE_TABLE_TAG) t = t->super.poe_table;
    if (!poe_pushobj(U,(poe_obj)t,POE_TABLE_TAG)) return POE_FATAL_ERROR;
    return POE_CONTINUE;
    break;
  case LOCALS:
    *offset += 1;
    if (!poe_pushobj(U,(poe_obj)U->locals_stack_base[U->locals_stack_index],
		     POE_TABLE_TAG)) return POE_FATAL_ERROR;
    return POE_CONTINUE;
    break;
    /* iteration/control flow */
  case FORPREP:
    return pexec_forprep(U,code,offset);
    break;
  case FORITER:
    return pexec_foriter(U,offset);
    break;
  case WHILEPREP:
    return pexec_whileprep(U,code,offset);
    break;
  case WHILEITER:
    return pexec_whileiter(U,offset);
    break;
  case DOWPREP:
    return pexec_dowprep(U,code,offset);
    break;
  case IF:
    return pexec_if(U,code,offset);
    break;
  case ELSE:
    *offset += size_code(code,IFEND)+2;
    return POE_CONTINUE;
    break;
  case IFEND:
    *offset += 1;
    return POE_CONTINUE;
    break;
  case BREAK:
    return pexec_break(U,offset);
    break;
  case CONT:
    return pexec_cont(U,offset);
    break;
  default:
    return 0;
    break;
  }
  return 1;
}
int autoPatchRom(void*data,int size)
{
    static int ap_sorted=0;
    static DWORD auto_patch_table_index[auto_patch_table_size];
    if(ap_sorted==0)
    {
        ap_sorted=1;
        for(int i=0;i<auto_patch_table_size;i++)
        {
            auto_patch_table_index[i]=i;
        }
        quickSort(auto_patch_table_index,0,auto_patch_table_size-1,ap_sortbysize,auto_patch_table);
    }
    md5struct md5;
    int md5size=0;
    for(int i=0;i<auto_patch_table_size;i++)
    {
        if(size>=sorted(auto_patch_table,i).size)
        {
            if(md5size!=sorted(auto_patch_table,i).size)
            {
                if(md5size==0||md5size>sorted(auto_patch_table,i).size)
                {
                    getmd5(data,sorted(auto_patch_table,i).size,md5);
                }
                else
                {
                    updatemd5(((BYTE*)data)+md5size,sorted(auto_patch_table,i).size-md5size,md5);
                }
                md5size=sorted(auto_patch_table,i).size;
            }
            if(memcmp(md5,sorted(auto_patch_table,i).md5,16)==0)
            {
                if(getoption(enableKnownPatches))
                {
                    if(sorted(auto_patch_table,i).patch[0].offset!=-1)
                    {
                        for(int j=0;sorted(auto_patch_table,i).patch[j].offset!=-1;j++)
                        {
                            //printf("\n\toffset: %.4x\tvalue: %.4x\n",sorted(auto_patch_table,i).patch[j].offset,sorted(auto_patch_table,i).patch[j].value);
                            store_word_be(sorted(auto_patch_table,i).patch[j].value,((BYTE*)data)+sorted(auto_patch_table,i).patch[j].offset);
                        }
                        printf("\tauto patched: %s\n",sorted(auto_patch_table,i).name);
                    }
                    if(getoption(savePatchedFiles))
                    {
                        char rname[1024];
                        sprintf(rname,"%s_auto_patched.bin",sorted(auto_patch_table,i).name);
                        SaveFile(rname,(char*)data,size);
                    }
                }
                if(sorted(auto_patch_table,i).romtype==scd_bios)
                {
                    if((size>(sorted(auto_patch_table,i).size+16))&&(memcmp(((BYTE*)data)+sorted(auto_patch_table,i).size,"\xff\x04\xff\x04\xff\x04\xff\x04\xff\x04\xff\x04\xff\x04\xff\x04",16)==0))
                    {
                        return scd_bios_bram;
                    }
                }
                return sorted(auto_patch_table,i).romtype;
            }
        }
    }
    return unknown_rom;
}
int initparamsneighbourhoodshape(Option * opts, int optsc) {
  neighbourradius = atof(getoption("neighbourradius", opts, optsc).args[0]);
  return EXIT_SUCCESS;
}
Beispiel #24
0
int main(void)
{
	char key[KEY_SIZE + 1], value[VALUE_SIZE + 1];
	char *content = NULL;
	ssize_t content_size = 0;
	int n1, n2, m1, m2;
	/* response chosen for this request */
	/* leave uninitialized so the compiler warns */
	int response;
	int terminate = 0;

	do { /* main loop */

		/* Read header in the form: */
		/* METHOD ADDRESS HTTP/x.y\r\n */
		switch (scanf(" %n%" INTTOSTR(METHOD_SIZE) "[^ \f\v\t\r\n]%n %n%" INTTOSTR(ADDR_SIZE)
					"[^ \f\v\t\r\n]%n %*[Hh]%*[Tt]%*[Pp] / %u . %u\r\n",
					&n1, method, &n2, &m1, addr, &m2, &httpver[0], &httpver[1])) {
			case -1: /* EOF */
				return 0;

			case 0: /* I don't know if this could happen, but let's retry */
				continue;

			case 1:
			case 2:
			case 3:
				if ((n2 - n1) >= METHOD_SIZE) {
					fprintf(stderr, TEXTTOSTR(METHOD_SIZE) " too short (" INTTOSTR(METHOD_SIZE) ") for method %s...\n", method);
					response = 400; /* Bad Request */
					terminate = 1; /* let's not try to recover from this */
				} else if ((m2 - m1) >= ADDR_SIZE) {
					fprintf(stderr, TEXTTOSTR(ADDR_SIZE) " too short (" INTTOSTR(ADDR_SIZE) ") for addr %s...\n", addr);
					response = 414; /* Request-URI Too Long */
					/* discard the rest of the line and retry */
					scanf(" %*[^\r]\r\n");
				} else {
					response = 400; /* Bad Request */
					/* discard the rest of the line and retry */
					scanf(" %*[^\r]\r\n");
				}
				goto respond;

			case 4:
			default:
				/* move on to reading the options */
				break;
		}

		/* Read the options in the form: */
		/* KEY : VALUE\r\n */
		do {
			switch (scanf(" %n%" INTTOSTR(KEY_SIZE) "[^: \f\v\t\r\n]%n : %n%" INTTOSTR(VALUE_SIZE)
						"[^ \f\v\t\r\n]%n \r\n", &n1, key, &n2, &m1, value, &m2)) {
				case 0:
					if (scanf(" \r\n") == 0)
						/* end of options */
						goto break2;
					else /* EOF possibly? */
						/* passthrough */;

				case 1: /* key or value too long or : ou \r not found */
					if ((n2 - n1) >= KEY_SIZE || (m2 - m1) >= VALUE_SIZE) {
						fprintf(stderr, "key (size %d of %d) or value (size %d of %d) was too long\n", n2 - n1, KEY_SIZE, m2 - m1, VALUE_SIZE);
						response = 413; /* Request Entity Too Long */
						terminate = 1;
						goto respond;
					} else /* possibly not key:value\r\n format */
						/* passthrough to Bad Request */;

				case -1: /* EOF */
					/* expected \r\n, but nevermind */
					terminate = 1;
					goto break2;

				case 2:
				default:
					setinoption(key, value);
			}
		} while (1);
break2:

		if (getoption("Content-Length") == NULL) {
			response = 411; /* Length Required */
			goto respond;
		}

		/* utility function for OPTIONS, GET, HEAD... */
		void discard_input_content()
		{
			ssize_t content_len = atoi(getoption("Content-Length"));
			while (content_len > 0) {
				/* maybe use some other general-purpose buffer? */
				ssize_t n = read(0, value, (content_len <= VALUE_SIZE) ? content_len : VALUE_SIZE);
				if (n == -1) /* EOF, no more content, in spite of Content-Length */
					return;
				content_len -= n;
			}
		}

		if (!strcasecmp(method, "OPTIONS")) {
			response = 200; /* OK */
			discard_input_content();
			setoutoption("Accept","*/*");
			setoutoption("Content-Length", "0"); /* force this */
		} else if (!strcasecmp(method, "TRACE")) {
			response = 200; /* OK */

			ssize_t header_len = snprintf(value, VALUE_SIZE + 1, "%s %s HTTP/%u.%u\r\n", method, addr, httpver[0], httpver[1]);
			ssize_t content_len = atoi(getoption("Content-Length"));
			ssize_t options_len = rebuildinputoptions(&content, &content_size);
			ssize_t total_len = header_len + options_len + 2 + content_len + 1;

			if (content_size < total_len)
				content = realloc(content, content_size = total_len);

			/* make space in the beginning for the header */
			memmove(content + header_len, content, options_len);
			/* copy the header to its position */
			memcpy(content, value, header_len);
			/* put \r\n between the options and the original content */
			content[header_len + options_len] = '\r';
			content[header_len + options_len + 1] = '\n';
			/* bring the original content into the outgoing message */
			read(0, content + header_len + options_len + 2, content_len); /* don't really care about what this returns */
			/* put the response's Content-Length in place */
			snprintf(key, KEY_SIZE + 1, "%d", total_len - 1); /* the last \0 is not going to be streamed */
			setoutoption("Content-Length", key);
		} else { /* most valid methods fall into this ATM */
			fprintf(stderr, "received request for method %s\n", method);
			response = 405; /* Method Not Allowed */
			setoutoption("Allow", "OPTIONS");
			setoutoption("Content-Length", "0"); /* force this */
		}

respond:
		touchoption("Server"); /* this should always be sent */
		if (getoption("Content-Length") == NULL)
			setoutoption("Content-Length", "0");
		if (!response) {
			fprintf(stderr, "execution path not predicted\n");
			response = 500; /* Internal Server Error */
			setoutoption("Content-length", "0");
		}

		/* status line */
		printf("%d %s HTTP/%u.%u\r\n", response, response_text(response), HTTP_MAJOR_VERSION, HTTP_MINOR_VERSION);

		/* header options */
		spewoutputoptions();
		fflush(stdout);

		ssize_t content_length = atoi(getoption("Content-Length"));
		if (content_length > 0)
			if (write(1, content, content_length) != content_length)
				fprintf(stderr, "could not output %d bytes of content\n", content_length);

		currentver++;
	} while (!terminate); /* main loop */