Example #1
0
	CnxInfo::CnxInfo(IN const CnxInfo &x)
	{
		addr = x.addr;
		saddr = x.saddr;

		init_strings();
	}
Example #2
0
int				sh_setenv(t_cmd *cmd, t_env *env)
{
	t_var		*temp;
	t_var		*start;
	t_var		*p_var;

	start = NULL;
	if (setenv_isvalid(cmd, env))
		return (1);
	temp = init_strings(env->var, &p_var);
	while (p_var)
	{
		if (ft_strcmp(cmd->split[1], p_var->name) == 0)
			return (sh_setenv_var(p_var, cmd, env));
		temp = p_var;
		p_var = p_var->next;
	}
	env_list_add(&temp, &start);
	temp->name = ft_strdup(cmd->split[1]);
	temp->value = (cmd->split[2]) ? ft_strdup(cmd->split[2]) : NULL;
	env->nb++;
	if (cmd->env)
		array2d_free(cmd->env);
	if (env->var == NULL)
		env->var = temp;
	cmd->env = env_list_to_array(env->var, env->nb);
	return (0);
}
Example #3
0
int				get_next_line(int fd, char **line)
{
	static char	*s[1];
	char		*buff;
	char		*tmp;
	int			ret;

	init_strings(&buff, &tmp);
	fd > -1 && (read(fd, tmp, 0) >= 0) ? buff = malloc(BUFF_SIZE + 1) : NULL;
	if (fd > -1 && (read(fd, tmp, 0) >= 0))
		!s[fd] ? (s[fd] = ft_strnew(0))
			: (tmp = ft_strchr(s[fd], '\n'));
	if (!buff)
		return (-1);
	while (fd > -1 && line && !tmp && (ret = read(fd, buff, BUFF_SIZE)) > 0)
	{
		buff[ret] = '\0';
		(tmp = ft_strjoin(s[fd], buff)) ? free(s[fd]) : NULL;
		s[fd] = tmp;
		tmp = ft_strchr(s[fd], '\n');
	}
	fd > -1 && (read(fd, tmp, 0) >= 0) ? free(buff) : NULL;
	if ((fd < 0 || ret < 0 || !line) || (!tmp && s[fd][0] == '\0'))
		return (!tmp && s[fd][0] == '\0' ? 0 : -1);
	*line = (tmp ? ft_strsub(s[fd], 0, tmp - s[fd]) : ft_strdup(s[fd]));
	s[fd] = (tmp ? ft_strcpy(s[fd], ++tmp) : ft_strdup("\0"));
	return (ft_strlen(*line));
}
Example #4
0
int main(void)
{
	SetConsoleTitle(TITLE);

	mtx_init(&gmutex, mtx_plain);
	cnd_init(&gcond);

	init_timer();
	init_path();
	init_strings();
	init_server();
	initpackets();
	//test_map(1);
	thrd_create(&t1, initsocket, (void*)0);
	thrd_create(&t2, commands, (void*)0);
	server_loop();
	destroy_server();
	mtx_destroy(&gmutex);
	cnd_destroy(&gcond);
#if _DEBUG
	VLDReportLeaks();
#endif

	exit(TRUE);// Exit program
}
Example #5
0
token_initer::token_initer()
{
  init_ascii();
  init_latin1();
  init_special_chars();
  init_strings();
  default_token_info.set(TOKEN_OTHER);
}
Example #6
0
	CnxInfo::CnxInfo(IN in_addr p_in_addr, IN int p_port)
	{
		addr.sin_family = AF_INET;;
		addr.sin_addr = p_in_addr;
		addr.sin_port = ::htons(p_port);


		init_strings();
	}
Example #7
0
	void CnxInfo::init_from_hostname(const char *host_name,int p_port)
	{
		
		unsigned long ia = inet_addr(host_name);

		addr.sin_addr.S_un.S_addr = ia;
		addr.sin_family = AF_INET;
		addr.sin_port = ::htons(p_port);
	
		init_strings();

	}
Example #8
0
int main(int argc, char** argv) {
	if (argc != 2) {		// Ensure that the user supplies a image filename
		fprintf(stderr,"Usage: %s image.nsi\n",argv[0]);
		return 1;		// Return error and usage message if no file supplied
	}
	init_memory(argv[1]);		// create a new memory image of the suppied filename
	init_strings();			// setup of core system strings, and opcode tables
	init_lexicon();			// define a basic lexicon
	compile();			// compile the source listings from stdin
	fini_memory();			// save the memory image and close the file
	return 0;			// return success
}
Example #9
0
void
rocPrestart()
{
  unsigned short iflag;
  int stat;

  /* Check ffile for changes (usrstrutils) 
     Useful for items that may change without re-download (e.g. prescale factors) */
  init_strings();
  ps1 = getint("ps1");
  printf("usrstrutils configuration:\n");
  printf("\tps1 = %d\n",ps1);

  /* Program/Init Trigger Supervisor and VME Modules Here */
  tsReset(0);

  tsCsr2Set(TS_CSR2_LOCK_ALL);  /* ROC Lock mode on all BRANCHES */
  tsEnableInput(0xfff,0);       /* Enable all Trigger inputs in non-strobe mode */
  tsRoc(0,0,0,0);               /* Enable ACK 0,1 on BRANCH 1  and ACK 2 on Branch 2*/

  /* Synchronization programming */
  tsSync(100);                      /* schedule Sync every 100th physics trigger */
  tsCsr2Set(TS_CSR2_ENABLE_SYNC);   /* Enable Scheduled syncs */ 

  /* Set nominal Level 2/3 timer values */
  tsTimerWrite(TS_TIMER_L2A,0x05);   /* Level 2 Timer 40ns/count */
  tsTimerWrite(TS_TIMER_L3A,0x05);   /* Level 3 Timer 40ns/count */

  /* Front End Busy timer 40ns/count */
  tsTimerWrite(TS_TIMER_FB,250);         /* 250 = 10 microsec */   
  tsCsr2Set(TS_CSR2_ENABLE_FB_TIMER);    /* Enable FEB Timer */

  /*  Construct TS memory data  ---  in the following model, all trigger patterns 
      that form the memory address are assigned to trigger class 1.  For those 
      trigger patterns with a single hit, the ROC code is set to be the trigger 
      input number.  Otherwise, the ROC code is set to 0xE.  All LEVEL 1 ACCEPT 
      signals are asserted for every pattern.  */
   
  tsMemInit();

  /* Fix special cases - both inputs 1 and 2 firing - type 13 (0xd) 
     all L1 accept outputs firing 0xff03 */
  tsMemWrite(3,0xdff03);

  /* Set specific input prescale factors */
  tsPrescale(1,0);
  tsPrescale(2,0);

  printf("rocPrestart: User Prestart Executed\n");

}
Example #10
0
STRING* ui_gettext(UI_LANG_ID lang, UI_STRING_ID string_id) {
    static STRING localized_strings[LANGS_MAX+1][STRS_MAX+1];
    static int ready = 0;

    if(!ready) {
        init_strings(localized_strings);
        ready = 1;
    }

    if((lang > LANGS_MAX) || (string_id > STRS_MAX)) {
        return &canary;
    }

    return &localized_strings[lang][string_id];
}
Example #11
0
STRING* ui_gettext(UI_LANG_ID lang, UI_STRING_ID string_id) {
    static STRING localized_strings[NUM_LANGS][NUM_STRS];
    static int ready = 0;

    if(!ready) {
        init_strings(localized_strings);
        ready = 1;
    }

    if((lang >= NUM_LANGS) || (string_id >= NUM_STRS)) {
        return &canary;
    }

    return &localized_strings[lang][string_id];
}
Example #12
0
void
rocDownload()
{
  int dmaMode;

  /* Initialize usrstrutils */
  init_strings();
  string1 = getflag("string");
  string2 = getflag("string2");

  printf("usrstrutils configuration:\n");
  printf("\tstring1 = %d\n\tstring2 = %d\n",string1,string2);

  printf("rocDownload: User Download Executed\n");

}
Example #13
0
/******************************************************************
 *              DllMain (jscript.@)
 */
BOOL WINAPI DllMain(HINSTANCE hInstDLL, DWORD fdwReason, LPVOID lpv)
{
    TRACE("(%p %d %p)\n", hInstDLL, fdwReason, lpv);

    switch(fdwReason) {
    case DLL_PROCESS_ATTACH:
        DisableThreadLibraryCalls(hInstDLL);
        jscript_hinstance = hInstDLL;
        if(!init_strings())
            return FALSE;
        break;
    case DLL_PROCESS_DETACH:
        if (lpv) break;
        free_strings();
    }

    return TRUE;
}
Example #14
0
int main(int argc, const char * argv[])
{
	/* Name our little program */
	strncpy(program_name, argv[0], short_strlen);
	/* Prepare ilu functions "database" */ 
	init_strings();
	/* initialize DevIL in order to get defined behavior of the app */
	ilInit();
	iluInit();
	/* Prepare command line parsing */
	Params * parameters = create_params();
	/* Do the parsing */
	parse_arguments(argc, argv, parameters);
	/* Finally do what we wanted */
	do_stuff(parameters);
	/* Clean after the party */
	destroy_params(parameters);
	return 0;
}
Example #15
0
/* slave information interface */
void init_sii(ecat_slave *esv)
{
    int pdoe_idx = 0;

    memset(&esv->categories,0,sizeof(struct __sii_categories__));
    init_si_info(&esv->categories.sii);
    init_strings(&esv->categories.strings, &esv->categories.strings_hdr);
    init_fmmu(&esv->categories.fmmu, &esv->categories.fmmu_hdr);
    init_syncm(esv, &esv->categories.syncm0, 0 ,&esv->categories.syncm_hdr0);
    init_syncm(esv, &esv->categories.syncm1, 1 ,&esv->categories.syncm_hdr1);
    init_general(esv, &esv->categories.general, &esv->categories.general_hdr);
    init_end_hdr(&esv->categories.endhdr);

    // pdos
    esv->categories.rxpdo_hdr.type = CAT_TYPE_RXPDO;
    esv->categories.rxpdo_hdr.size = sizeof(esv->categories.rxpdo)/2;
    esv->categories.rxpdo.entries = 2;
    esv->categories.rxpdo.flags = 0;
    esv->categories.rxpdo.name_idx = RXPDO_CAT_NAME_IDX + 1;
    esv->categories.rxpdo.synchronization = 0;
    esv->categories.rxpdo.syncm = 0;
    esv->categories.rxpdo.pdo_index = 0x1600;

    init_pdo(&esv->categories.rxpdo.pdo[0], 0x1600, 0X02, RX_PDO1_NAME_IDX + 1, 0, 8, 0);
    esv->pdoe_sizes[pdoe_idx++] = 8;
    init_pdo(&esv->categories.rxpdo.pdo[1], 0x1600, 0X01, RX_PDO2_NAME_IDX + 1, 0, 32, 0);
    esv->pdoe_sizes[pdoe_idx++]  = 32;

    esv->categories.txpdo_hdr.type = CAT_TYPE_TXPDO;
    esv->categories.txpdo.entries = 2;
    esv->categories.txpdo.flags = 0;
    esv->categories.txpdo.name_idx = TXPDO_CAT_NAME_IDX  +1;
    esv->categories.txpdo.synchronization = 0;
    esv->categories.txpdo.syncm = 1;
    esv->categories.txpdo.pdo_index = 0x1a00;
    esv->categories.txpdo_hdr.size = sizeof(esv->categories.txpdo)/2;

    init_pdo(&esv->categories.txpdo.pdo[0], 0x1a00, 0X02, TX_PDO1_NAME_IDX + 1, 0, 32, 0);
    esv->pdoe_sizes[pdoe_idx++]  = 32;
    init_pdo(&esv->categories.txpdo.pdo[1], 0x1a00, 0X01, TX_PDO2_NAME_IDX + 1, 0, 16, 0);
    esv->pdoe_sizes[pdoe_idx++]  = 16;
}
Example #16
0
int WWWLib_Init(Tcl_Interp *interp) 
{  
    LibraryFunction *c;

#ifdef CMDLINE
    HTProfile_newClient(APP_NAME, APP_VERSION);
#else
    HTLibInit(APP_NAME, APP_VERSION);
#endif

    Tcl_InitHashTable(&HTableAnchor, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableLink, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableList, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableReq, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableStream, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableVoid, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableAssoc, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableUser, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableCallback, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableHost, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableChunk, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableProt,  TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableConverter, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableCoder, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableAlertCallback, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableAlertPar, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableError, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableMIMEParseSet, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableCallback, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableNet, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableDNS, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableTrans, TCL_STRING_KEYS);
    Tcl_InitHashTable(&HTableChannel, TCL_STRING_KEYS);

    random_seed();
    init_strings();
    for(c = www_commands; c->name; c++){
	Tcl_CreateCommand(interp, c->name, c->proc, c->data,
			  NULL /* delete proc???*/);
    }
    return TCL_OK;
}
Example #17
0
int main P2(int, argc, char **, argv)
{
    time_t tm;
    int i, new_mudlib = 0, got_defaults = 0;
    int no_ip_demon = 0;
    char *p;
    char version_buf[80];
#if 0
    int dtablesize;
#endif
    error_context_t econ;

#if !defined(LATTICE) && !defined(OLD_ULTRIX) && !defined(sequent) && \
    !defined(sgi)
    void tzset();
#endif
    struct lpc_predef_s predefs;

#if !defined(__SASC) && (defined(AMITCP) || defined(AS225))
    amiga_sockinit();
    atexit(amiga_sockexit);
#endif
#ifdef WRAPPEDMALLOC
    wrappedmalloc_init();
#endif				/* WRAPPEDMALLOC */
#ifdef DEBUGMALLOC
    MDinit();
#endif

#if (defined(PROFILING) && !defined(PROFILE_ON) && defined(HAS_MONCONTROL))
    moncontrol(0);
#endif
#if !defined(OLD_ULTRIX) && !defined(LATTICE) && !defined(sequent)
    tzset();
#endif
    boot_time = get_current_time();

    const0.type = T_NUMBER;
    const0.u.number = 0;
    const1.type = T_NUMBER;
    const1.u.number = 1;

    /* const0u used by undefinedp() */
    const0u.type = T_NUMBER;
    const0u.subtype = T_UNDEFINED;
    const0u.u.number = 0;

    /* const0n used by nullp() */
    const0n.type = T_NUMBER;
    const0n.subtype = T_NULLVALUE;
    const0n.u.number = 0;

    fake_prog.program_size = 0;

    /*
     * Check that the definition of EXTRACT_UCHAR() is correct.
     */
    p = (char *) &i;
    *p = -10;
    if (EXTRACT_UCHAR(p) != 0x100 - 10) {
	fprintf(stderr, "Bad definition of EXTRACT_UCHAR() in interpret.h.\n");
	exit(-1);
    }

    /*
     * An added test: can we do EXTRACT_UCHAR(x++)?
     * (read_number, etc uses it)
     */
    p = (char *) &i;
    (void) EXTRACT_UCHAR(p++);
    if ((p - (char *) &i) != 1) {
	fprintf(stderr, "EXTRACT_UCHAR() in interpret.h evaluates its argument more than once.\n");
	exit(-1);
    }

    /*
     * Check the living hash table size
     */
    if (CFG_LIVING_HASH_SIZE != 4 && CFG_LIVING_HASH_SIZE != 16 &&
	CFG_LIVING_HASH_SIZE != 64 && CFG_LIVING_HASH_SIZE != 256 &&
	CFG_LIVING_HASH_SIZE != 1024 && CFG_LIVING_HASH_SIZE != 4096) {
	fprintf(stderr, "CFG_LIVING_HASH_SIZE in options.h must be one of 4, 16, 64, 256, 1024, 4096, ...\n");
	exit(-1);
    }

#ifdef RAND
    srand(get_current_time());
#else
#  ifdef DRAND48
    srand48(get_current_time());
#  else
#    ifdef RANDOM
    srandom(get_current_time());
#    else
    fprintf(stderr, "Warning: no random number generator specified!\n");
#    endif
#  endif
#endif
    current_time = get_current_time();
    /*
     * Initialize the microsecond clock.
     */
    init_usec_clock();

    /* read in the configuration file */

    got_defaults = 0;
    for (i = 1; (i < argc) && !got_defaults; i++) {
	if (argv[i][0] != '-') {
	    set_defaults(argv[i]);
	    got_defaults = 1;
	}
    }
    if (!got_defaults) {
	fprintf(stderr, "You must specify the configuration filename as an argument.\n");
	exit(-1);
    }

    printf("Initializing internal tables....\n");
    init_strings();		/* in stralloc.c */
    init_otable();		/* in otable.c */
    init_identifiers();		/* in lex.c */
    init_locals();              /* in compiler.c */

/* disable this for now */
#if 0
    /*
     * We estimate that we will need MAX_USERS + MAX_EFUN_SOCKS + 10 file
     * descriptors if the maximum number of users were to log in and all LPC
     * sockets were in use.  This is a pretty close estimate.
     */
#ifndef LATTICE
    dtablesize = MAX_USERS + MAX_EFUN_SOCKS + 10;
#else
    /*
     * Amiga sockets separate from file descriptors
     */
    dtablesize = MAX_USERS + MAX_EFUN_SOCKS;
#endif

    /*
     * If our estimate is larger than FD_SETSIZE, then we need more file
     * descriptors than the operating system can handle.  This is a problem
     * that can be resolved by decreasing MAX_USERS, MAX_EFUN_SOCKS, or both.
     */
    if (dtablesize > FD_SETSIZE) {
	fprintf(stderr, "Warning: File descriptor requirements exceed system capacity!\n");
	fprintf(stderr, "         Configuration exceeds system capacity by %d descriptor(s).\n",
		dtablesize - FD_SETSIZE);
    }
#ifdef HAS_SETDTABLESIZE
    /*
     * If the operating system supports setdtablesize() then we can request
     * the number of file descriptors we really need.  First check to see if
     * wee already have enough.  If so dont bother the OS. If not, attempt to
     * allocate the number we estimated above.  There are system imposed
     * limits on file descriptors, so we may not get as many as we asked for.
     * Check to make sure we get enough.
     */
    if (getdtablesize() < dtablesize)
	if (setdtablesize(dtablesize) < dtablesize) {
	    fprintf(stderr, "Warning: Could not allocate enough file descriptors!\n");
	    fprintf(stderr, "         setdtablesize() could not allocate %d descriptor(s).\n",
		    getdtablesize() - dtablesize);
	}
    /*
     * Just be polite and tell the administrator how many he has.
     */
    fprintf(stderr, "%d file descriptors were allocated, (%d were requested).\n",
	    getdtablesize(), dtablesize);
#endif
#endif
    time_to_clean_up = TIME_TO_CLEAN_UP;
    time_to_swap = TIME_TO_SWAP;
    max_cost = MAX_COST;
    reserved_size = RESERVED_SIZE;
    max_array_size = MAX_ARRAY_SIZE;
    max_buffer_size = MAX_BUFFER_SIZE;
    max_string_length = MAX_STRING_LENGTH;
    master_file_name = (char *) MASTER_FILE;
    /* fix the filename */
    while (*master_file_name == '/') master_file_name++;
    p = master_file_name;
    while (*p++);
    if (p[-2]=='c' && p[-3]=='.')
	p[-3]=0;
    mud_lib = (char *) MUD_LIB;
    set_inc_list(INCLUDE_DIRS);
    if (reserved_size > 0)
	reserved_area = (char *) DMALLOC(reserved_size, TAG_RESERVED, "main.c: reserved_area");
    for (i = 0; i < sizeof consts / sizeof consts[0]; i++)
	consts[i] = exp(-i / 900.0);
    init_num_args();
    reset_machine(1);
    /*
     * The flags are parsed twice ! The first time, we only search for the -m
     * flag, which specifies another mudlib, and the D-flags, so that they
     * will be available when compiling master.c.
     */
    for (i = 1; i < argc; i++) {
	if (argv[i][0] != '-')
	    continue;
	switch (argv[i][1]) {
	case 'D':
	    if (argv[i][2]) {	/* Amylaar : allow flags to be passed down to
				 * the LPC preprocessor */
		struct lpc_predef_s *tmp;

		tmp = &predefs;
		tmp->flag = argv[i] + 2;
		tmp->next = lpc_predefs;
		lpc_predefs = tmp;
		continue;
	    }
	    fprintf(stderr, "Illegal flag syntax: %s\n", argv[i]);
	    exit(-1);
	case 'N':
	    no_ip_demon++;
	    continue;
#ifdef YYDEBUG
	case 'y':
	    yydebug = 1;
	    continue;
#endif				/* YYDEBUG */
	case 'm':
	    mud_lib = alloc_cstring(argv[i] + 2, "mudlib dir");
	    if (chdir(mud_lib) == -1) {
		fprintf(stderr, "Bad mudlib directory: %s\n", mud_lib);
		exit(-1);
	    }
	    new_mudlib = 1;
	    break;
	}
    }
    if (!new_mudlib && chdir(mud_lib) == -1) {
	fprintf(stderr, "Bad mudlib directory: %s\n", mud_lib);
	exit(-1);
    }
    get_version(version_buf);
    time(&tm);
    debug_message("----------------------------------------------------------------------------\n%s (%s) starting up on %s - %s\n\n", MUD_NAME, version_buf, ARCH, ctime(&tm));

#ifdef BINARIES
    init_binaries(argc, argv);
#endif
#ifdef LPC_TO_C
    init_lpc_to_c();
#endif
    add_predefines();

#ifndef NO_IP_DEMON
    if (!no_ip_demon && ADDR_SERVER_IP)
	init_addr_server(ADDR_SERVER_IP, ADDR_SERVER_PORT);
#endif				/* NO_IP_DEMON */

    eval_cost = max_cost;	/* needed for create() functions */

    save_context(&econ);
    if (SETJMP(econ.context)) {
	debug_message("The simul_efun (%s) and master (%s) objects must be loadable.\n", 
		      SIMUL_EFUN, MASTER_FILE);
	exit(-1);
    } else {
	init_simul_efun(SIMUL_EFUN);
	init_master(MASTER_FILE);
    }
    pop_context(&econ);

    for (i = 1; i < argc; i++) {
	if (argv[i][0] != '-') {
	    continue;
	} else {
	    /*
	     * Look at flags. -m and -o has already been tested.
	     */
	    switch (argv[i][1]) {
	    case 'D':
	    case 'N':
	    case 'm':
	    case 'y':
		continue;
	    case 'f':
		save_context(&econ);
		if (SETJMP(econ.context)) {
		    debug_message("Error while calling master::flag(\"%s\"), aborting ...", argv[i] + 2);
		    exit(-1);
		}
		push_constant_string(argv[i] + 2);
		(void) apply_master_ob(APPLY_FLAG, 1);
		if (MudOS_is_being_shut_down) {
		    debug_message("Shutdown by master object.\n");
		    exit(0);
		}
		pop_context(&econ);
		continue;
	    case 'e':
		e_flag++;
		continue;
	    case 'p':
		external_port[0].port = atoi(argv[i] + 2);
		continue;
            case 'd':
#ifdef DEBUG
                d_flag++;
#else
                debug_message("Driver must be compiled with DEBUG on to use -d.\n");
#endif
	    case 'c':
		comp_flag++;
		continue;
	    case 't':
		t_flag++;
		continue;
	    default:
		debug_message("Unknown flag: %s\n", argv[i]);
		exit(-1);
	    }
	}
    }
    if (MudOS_is_being_shut_down)
	exit(1);
    if (strlen(DEFAULT_FAIL_MESSAGE))
	default_fail_message = DEFAULT_FAIL_MESSAGE;
    else
	default_fail_message = "What?";
#ifdef PACKAGE_MUDLIB_STATS
    restore_stat_files();
#endif
#ifdef PACKAGE_SOCKETS
    init_sockets();		/* initialize efun sockets           */
#endif
    preload_objects(e_flag);
#ifdef SIGFPE
    signal(SIGFPE, sig_fpe);
#endif
#ifdef TRAP_CRASHES
#ifdef SIGUSR1
    signal(SIGUSR1, sig_usr1);
#endif
    signal(SIGTERM, sig_term);
    signal(SIGINT, sig_int);
#ifndef DEBUG
#if defined(SIGABRT) && !defined(LATTICE)
    signal(SIGABRT, sig_abrt);
#endif
#ifdef SIGIOT
    signal(SIGIOT, sig_iot);
#endif
#ifdef SIGHUP
    signal(SIGHUP, sig_hup);
#endif
#ifdef SIGBUS
    signal(SIGBUS, sig_bus);
#endif
#ifndef LATTICE
    signal(SIGSEGV, sig_segv);
    signal(SIGILL, sig_ill);
#endif
#endif				/* DEBUG */
#endif
    backend();
    return 0;
}
Example #18
0
/** used in client thread */
void sdl_user::init()
{
    main_config = new config("Lineage.ini");
    if (!main_config->config_ok())
    {
        delete main_config;
        main_config = 0;
        throw "ERROR Loading configuration file.\n";
    }
    char *test;
    test = (char*)getfiles->load_file("Sprite00.idx", 0, FILE_REGULAR1, 0);
    if (test == 0)
    {
        throw "Lineage Data not found";
    }
    delete [] test;
    lineage_font.init("Font/eng.fnt", this);	//TODO : make a client specific version of the font

    unsigned char *sprite_data;
    int sprite_dlength;
    sprite_data = (unsigned char*)getfiles->load_file("sprite_table.txt", &sprite_dlength, FILE_REGULAR2, 0);
    if (sprite_data == 0)
    {
        printf("sprite_table.txt not found\n");
    }
    else
    {
        int offset = 1;
        int sprnum = 0;
        printf("The first number is %d\n", atoi((char*)&sprite_data[offset]));
        while (isdigit(sprite_data[offset])) {
            offset++;
        }
        if (sprite_data[offset] == '=')
        {
            offset += 1;
            int alias = atoi((char*)&sprite_data[offset]);
            printf("Alias of %d found\n", alias);
            while (isdigit(sprite_data[offset])) {
                offset++;
            }
            while (!isdigit(sprite_data[offset])) {
                offset++;
            }
        }
        char value = atoi((char*)&sprite_data[offset]);
        while (isdigit(sprite_data[offset])) {
            offset++;
        }
        int temp;
        switch (value)
        {
        case 100:	//switches
            //read a value, then read 4 times that many values
            temp = atoi((char*)&sprite_data[offset]);
            while (isdigit(sprite_data[offset])) {
                offset++;
            }
            for (int i = 0; i < temp; i++)
            {
                atoi((char*)&sprite_data[offset]);
                while (isdigit(sprite_data[offset])) {
                    offset++;
                }
                atoi((char*)&sprite_data[offset]);
                while (isdigit(sprite_data[offset])) {
                    offset++;
                }
                atoi((char*)&sprite_data[offset]);
                while (isdigit(sprite_data[offset])) {
                    offset++;
                }
                atoi((char*)&sprite_data[offset]);
                while (isdigit(sprite_data[offset])) {
                    offset++;
                }
            }
            break;
        case 101: //shadow
            //read one value
            break;
        case 102: //objType
            //read one value
            break;
        case 103: //altAttack
            //read one value
            break;
        case 104: //attr
            //read one value
            break;
        case 105: //clothing
            //read a value
            //read 0 or that value of numbers, whichever is higher
            break;
        case 106: //weapons
            //?
            break;
        case 107: //size
            //read 2 numbers
            break;
        case 108: //flyingType
            //read one number
            break;
        case 109: //immaterial
            //read two numbers
            break;
        case 110:
            //read a number and modify the stack with it
            break;
        case 111: //stride
            //read one number
            break;
        case 112: //furniture
            //read one number
            break;
        case 113: //morphEffect
            //read one number
            break;
        case 114: //furnitureSize
            //read one number
            break;
        default:
            printf("?(%d)\n", value);
            break;
        }



        while (offset < sprite_dlength)
        {

            offset++;
        }
    }

    DesKeyInit("~!@#%^$<");	//TODO : move this code to a class and use an object
    init_packs();
    init_tiles();

    change_drawmode(DRAWMODE_LOADING);

    while (!are_you_ready())
    {
        check_requests();
    }
    draw_loading *load;
    int what_server;
    load = (draw_loading*)get_drawmode(false);

    //wait for the user to pick a server
    do
    {
        what_server = load->get_server_pick();
        check_requests();
    } while (what_server == -1);

    server_name = new char[strlen(main_config->get_name(what_server)) + 1];
    strcpy(server_name, main_config->get_name(what_server));

    server = new connection(main_config, what_server);
    proc = new packet(server, this);
    if (get_updates(server, load) > 0)
    {
    }

    //check for custom opcodes
    unsigned char *copcodes;
    copcodes = (unsigned char*)getfiles->load_file("opcodes.txt", 0, FILE_REGULAR3, 0);
    if (copcodes != 0)
    {   //there are custom opcodes for this server
        printf("This server has custom opcodes\n");
        int offset;
        char *data = (char*)copcodes;
        for (int i = 0; i < 256; i++)
        {
            char *p;
            p = strtok(data, "\n");
            if (data != NULL)
                data = NULL;
            int temp;
            sscanf(p, "%d", &temp);
            convert_client_packets[i] = (unsigned char)temp;
        }
        for (int i = 0; i < 256; i++)
        {
            char *p;
            p = strtok(data, "\n");
            if (data != NULL)
                data = NULL;
            int temp;
            sscanf(p, "%d", &temp);
            convert_server_packets[i] = (unsigned char)temp;
        }
        delete [] copcodes;
        copcodes = 0;
    }

    //begin game portion of client
//	if (server->connection_ok() == 1)
    {
        if (server->change() != 1)
        {
            throw "Failed to connect to game server\n";
        }
    }

    init_codepage(0);
    init_math_tables();
//	printf("STUB Load player config\n");
//	printf("STUB Initialize emblem cache\n");
    init_strings();
    load->load_done();
}
Example #19
0
static PyObject*
module_init(void)
{
    PyObject *module, *ts_module, *capi;
    PyObject *copy_reg;

    if (init_strings() < 0)
        return NULL;

#ifdef PY3K
    module = PyModule_Create(&moduledef);
#else
    module = Py_InitModule3("cPersistence", cPersistence_methods,
                            cPersistence_doc_string);
#endif

#ifdef PY3K
    ((PyObject*)&Pertype)->ob_type = &PyType_Type;
#else
    Pertype.ob_type = &PyType_Type;
#endif
    Pertype.tp_new = PyType_GenericNew;
    if (PyType_Ready(&Pertype) < 0)
        return NULL;
    if (PyModule_AddObject(module, "Persistent", (PyObject *)&Pertype) < 0)
        return NULL;

    cPersistenceCAPI = &truecPersistenceCAPI;
#ifdef PY3K
    capi = PyCapsule_New(cPersistenceCAPI, CAPI_CAPSULE_NAME, NULL);
#else
    capi = PyCObject_FromVoidPtr(cPersistenceCAPI, NULL);
#endif
    if (!capi)
        return NULL;
    if (PyModule_AddObject(module, "CAPI", capi) < 0)
        return NULL;

    if (PyModule_AddIntConstant(module, "GHOST", cPersistent_GHOST_STATE) < 0)
        return NULL;

    if (PyModule_AddIntConstant(module, "UPTODATE",
                                cPersistent_UPTODATE_STATE) < 0)
        return NULL;

    if (PyModule_AddIntConstant(module, "CHANGED",
                                cPersistent_CHANGED_STATE) < 0)
        return NULL;

    if (PyModule_AddIntConstant(module, "STICKY",
                                cPersistent_STICKY_STATE) < 0)
        return NULL;

    py_simple_new = PyObject_GetAttrString(module, "simple_new");
    if (!py_simple_new)
        return NULL;

#ifdef PY3K
    copy_reg = PyImport_ImportModule("copyreg");
#else
    copy_reg = PyImport_ImportModule("copy_reg");
#endif
    if (!copy_reg)
        return NULL;

    copy_reg_slotnames = PyObject_GetAttrString(copy_reg, "_slotnames");
    if (!copy_reg_slotnames)
    {
      Py_DECREF(copy_reg);
      return NULL;
    }

    __newobj__ = PyObject_GetAttrString(copy_reg, "__newobj__");
    if (!__newobj__)
    {
      Py_DECREF(copy_reg);
      return NULL;
    }

    if (!TimeStamp)
    {
      ts_module = PyImport_ImportModule("persistent.timestamp");
      if (!ts_module)
        return NULL;
      TimeStamp = PyObject_GetAttrString(ts_module, "TimeStamp");
      Py_DECREF(ts_module);
      /* fall through to immediate return on error */
    }
    return module;
}
Example #20
0
bool main_menu::opening_screen()
{
    // Play title music, whoo!
    play_music( "title" );

    world_generator->set_active_world( NULL );
    world_generator->init();

    init_windows();
    init_strings();
    print_menu( w_open, 0, iMenuOffsetX, iMenuOffsetY );

    if( !assure_dir_exist( FILENAMES["config_dir"] ) ) {
        popup( _( "Unable to make config directory. Check permissions." ) );
        return false;
    }

    if( !assure_dir_exist( FILENAMES["savedir"] ) ) {
        popup( _( "Unable to make save directory. Check permissions." ) );
        return false;
    }

    if( !assure_dir_exist( FILENAMES["templatedir"] ) ) {
        popup( _( "Unable to make templates directory. Check permissions." ) );
        return false;
    }

    for( std::string path : get_files_from_path( ".template", FILENAMES["templatedir"], false,
            true ) ) {
        path = native_to_utf8( path );
        path.erase( path.find( ".template" ), std::string::npos );
        path.erase( 0, path.find_last_of( "\\//" ) + 1 );
        templates.push_back( path );
    }
    std::sort( templates.begin(), templates.end(), std::greater<std::string>() );

    ctxt.register_cardinal();
    ctxt.register_action( "QUIT" );
    ctxt.register_action( "CONFIRM" );
    ctxt.register_action( "DELETE_TEMPLATE" );
    // for the menu shortcuts
    ctxt.register_action( "ANY_INPUT" );
    bool start = false;

    g->u = player();

    // Make [Load Game] the default cursor position if there's game save available
    if( !world_generator->all_worldnames().empty() ) {
        sel1 = 2;
    }

    while( !start ) {
        print_menu( w_open, sel1, iMenuOffsetX, iMenuOffsetY, ( sel1 != 0 ) );

        if( layer == 1 ) {
            if( sel1 == 0 ) { // Print the MOTD.
                const int motdy = ( iMenuOffsetY - mmenu_motd.size() ) * 2 / 3;
                const int motdx = 8 + extra_w / 2;
                for( size_t i = 0; i < mmenu_motd.size(); i++ ) {
                    mvwprintz( w_open, motdy + i, motdx, c_light_red, mmenu_motd[i].c_str() );
                }

                wrefresh( w_open );
                catacurses::refresh();
            }

            std::string action = handle_input_timeout( ctxt );

            std::string sInput = ctxt.get_raw_input().text;
            // check automatic menu shortcuts
            for( size_t i = 0; i < vMenuHotkeys.size(); ++i ) {
                for( auto hotkey : vMenuHotkeys[i] ) {
                    if( sInput == hotkey ) {
                        sel1 = i;
                        action = "CONFIRM";
                    }
                }
            }
            // also check special keys
            if( action == "QUIT" ) {
                if( query_yn( _( "Really quit?" ) ) ) {
                    sel1 = 8;
                    action = "CONFIRM";
                }
            } else if( action == "LEFT" ) {
                if( sel1 > 0 ) {
                    sel1--;
                } else {
                    sel1 = 8;
                }
                on_move();
            } else if( action == "RIGHT" ) {
                if( sel1 < 8 ) {
                    sel1++;
                } else {
                    sel1 = 0;
                }
                on_move();
            }
            if( ( action == "UP" || action == "CONFIRM" ) && sel1 > 0 ) {
                if( sel1 == 6 ) {
                    display_help();
                } else if( sel1 == 7 ) {
                    display_credits();
                } else if( sel1 == 8 ) {
                    return false;
                } else {
                    sel2 = 0;
                    layer = 2;
                    print_menu( w_open, sel1, iMenuOffsetX, iMenuOffsetY, ( sel1 != 0 ) );

                    switch( sel1 ) {
                        case 1:
                            start = new_character_tab();
                            break;
                        case 2:
                            start = load_character_tab();
                            break;
                        case 3:
                            world_tab();
                            break;
                        default:
                            break;
                    }
                }
            }
        } else if( layer == 2 ) {
            if( sel1 == 4 ) { // Special game
                if( MAP_SHARING::isSharing() ) { // Thee can't save special games, therefore thee can't share them
                    layer = 1;
                    popup( _( "Special games don't work with shared maps." ) );
                    continue;
                }

                std::vector<std::string> special_names;
                int xoffset = 32 + iMenuOffsetX  + extra_w / 2;
                int yoffset = iMenuOffsetY - 2;
                int xlen = 0;
                for( int i = 1; i < NUM_SPECIAL_GAMES; i++ ) {
                    std::string spec_name = special_game_name( special_game_id( i ) );
                    special_names.push_back( spec_name );
                    xlen += spec_name.size() + 2;
                }
                xlen += special_names.size() - 1;
                print_menu_items( w_open, special_names, sel2, yoffset, xoffset - ( xlen / 4 ) );

                wrefresh( w_open );
                catacurses::refresh();
                std::string action = handle_input_timeout( ctxt );
                if( action == "LEFT" ) {
                    if( sel2 > 0 ) {
                        sel2--;
                    } else {
                        sel2 = NUM_SPECIAL_GAMES - 2;
                    }
                    on_move();
                } else if( action == "RIGHT" ) {
                    if( sel2 < NUM_SPECIAL_GAMES - 2 ) {
                        sel2++;
                    } else {
                        sel2 = 0;
                    }
                    on_move();
                } else if( action == "DOWN" || action == "QUIT" ) {
                    layer = 1;
                }
                if( action == "UP" || action == "CONFIRM" ) {
                    if( sel2 >= 0 && sel2 < NUM_SPECIAL_GAMES - 1 ) {
                        g->gamemode = get_special_game( special_game_id( sel2 + 1 ) );
                        // check world
                        WORLDPTR world = world_generator->make_new_world( special_game_id( sel2 + 1 ) );
                        if( world == NULL ) {
                            continue;
                        }
                        world_generator->set_active_world( world );
                        try {
                            g->setup();
                        } catch( const std::exception &err ) {
                            debugmsg( "Error: %s", err.what() );
                            g->gamemode.reset();
                            g->u = player();
                            continue;
                        }
                        if( !g->gamemode->init() ) {
                            g->gamemode.reset();
                            g->u = player();
                            continue;
                        }
                        start = true;
                    }
                }
            } else if( sel1 == 5 ) {  // Settings Menu
                int settings_subs_to_display = vSettingsSubItems.size();
                std::vector<std::string> settings_subs;
                int xoffset = 46 + iMenuOffsetX + extra_w / 2;
                int yoffset = iMenuOffsetY - 2;
                int xlen = 0;
                for( int i = 0; i < settings_subs_to_display; ++i ) {
                    settings_subs.push_back( vSettingsSubItems[i] );
                    xlen += vSettingsSubItems[i].size() + 2; // Open and close brackets added
                }
                xlen += settings_subs.size() - 1;
                if( settings_subs.size() > 1 ) {
                    xoffset -= 6;
                }
                print_menu_items( w_open, settings_subs, sel2, yoffset, xoffset - ( xlen / 4 ) );
                wrefresh( w_open );
                catacurses::refresh();
                std::string action = handle_input_timeout( ctxt );
                std::string sInput = ctxt.get_raw_input().text;
                for( int i = 0; i < settings_subs_to_display; ++i ) {
                    for( auto hotkey : vSettingsHotkeys[i] ) {
                        if( sInput == hotkey ) {
                            sel2 = i;
                            action = "CONFIRM";
                        }
                    }
                }

                if( action == "LEFT" ) {
                    if( sel2 > 0 ) {
                        --sel2;
                    } else {
                        sel2 = settings_subs_to_display - 1;
                    }
                    on_move();
                } else if( action == "RIGHT" ) {
                    if( sel2 < settings_subs_to_display - 1 ) {
                        ++sel2;
                    } else {
                        sel2 = 0;
                    }
                    on_move();
                } else if( action == "DOWN" || action == "QUIT" ) {
                    layer = 1;
                }

                if( action == "UP" || action == "CONFIRM" ) {
                    if( sel2 == 0 ) {
                        get_options().show( true );
                        // The language may have changed- gracefully handle this.
                        init_strings();
                        print_menu( w_open, sel1, iMenuOffsetX, iMenuOffsetY, ( sel1 != 0 ) );
                    } else if( sel2 == 1 ) {
                        input_context ctxt_default = get_default_mode_input_context();
                        ctxt_default.display_menu();
                    } else if( sel2 == 2 ) {
                        get_auto_pickup().show();
                    } else if( sel2 == 3 ) {
                        get_safemode().show();
                    } else if( sel2 == 4 ) {
                        all_colors.show_gui();
                    }
                }
            }
        }
    }
    if( start ) {
        g->refresh_all();
        g->draw();
    }
    return start;
}
Example #21
0
int main (int argc, char ** argv)
{
    time_t tm;
    int i, new_mudlib = 0, got_defaults = 0;
    char *p;
    char version_buf[80];
#if 0
    int dtablesize;
#endif
    error_context_t econ;

#ifdef PROTO_TZSET
    void tzset();
#endif

#ifdef INCL_LOCALE_H
    setlocale(LC_ALL, "C");
#endif

#if !defined(__SASC) && (defined(AMITCP) || defined(AS225))
    amiga_sockinit();
    atexit(amiga_sockexit);
#endif
#ifdef WRAPPEDMALLOC
    wrappedmalloc_init();
#endif        /* WRAPPEDMALLOC */
#ifdef DEBUGMALLOC
    MDinit();
#endif

#if (defined(PROFILING) && !defined(PROFILE_ON) && defined(HAS_MONCONTROL))
    moncontrol(0);
#endif
#ifdef USE_TZSET
    tzset();
#endif
    boot_time = get_current_time();

    const0.type = T_NUMBER;
    const0.u.number = 0;
    const1.type = T_NUMBER;
    const1.u.number = 1;

    /* const0u used by undefinedp() */
    const0u.type = T_NUMBER;
    const0u.subtype = T_UNDEFINED;
    const0u.u.number = 0;

    //fake_prog.program_size = 0; //0 anyway

    /*
     * Check that the definition of EXTRACT_UCHAR() is correct.
     */
    p = (char *) &i;
    *p = -10;
    if (EXTRACT_UCHAR(p) != 0x100 - 10) {
        fprintf(stderr, "Bad definition of EXTRACT_UCHAR() in interpret.h.\n");
        exit(-1);
    }

    /*
     * An added test: can we do EXTRACT_UCHAR(x++)?
     * (read_number, etc uses it)
     */
    p = (char *) &i;
    (void) EXTRACT_UCHAR(p++);
    if ((p - (char *) &i) != 1) {
        fprintf(stderr, "EXTRACT_UCHAR() in interpret.h evaluates its argument more than once.\n");
        exit(-1);
    }

    /*
     * Check the living hash table size
     */
    if (CFG_LIVING_HASH_SIZE != 4 && CFG_LIVING_HASH_SIZE != 16 &&
            CFG_LIVING_HASH_SIZE != 64 && CFG_LIVING_HASH_SIZE != 256 &&
            CFG_LIVING_HASH_SIZE != 1024 && CFG_LIVING_HASH_SIZE != 4096) {
        fprintf(stderr, "CFG_LIVING_HASH_SIZE in options.h must be one of 4, 16, 64, 256, 1024, 4096, ...\n");
        exit(-1);
    }

#ifdef RAND
    srand(get_current_time());
#else
#  ifdef DRAND48
    srand48(get_current_time());
#  else
#    ifdef RANDOM
    srandom(get_current_time());
#    else
    fprintf(stderr, "Warning: no random number generator specified!\n");
#    endif
#  endif
#endif
    current_time = get_current_time();
    /*
     * Initialize the microsecond clock.
     */
    init_usec_clock();

    /* read in the configuration file */

    got_defaults = 0;
    for (i = 1; (i < argc) && !got_defaults; i++) {
        if (argv[i][0] != '-') {
            set_defaults(argv[i]);
            got_defaults = 1;
        }
    }
    get_version(version_buf);
    if (!got_defaults) {
        fprintf(stderr, "%s for %s.\n", version_buf, ARCH);
        fprintf(stderr, "You must specify the configuration filename as an argument.\n");
        exit(-1);
    }

    printf("Initializing internal tables....\n");
    init_strings();   /* in stralloc.c */
    init_otable();    /* in otable.c */
    init_identifiers();   /* in lex.c */
    init_locals();              /* in compiler.c */

    /*
     * If our estimate is larger than FD_SETSIZE, then we need more file
     * descriptors than the operating system can handle.  This is a problem
     * that can be resolved by decreasing MAX_USERS, MAX_EFUN_SOCKS, or both.
     *
     * Unfortunately, since neither MAX_USERS or MAX_EFUN_SOCKS exist any more,
     * we have no clue how many we will need.  This code really should be
     * moved to places where ENFILE/EMFILE is returned.
     */
#if 0
    if (dtablesize > FD_SETSIZE) {
        fprintf(stderr, "Warning: File descriptor requirements exceed system capacity!\n");
        fprintf(stderr, "         Configuration exceeds system capacity by %d descriptor(s).\n",
                dtablesize - FD_SETSIZE);
    }
#ifdef HAS_SETDTABLESIZE
    /*
     * If the operating system supports setdtablesize() then we can request
     * the number of file descriptors we really need.  First check to see if
     * wee already have enough.  If so dont bother the OS. If not, attempt to
     * allocate the number we estimated above.  There are system imposed
     * limits on file descriptors, so we may not get as many as we asked for.
     * Check to make sure we get enough.
     */
    if (getdtablesize() < dtablesize)
        if (setdtablesize(dtablesize) < dtablesize) {
            fprintf(stderr, "Warning: Could not allocate enough file descriptors!\n");
            fprintf(stderr, "         setdtablesize() could not allocate %d descriptor(s).\n",
                    getdtablesize() - dtablesize);
        }
    /*
     * Just be polite and tell the administrator how many he has.
     */
    fprintf(stderr, "%d file descriptors were allocated, (%d were requested).\n",
            getdtablesize(), dtablesize);
#endif
#endif
    time_to_clean_up = TIME_TO_CLEAN_UP;
    max_cost = MAX_COST;
    reserved_size = RESERVED_SIZE;
    max_array_size = MAX_ARRAY_SIZE;
    if(max_array_size > 65535){
        fprintf(stderr, "Maximum array size can not exceed 65535");
        max_array_size = 65535;
    }
    max_buffer_size = MAX_BUFFER_SIZE;
    max_string_length = MAX_STRING_LENGTH;
    mud_lib = (char *) MUD_LIB;
    set_inc_list(INCLUDE_DIRS);
    if (reserved_size > 0)
        reserved_area = (char *) DMALLOC(reserved_size, TAG_RESERVED, "main.c: reserved_area");
    for (i = 0; i < sizeof consts / sizeof consts[0]; i++)
        consts[i] = exp(-i / 900.0);
    reset_machine(1);
    /*
     * The flags are parsed twice ! The first time, we only search for the -m
     * flag, which specifies another mudlib, and the D-flags, so that they
     * will be available when compiling master.c.
     */
    for (i = 1; i < argc; i++) {
        if (argv[i][0] != '-')
            continue;
        switch (argv[i][1]) {
            case 'D':
                if (argv[i][2]) {
                    lpc_predef_t *tmp = ALLOCATE(lpc_predef_t, TAG_PREDEFINES,
                            "predef");
                    tmp->flag = argv[i] + 2;
                    tmp->next = lpc_predefs;
                    lpc_predefs = tmp;
                    continue;
                }
                fprintf(stderr, "Illegal flag syntax: %s\n", argv[i]);
                exit(-1);
            case 'N':
                no_ip_demon++;
                continue;
#ifdef HAS_CONSOLE
            case 'C':
                has_console = 1;
                continue;
#endif
#ifdef YYDEBUG
            case 'y':
                yydebug = 1;
                continue;
#endif        /* YYDEBUG */
            case 'm':
                mud_lib = alloc_cstring(argv[i] + 2, "mudlib dir");
                if (chdir(mud_lib) == -1) {
                    fprintf(stderr, "Bad mudlib directory: %s\n", mud_lib);
                    exit(-1);
                }
                new_mudlib = 1;
                break;
        }
    }
    if (!new_mudlib && chdir(mud_lib) == -1) {
        fprintf(stderr, "Bad mudlib directory: %s\n", mud_lib);
        exit(-1);
    }
    time(&tm);
    debug_message("----------------------------------------------------------------------------\n%s (%s) starting up on %s - %s\n\n", MUD_NAME, version_buf, ARCH, ctime(&tm));

    add_predefines();
#ifdef WIN32
    _tzset();
#endif

#ifndef NO_IP_DEMON
    if (!no_ip_demon && ADDR_SERVER_IP)
        init_addr_server(ADDR_SERVER_IP, ADDR_SERVER_PORT);
#endif        /* NO_IP_DEMON */

    set_eval(max_cost);

    save_context(&econ);
    if (SETJMP(econ.context)) {
        debug_message("The simul_efun (%s) and master (%s) objects must be loadable.\n",
                SIMUL_EFUN, MASTER_FILE);
        exit(-1);
    } else {
        init_simul_efun(SIMUL_EFUN);
        init_master();
    }
    pop_context(&econ);

    for (i = 1; i < argc; i++) {
        if (argv[i][0] != '-') {
            continue;
        } else {
            /*
             * Look at flags. -m and -o has already been tested.
             */
            switch (argv[i][1]) {
                case 'D':
                case 'N':
                case 'm':
                case 'y':
                case 'C':
                    continue;
                case 'f':
                    save_context(&econ);
                    if (SETJMP(econ.context)) {
                        debug_message("Error while calling master::flag(\"%s\"), aborting ...\n", argv[i] + 2);
                        exit(-1);
                    }
                    push_constant_string(argv[i] + 2);
                    apply_master_ob(APPLY_FLAG, 1);
                    if (MudOS_is_being_shut_down) {
                        debug_message("Shutdown by master object.\n");
                        exit(0);
                    }
                    pop_context(&econ);
                    continue;
                case 'e':
                    e_flag++;
                    continue;
                case 'p':
                    external_port[0].port = atoi(argv[i] + 2);
                    continue;
                case 'd':
#ifdef DEBUG_MACRO
                    if (argv[i][2])
                        debug_level_set(&argv[i][2]);
                    else
                        debug_level |= DBG_d_flag;
#else
                    debug_message("Driver must be compiled with DEBUG_MACRO on to use -d.\n");
#endif
                    break;
                case 'c':
                    comp_flag++;
                    continue;
                case 't':
                    t_flag++;
                    continue;
                default:
                    debug_message("Unknown flag: %s\n", argv[i]);
                    exit(-1);
            }
        }
    }
    if (MudOS_is_being_shut_down)
        exit(1);
    if (*(DEFAULT_FAIL_MESSAGE)) {
        char buf[8192];

        strcpy(buf, DEFAULT_FAIL_MESSAGE);
        strcat(buf, "\n");
        default_fail_message = make_shared_string(buf);
    } else
        default_fail_message = "What?\n";
#ifdef PACKAGE_MUDLIB_STATS
    restore_stat_files();
#endif
    preload_objects(e_flag);
#ifdef SIGFPE
    signal(SIGFPE, sig_fpe);
#endif
#ifdef TRAP_CRASHES
#ifdef SIGUSR1
    signal(SIGUSR1, sig_usr1);
#endif
#ifdef SIGUSR2
    signal(SIGUSR2, sig_usr2);
#endif
    signal(SIGTERM, sig_term);
    signal(SIGINT, sig_int);
#ifndef DEBUG
#if defined(SIGABRT)
    signal(SIGABRT, sig_abrt);
#endif
#ifdef SIGIOT
    signal(SIGIOT, sig_iot);
#endif
#ifdef SIGHUP
    signal(SIGHUP, sig_hup);
#endif
#ifdef SIGBUS
    signal(SIGBUS, sig_bus);
#endif
    signal(SIGSEGV, sig_segv);
    signal(SIGILL, sig_ill);
#endif        /* DEBUG */
#endif
#ifndef WIN32
#ifdef USE_BSD_SIGNALS
    signal(SIGCHLD, sig_cld);
#else
    signal(SIGCLD, sig_cld);
#endif
#endif

#ifdef HAS_CONSOLE
    if(has_console >= 0)
        signal(SIGTTIN, sig_ttin);
    signal(SIGTTOU, SIG_IGN);
#endif

    backend();
    return 0;
}
Example #22
0
int main() {
	int res, try, retries;
	char *query_string, *abf_api_url, *api_token;

	char *log_level = getenv("LOG_LEVEL");
	if (init_logger(log_level == NULL ? "INFO" : log_level) < 0) {
		return 2;
	}
	register_thread("Main");

	log_printf(LOG_INFO, "Starting DNS check...\n");
	res = check_dns();
	if (res < 0) {
		log_printf(LOG_FATAL, "Check DNS failed, can't resolve github.com. Exiting...\n");
		return 6;
	} else {
		log_printf(LOG_INFO, "Successfuly resolved github. Continuing.\n");
	}

	usergroup omv_mock = get_omv_uid_mock_gid();
	if(omv_mock.omv_uid == 0) {
		log_printf(LOG_FATAL, "User omv doesn't exist. Exiting...\n");
		return 7;
	}
	if(omv_mock.mock_gid == 0) {
		log_printf(LOG_FATAL, "Group mock doesn't exist. Exiting...\n");
		return 8;
	}

	res = process_config(&abf_api_url, &api_token, &query_string);
	if (res < 0) {
		log_printf(LOG_FATAL, "Failed to process config, exiting.\n");
		return 1;
	}

	init_strings(api_token);

	init_api(abf_api_url, api_token);

	if(start_statistics_thread(query_string)) {
		log_printf(LOG_FATAL, "Failed to initialize statistics thread. Exiting...\n");
		return 5;
	}

	while(1) {
		char *job;
		if(api_jobs_shift(&job, query_string)) {
			sleep(10);
			continue;
		}

		char *build_id, *distrib_type;
		char **env;
		int ttl;

		res = parse_job_description(job, &build_id, &ttl, &distrib_type, &env);
		free(job);
		if(res < 0) {
			sleep(10);
			continue;
		}

		log_printf(LOG_INFO, "Starting build with build_id %s.\n", build_id);
		log_printf(LOG_INFO, "Sending build start notification to ABF.\n");
		retries = 5;
		try = 0;
		set_busy_status(1, build_id);
		int build_start_success = 0;
		while(retries) {
			log_printf(LOG_INFO, "Try #%d: Sending data to ABF.\n", try + 1);
			if(!api_jobs_feedback(build_id, BUILD_STARTED, hostname_payload)) {
				log_printf(LOG_INFO, "Try #%d: Data sent.\n", try + 1);
				build_start_success = 1;
				break;
			} else {
				log_printf(LOG_ERROR, "Try #%d: Failed to send data to ABF. Sleeping for %d seconds and retrying...\n", try + 1, 1 << try);
			}
			retries--;
			sleep(1 << try);
			try++;
		}

		if (!build_start_success) {
			log_printf(LOG_ERROR, "Failed to send build start to ABF, aborting build.\n");
			free(build_id);
			free(distrib_type);
			for(int i = 0; i < res; i++) {
				free(env[i]);
			}
			free(env);
			set_busy_status(0, NULL);
			continue;
		}

		child script = exec_build(distrib_type, (char * const *)env, omv_mock);

		int live_inspector_started = 1;
		log_printf(LOG_INFO, "Starting live inspector, build's time to live is %d seconds.\n", ttl);
		if(start_live_inspector(ttl, script.pid, build_id) < 0) {
			live_inspector_started = 0;
			log_printf(LOG_WARN, "Live inspector failed to start. Job canceling and timeout will be unavailable.\n");
		}

		int live_logger_started = 1;
		log_printf(LOG_INFO, "Starting live logger.\n");
		if(start_live_logger(build_id, script.read_fd) < 0) {
			live_logger_started = 0;
			log_printf(LOG_WARN, "Live logger failed to start. Live log will be unavailable.\n");
		}

		int status, build_status = BUILD_COMPLETED;
		waitpid(script.pid, &status, 0);
		int canceled = 0;
		if (live_inspector_started) {
			canceled = stop_live_inspector();
		}
		if (live_logger_started) {
			stop_live_logger();
		}

		int exit_code = 0;
		if (canceled) {
			build_status = BUILD_CANCELED;
		}
		else if(WIFEXITED(status)) {
			exit_code = WEXITSTATUS(status);
			switch(exit_code) {
				case 0:
					build_status = BUILD_COMPLETED;
					break;
				case 5:
					build_status = TESTS_FAILED;
					break;
				default:
					build_status = BUILD_FAILED;
			}
		}
		else if(WIFSIGNALED(status)) {
			exit_code = 255;
			build_status = BUILD_FAILED;
		}

		for(int i = 0; i < res; i++) {
			free(env[i]);
		}
		free(env);
		free(distrib_type);

		log_printf(LOG_INFO, "Build is over with status %s.\n", build_statuses_str[build_status]);

		mkdir(home_output, 0666);
		system(move_output_cmd);


		system(upload_cmd);

		char *container_data = read_file(container_data_path);
		char *results = read_file("/tmp/results.json");
		char *commit_hash = read_file(commit_hash_path);
		if(commit_hash != NULL) {
			commit_hash[40] = '\0';
		}

		char *fail_reason = NULL;
		if (build_status == BUILD_FAILED) {
			fail_reason = read_file(fail_reason_path);
			if (fail_reason != NULL) {
				for (unsigned int i = 0; i < strlen(fail_reason); i++) {
					if (!isprint(fail_reason[i]) || fail_reason[i] == '"') {
						fail_reason[i] = ' ';
					}
				}
			}
		}

		char *args = xmalloc((container_data ? strlen(container_data) : 0) + (results ? strlen(results) : 0) + 2048);
		sprintf(args, build_completed_args_fmt, (results ? results : "[]"), \
				(container_data ? container_data : "{}"), exit_code, (commit_hash ? commit_hash : ""),
				(fail_reason ? fail_reason : ""));

		retries = 5;
		try = 0;
		while(retries) {
			log_printf(LOG_INFO, "Try #%d: Sending data to ABF\n", try + 1);
			if(!api_jobs_feedback(build_id, build_status, args)) {
				log_printf(LOG_INFO, "Data sent.\n");
				break;
			} else {
				log_printf(LOG_ERROR, "Failed to send data to ABF. Sleeping for %d seconds and retrying...\n", 1 << try);
			}
			retries--;
			sleep(1 << try);
			try++;
		}

		set_busy_status(0, NULL);
		free(args);
		free(build_id);

		if(commit_hash) {
			free(commit_hash);
		}
		if(results) {
			free(results);
		}
		if(container_data) {
			free(container_data);
		}
		if(fail_reason) {
			free(fail_reason);
		}
	}

	return 0;
}