Exemplo n.º 1
0
int
print_usage (void) {

	print_banner ();

	printf (" usage: ./%s [options]\n\n", APP_NAME);

	printf (" UDP SCAN MODE:\n -u\t\t\tenables UDP scan mode [sends UDP probes]\n");

	printf (" TCP SCAN MODES:\n -a\t\t\tenables ACK scan mode [TCP - ACK flag set]\n");
	printf (" -r\t\t\tenables RST scan mode [TCP - RST flag set]\n");
	printf (" -s\t\t\tenables SYN scan mode [TCP - SYN flag set]\n");
	printf (" -f\t\t\tenables FIN scan mode [TCP - FIN flag set]\n");

	printf (" ICMP SCAN MODES:\n -e\t\t\tenables ECHO scan mode [sends ICMP ECHO-REQUESTS]\n");
	printf (" -t\t\t\tenables TSTAMP scan mode [sends ICMP TIMESTAMP-REQUESTS]\n");

	printf (" MISC:\n -i <device>\t\tnetwork interface to use for arp-secur session\n");
	printf (" -p <port_number>\tTCP / UDP port to use for the probe packet (1 - 65535)\n");
	printf (" -P\t\t\tenables PREVENT mode to auto-delete poisoned entries from ARP cache\n");
	printf (" -o\t\t\tenables summary popup for current session\n");
	printf (" -g\t\t\tsets reply time-out in usecs for probe packets (1 - 9)\n");
	printf (" -v\t\t\tenables TCPDUMP-like HEX - ASCII layout of packet contents\n\n");

	return 0;

}//usage
Exemplo n.º 2
0
int
main(void)
{
	char	c;

	init_devices();

	comcninit();

	opt_subcmd_read(NULL);

	print_banner();

	c = awaitkey();
	if (c != '\r' && c != '\n' && c != '\0') {
		printf("type \"?\" or \"h\" for help.\n");
		bootmenu(); /* does not return */
	}

	command_boot(NULL);
	/*
	 * command_boot() returns only if it failed to boot.
	 * we enter to boot menu in this case.
	 */
	bootmenu();
	
	return 0;
}
Exemplo n.º 3
0
int main(int argc, char** argv) {
  spaceship * s;
  double tmp=0;
  if (argc<=1) {
    printf("Warning: tempo de sleep nao definido, usando valor default 8ms. (chame o programa como ./eagle2014 <sleeptime in ms>\n");
  } else if (argc==2) {
    tmp=strtod(argv[1],NULL);
  } else {
    printf("Demasiados argumentos enviados para o programa, saindo!\n");
    exit(0);
  }
  if (tmp<1 || tmp > 200) {
    tmp = TARGET_FPS;
    printf("W: sleep alterado para " PRETOSTRING(TARGET_FPS) " frames por segundo\n");
  } else {
    tmp = 1000.0/tmp;
  }
  s = spc_init(0,0,0,tmp);
  print_banner();

  while(!menu(s));

  spc_destroy(s);
  return 0;
}
Exemplo n.º 4
0
Arquivo: bxcommit.c Projeto: iver6/BA
int CDECL main()
{
  char filename[256];
  char tmplogname[256];
  char redologname[256];
  int  remove;

  print_banner();
  filename[0] = 0;
  redologname[0] = 0;

  if (ask_string("\nWhat is the flat image name?\n", "c.img", filename) < 0)
    fatal(EOF_ERR);

  snprintf(tmplogname,256,"%s%s", filename, UNDOABLE_REDOLOG_EXTENSION);

  if (ask_string("\nWhat is the redolog name?\n", tmplogname, redologname) < 0)
    fatal(EOF_ERR);

  if (ask_yn("\nShall I remove the redolog afterwards?\n", 1, &remove) < 0)
    fatal(EOF_ERR);

  commit_redolog(filename, redologname);

  if (remove) {
    if (unlink(redologname) != 0)
       fatal("ERROR: while removing the redolog !\n");
  }

  // make picky compilers (c++, gcc) happy,
  // even though we leave via 'myexit' just above
  return 0;
}
Exemplo n.º 5
0
Arquivo: core.c Projeto: bolry/lci
int lci_main(int argc, char *argv[])
{
	handle_possible_lci_options(&argc, &argv[0]);
	print_banner();
	only_run_lint_if_compile_and_or_link(argc, &argv[0]);
	flush_all();
	if (run_compiler && run_lint) {
		/*
		 * run compiler first and if OK then run lint
		 */
		int status;
		pid_t cpid;
		pid_t w;

		cpid = fork();
		if (-1 == cpid) {
			perror(TOOL_NAME ": fork");
			exit(EXIT_FAILURE);
		}
		if (0 == cpid) {
			(void)execvp(argv[1], &argv[1]);
			perror(TOOL_NAME ": execvp");
			_exit(EXIT_FAILURE);
		}
		errno = 0;
		w = waitpid(cpid, &status, 0);
		if (w != cpid) {
			perror(TOOL_NAME ": waitpid");
			exit(EXIT_FAILURE);
		}
		if (WIFEXITED(status) && (WEXITSTATUS(status) != EXIT_SUCCESS)) {
			if (force_lint) {
				/*
				 * run lint anyway
				 */
			} else {
				exit(WEXITSTATUS(status));
			}
		}
		if (WIFSIGNALED(status))
			exit(WTERMSIG(status));
		argv[0] = lint;
		(void)execvp(argv[0], &argv[0]);
		perror(TOOL_NAME ": execvp");
	} else if (run_compiler) {
		(void)execvp(argv[1], &argv[1]);
		perror(TOOL_NAME ": execvp");
	} else if (run_lint) {
		argv[0] = lint;
		(void)execvp(argv[0], &argv[0]);
		perror(TOOL_NAME ": execvp");
	} else {
		/*
		 * a do nothing option
		 */
		exit(EXIT_SUCCESS);
	}
	exit(EXIT_FAILURE);
}
Exemplo n.º 6
0
void print_usage() {
  print_banner();
  /* Removed: [-s server_name][-u username][-p password] */
  fprintf( stderr, \
           "Usage: NWBACKUP [-d | -f][-l logfile] [backup_name] [local_dir]\n" \
           "  NWBACKUP -r[-l logfile] [backup_name] [local_dir] \n" \
           "  [-d | -f]: Differential or full backup (default full).\n" \
           "  -r: Perform restore. Does NOT need to be first argument.\n" \
           "  Default logfile name is [backup_name].LOG.\n");
}
Exemplo n.º 7
0
int test_blink_n_shift(void)
{
    print_banner("Blink & Shift");
    puts("This tests the blink indicator and shift functionality");

    TEST_BLINK_OR_SHIFT(blink);
    TEST_BLINK_OR_SHIFT(shift);

    return 0;
}
Exemplo n.º 8
0
//---------------------------------------------------------------------------------------------------------------------------------------------------
int main(int argc, char *argv[]) {
	int r          = 0;
	char *username = NULL;
	char *tty      = NULL;
    char *ip       = NULL;
	int paranoid   = 0;

    if(argc < 2)
        usage(argv[0]);

	while((r = getopt(argc, argv, OPTSTRING)) != -1) {
		switch(r) {
			case 'u':
				username = optarg;
				break;
			case 't':
				tty = optarg;
				break;
            case 'i':
                ip = optarg;
                break;
			case 'p':
				paranoid = 1;
				break;
			default:
				return -1;
		}
	}

    print_banner();

	if(getuid() != 0)
		printf("[+] You should be root\n");

    printf("[*] User:     %s\n", username);
    printf("[*] TTY:      %s\n", tty);
    printf("[*] IP:       %s\n", ip);
	printf("[*] Paranoid: %s\n", (paranoid == 1) ? "yes" : "no");

	init_paths();

    if(username && tty) {
        clear_system_layer(username, tty);
	}
    if(ip) {
        clear_application_layer(ip);
	}
	if(paranoid == 1) {
		clear_paranoid_layer();
	}

    printf("\n[*] Cleaning is complete\n");
	return 0;
}
Exemplo n.º 9
0
int main(int ac, char **argv)
{
	struct rlimit r = {1024*1024, RLIM_INFINITY};
	char filename[256];
	int i;

	snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);

	if (setrlimit(RLIMIT_MEMLOCK, &r)) {
		perror("setrlimit(RLIMIT_MEMLOCK)");
		return 1;
	}

	if (load_bpf_file(filename)) {
		printf("%s", bpf_log_buf);
		return 1;
	}

	for (i = 1; i < ac; i++) {
		if (strcmp(argv[i], "-a") == 0) {
			full_range = true;
		} else if (strcmp(argv[i], "-t") == 0) {
			text_only = true;
		} else if (strcmp(argv[i], "-h") == 0) {
			printf("Usage:\n"
			       "  -a display wider latency range\n"
			       "  -t text only\n");
			return 1;
		}
	}

	printf("  heatmap of IO latency\n");
	if (text_only)
		printf("  %s", sym[num_colors - 1]);
	else
		printf("  %s %s", color[num_colors - 1], nocolor);
	printf(" - many events with this latency\n");

	if (text_only)
		printf("  %s", sym[0]);
	else
		printf("  %s %s", color[0], nocolor);
	printf(" - few events\n");

	for (i = 0; ; i++) {
		if (i % 20 == 0)
			print_banner();
		print_hist(map_fd[1]);
		sleep(2);
	}

	return 0;
}
Exemplo n.º 10
0
int main( int argc, char **argv )
/*******************************/
{
    int     rc;

#ifndef __WATCOMC__
    _argc = argc;
    _argv = argv;
#endif

    if( argc <= 1 ) {
        /* no arguments: just tell the user who I am */
        puts( "Usage: owcc [-?] [options] file ..." );
        exit( EXIT_SUCCESS );
    }

    errno = 0; /* Standard C does not require fopen failure to set errno */
    if( (Fp = fopen( TEMPFILE, "w" )) == NULL ) {
        /* Message before banner decision as '@' option uses Fp in Parse() */
        PrintMsg( WclMsgs[UNABLE_TO_OPEN_TEMPORARY_FILE], TEMPFILE,
            strerror( errno ) );
        exit( EXIT_FAILURE );
    }
    MemInit();
    ProcMemInit();
    /* destruct the temp. linker script in case of -? or parse errors */
    atexit( ExitHandler );
    rc = Parse( argc, argv );
    if( rc == 0 ) {
        if( !Flags.be_quiet ) {
            print_banner();
        }
        rc = CompLink();
    }
    if( rc == 1 ) {
        fclose( Fp );
        Fp = NULL;
    }
    if( Link_Name != NULL ) {
        if( strfcmp( Link_Name, TEMPFILE ) != 0 ) {
            remove( Link_Name );
            rename( TEMPFILE, Link_Name );
        }
    } else {
        remove( TEMPFILE );
    }
    ProcMemFini();
    MemFini();
    return( rc == 0 ? 0 : 1 );
}
Exemplo n.º 11
0
void
command_consdev(char *arg)
{
	const struct cons_devs *cdp;

	for (cdp = cons_devs; cdp->name; cdp++) {
		if (!strcmp(arg, cdp->name)) {
			initio(cdp->tag);
			print_banner();
			return;
		}
	}
	printf("invalid console device.\n");
}
Exemplo n.º 12
0
/* returns process id of new process, prompts for username and starts /bin/login */
pid_t 
start_login(int slavefd) {
  pid_t pid;
  static char *username;

  assert(slavefd >= 0);

  if ((pid = fork()) == 0) {
    char *argv[10];
    char *envp[2];
    int argc = 0;
    /* child */
    close(master);
    close(console);

    dup2(slavefd,0);
    dup2(slavefd,1);
    dup2(slavefd,2);
    if (slave > 2) close(slavefd);
    settitle("consoled: login");

    if (setsid() == -1) {
      fprintf(stderr,"setsid failed: errno %d\n",errno);
      exit(-1);
    }
    if (ioctl(0, TIOCSCTTY, (char *)0) < 0) {
      fprintf(stderr,"ioctl slave TIOSCTTY failed: %d,%d\n",pid,errno);
      exit(-1);
    }
    print_banner();
    username = getloginname();
    if (username == NULL) exit(-1);
    envp[0] = "TERM=pc3";
    envp[1] = NULL;
    
    argv[argc++] = "login";
    argv[argc++] = "-p";	/* preserve environment */
    argv[argc++] = "-h";
    argv[argc++] = "localhost";
    argv[argc++] = username;
    argv[argc] = NULL;
    if (execve(LOGIN,argv,envp) == -1) {
      fprintf(stderr,"exec failed\n");
      exit(-1);
    }
    /* never reached */
  }
  return pid;
}
Exemplo n.º 13
0
void loop() {
	char str[STRSZ];
	int len;

	print_banner();
	for (;;) {
		if ((len = read_len()) == -1)
			break;
		if (read_str(str, len) == -1)
			break;
		if (crypt_str(str, len) == -1)
			break;
	}
	fprintf(fdclient, "Bye\n");
	fflush(fdclient);
}
int main(int argc, char **argv)
{
  Prover_input input;
  int return_code;

  print_banner(argc, argv, PROVER_NAME, PROGRAM_VERSION, PROGRAM_DATE, FALSE);

  /***************** Initialize and read the input ***************************/

  input = std_prover_init_and_input(argc, argv,
			    FALSE,          // don't clausify
			    TRUE,           // echo input to stdout
			    KILL_UNKNOWN);  // unknown flags/parms are fatal

  if (input->usable || input->demods)
    fatal_error(PROVER_NAME ": all input clauses must be in sos, assumptions, "
		"or goals list");
    
  /***************** Search for a proof **************************************/

  if (flag(input->options->auto_denials)) {
    clear_flag(input->options->auto_denials, TRUE);
    printf("\n%% clear(auto_denials), because it is incompatiable with "
	   "FOF reduction.\n");
  }

  /***************** Search for a proof **************************************/

  return_code = foffer(input);

  /***************** Print result message and exit ***************************/

  if (return_code == MAX_PROOFS_EXIT) {
    printf("\nTHEOREM PROVED\n");
    if (!flag(input->options->quiet))
      fprintf(stderr, "\nTHEOREM PROVED\n");
  }
  else {
    printf("\nSEARCH FAILED\n");
    if (!flag(input->options->quiet))
      fprintf(stderr, "\nSEARCH FAILED\n");
  }

  exit_with_message(stdout, return_code);
  exit(1);  // to satisfy the compiler (won't be called)
}  // main
Exemplo n.º 15
0
void
boot2(uint32_t boot_biossector)
{
	int currname;
	int c;

	/* Initialize hardware */
	tick_init();

	/* Initialize console */
	cninit(boot_params.bp_consdev);

	print_banner();

	/* try to set default device to what BIOS tells us */
	bios2dev(0x40, &default_devname, &default_unit,
		boot_biossector, &default_partition);

	/* if the user types "boot" without filename */
	default_filename = DEFFILENAME;

	printf("Press return to boot now, any other key for boot menu\n");
	currname = 0;
	for (;;) {
		printf("booting %s - starting in ", 
		    sprint_bootsel(names[currname][0]));

		c = awaitkey(boot_params.bp_timeout, 1);
		if ((c != '\r') && (c != '\n') && (c != '\0')) {
			printf("type \"?\" or \"help\" for help.\n");
			bootmenu(); /* does not return */
		}

		/*
		 * try pairs of names[] entries, foo and foo.gz
		 */
		/* don't print "booting..." again */
		bootit(names[currname][0], 0, 0);
		/* since it failed, try compressed bootfile. */
		bootit(names[currname][1], 0, 1);
		/* since it failed, try switching bootfile. */
		currname = (currname + 1) % NUMNAMES;
	}
}
Exemplo n.º 16
0
Arquivo: main.c Projeto: 0ida/coreboot
int main(void)
{
	extern unsigned long _binary_builtin_lar_start;
	struct LAR *lar;

	print_banner();

	lar = openlar((void *)&_binary_builtin_lar_start);

	if (lar == NULL) {
		printf("[CHOOSER]: Unable to scan the attached LAR file\n");
		return -1;
	}

	get_configuration(lar);

	if (bayoucfg.n_entries == 0) {
		printf("[CHOOSER]:  No payloads were found in the LAR\n");
		return -1;
	}

	/*
	 * If timeout == 0xFF, then show the menu immediately.
	 * If timeout is zero, then find and run the default item immediately.
	 * If there is no default item, then show the menu.
	 * If timeout is anything else, then show a message and wait for a
	 * keystroke. If there is no keystroke in time then run the default.
	 * If there is no default then show the menu.
	 */
	if (bayoucfg.timeout != 0xFF) {
		struct payload *d = payload_get_default();

		if (d != NULL) {
			if (bayoucfg.timeout == 0)
				run_payload(d);
			else
				run_payload_timeout(d, bayoucfg.timeout);
		}
	}

	menu();

	return 0;
}
Exemplo n.º 17
0
int test_leds(void)
{
    print_banner("LEDs");
    puts("This cycles the LEDs through all possible states");

    TEST_LED_MONO(FIRE);
    TEST_LED_COLOR(A);
    TEST_LED_COLOR(B);
    TEST_LED_COLOR(D);
    TEST_LED_COLOR(E);
    TEST_LED_COLOR(T1);
    TEST_LED_COLOR(T2);
    TEST_LED_COLOR(T3);
    TEST_LED_COLOR(POV);
    TEST_LED_COLOR(CLUTCH);
    TEST_LED_MONO(THROTTLE);

    return 0;
}
Exemplo n.º 18
0
int APIENTRY WinMain(HINSTANCE instance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    inst = instance;

    win32_init();

    speed=1000;
    play_f=-1;
    play_state=-1;
    tsx=tsy=0;

    defsx=80;
    defsy=25;

    vt=tty_init(defsx, defsy, 1);
    vt->cp437=1;

    if (*lpCmdLine=='"')        // FIXME: proper parsing
    {
        strncpy(filename, lpCmdLine+1, MAXFILENAME-1);
        filename[strlen(filename)-1]=0;
    }
    else
        strncpy(filename, lpCmdLine, MAXFILENAME-1);
    filename[MAXFILENAME-1]=0;

    create_window(nCmdShow);

    print_banner();
    draw_size();
    UpdateWindow(wndMain);

    ttr=0;

    if (*filename)
        if (!start_file(filename))
        {
            tty_printf(vt, "\n\e[41;1mFile not found: %s\e[0m\n", filename);
            *filename=0;
            redraw_term();
        }
Exemplo n.º 19
0
static void
bootcmd_consdev(char *arg)
{
	const struct cons_devs *cdp;
	char *p;
	int speed = 9600;

	p = strchr(arg, ' ');
	if (p != NULL) {
		*p++ = '\0';
		speed = atoi(p);
	}
	for (cdp = cons_devs; cdp->name != NULL; cdp++) {
		if (strcmp(arg, cdp->name) == 0) {
			consinit(cdp->tag, speed);
			print_banner();
			return;
		}
	}
	printf("invalid console device.\n");
}
int main(int argc, char* argv[])
{

	int handle = -1; 
	print_banner();




	handle = PasInit();
	PasStart(handle);


	printf("\n--------------- Detect devices -------------------------------------------\n");
	test_find_devices(handle);

	printf("\n-------------- Number of Channels ----------------------------------------\n");
	test_channels(handle);

	printf("\n-------------- Sensor attributes -----------------------------------------\n");	
	test_print_some_good_stuff_for_all_sensors(handle);

	printf("\n-------------- Read one shot data ----------------------------------------\n");
	test_read_data(handle,2); /* 2 -- do the test twice */

	printf("\n-------------- Read continous data ---------------------------------------\n");	
	test_read_continuous_data(handle,2); /* 2 -- do the test twice */
	

	PasStop(handle);
	PasDelete(handle);
	
#ifdef _WINDOWS
	// do this on windows since the cmd window might close automatically otherwise
	printf("\n>>>>Press enter to end the program<<<<\n");
	getchar();
#endif
	
	return 0;
}
Exemplo n.º 21
0
int main()
{
    srand(time(NULL));

    int secret = rand() % 1000000 + 1;
    char guess[9];

    print_banner();

    puts("**************************************************************************************");
    puts("|              1 to 1000000, 20 LOTTERY TICKETS. CAN YOU DO IT??                     |");
    puts("**************************************************************************************");
    fflush(stdout);

    signal(SIGALRM, handler);

    for(int i = 0; i < 20; i++) {
        printf("TICKET #%02d => ", i+1);
        fflush(stdout);
        alarm(2);
        fgets(guess, sizeof(guess), stdin);

        if (atoi(guess) == secret) {
            puts("flag{Y0u_4r3_RNG_G0d}");
            fflush(stdout);
            exit(0);
        } else if(atoi(guess) > secret) {
            puts("THE MYSTICAL COW SAYS: TOO HIGH");
            fflush(stdout);
        } else {
            puts("THE MYSTICAL COW SAYS: TOO LOW");
            fflush(stdout);
        }
    }
    puts("\nYOU RAN OUT OF TICKETS. SPENT ALL YOUR MONEY. YOU ARE BROKE. HAVE A NICE LIFE!");
    fflush(stdout);

    return 0;
}
Exemplo n.º 22
0
static void do_shutdown(struct context *ctx, int cur)
{
    Debug((DEBUG_PROC, "do_shutdown\n"));

    if (io_SSL_shutdown(ctx->ssl_c, ctx->io, cur, (void *) do_shutdown)
	< 0 && errno == EAGAIN)
	return;

    io_clr_i(ctx->io, cur);
    io_clr_o(ctx->io, cur);

    SSL_free(ctx->ssl_c);
    ctx->ssl_c = NULL;

    ctx->use_tls_d = 0;
    ctx->protected_buffer_size = -1;

    io_set_cb_e(ctx->io, cur, (void *) cleanup_control);
    io_set_cb_h(ctx->io, cur, (void *) cleanup_control);

    print_banner(ctx);
}
Exemplo n.º 23
0
int main(int argc, char **argv)
{
  struct mace_options opt;
  Plist clauses;
  Mace_results results;

  /* Following says whether to ignore unregognized set/clear/assigns. */
  BOOL prover_compatability_mode = member_args(argc, argv, "-c");

  init_standard_ladr();
  init_mace_options(&opt);  /* We must do this before calling usage_message. */
  init_attrs();

  if (member_args(argc, argv, "help") ||
      member_args(argc, argv, "-help")) {
    usage_message(stderr, &opt);
    exit(1);
  }

  print_banner(argc, argv, PROGRAM_NAME, PROGRAM_VERSION, PROGRAM_DATE, FALSE);
  set_program_name(PROGRAM_NAME);   /* for conditional input */

  signal(SIGINT,  mace4_sig_handler);
  signal(SIGUSR1, mace4_sig_handler);
  signal(SIGSEGV, mace4_sig_handler);

  clauses = read_mace4_input(argc, argv, prover_compatability_mode, &opt);

  print_separator(stdout, "CLAUSES FOR SEARCH", TRUE);
  fwrite_clause_list(stdout, clauses, "mace4_clauses", CL_FORM_BARE);
  print_separator(stdout, "end of clauses for search", TRUE);

  results = mace4(clauses, &opt);

  mace4_exit(results->return_code);  /* print messages and exit */

  exit(0);  /* won't happen */

}  /* main */
Exemplo n.º 24
0
//modify monster and map
int main(int argc, char *argv[])
{

	struct sockaddr_in server_addr, client_addr;
	char temp[20];
	int server_fd, client_fd;
	int len, msg_size;

	if(argc != 2){
		printf("useage : %s [port]\n", argv[0]);       
		exit(0); 
	}

	if((server_fd = socket(AF_INET, SOCK_STREAM,0))==-1){
		printf("Server : Can't open Stream socket\n");
		exit(0);
	}

	memset(&server_addr, 0x00, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	server_addr.sin_port = htons(atoi(argv[1]));

	if(bind(server_fd, (struct sockaddr *)&server_addr , sizeof(server_addr))<0){
		printf("Server : Can't bind local address.\n");
		exit(0);
	}

	if(listen(server_fd, 10) < 0){
		printf("Server : Can't listenling connect.\n");
		exit(0);
	}

	while(1)
	{
		char temp_buf[128];
		memset(temp_buf, 0, sizeof(temp_buf));
		client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &len);
		
		if(client_fd < 0){
			printf("Server : accept failed.\n");
			exit(0);
		}
		
		inet_ntop(AF_INET, &client_addr.sin_addr, temp, sizeof(temp));
		printf("Server : %s client connected.\n", temp);
		
		print_banner(client_fd);
		print_help(client_fd);
		print_map(client_fd);
		
		while(1){
			int win_flag = 0;
			msg_size = read(client_fd, temp_buf, 128);

			printf("[*] user_x : %d\nuser_y : %d\n", user_x, user_y);
			
			char *string_of_quit = "/q";
			char *string_of_help = "/h";
			char *string_of_pwd = "/pwd";
			char *string_of_map = "/map";
			char *enter_of_dungeon = "던전에 입장하셨습니다!\n";
			char *e_msg = "(동)쪽으로 이동하셨습니다.\n";
			char *w_msg = "(서)쪽으로 이동하셨습니다.\n";
			char *s_msg = "(남)쪽으로 이동하셨습니다.\n";
			char *n_msg = "(북)쪽으로 이동하셨습니다.\n";
			char *wrong_msg = "옳은 명령어가 아닙니다.\n";
			char *string_of_usage = "이동할 방향에 맞춰 w,e,s,n을 입력하세요\n현재 위치는 /pwd를 사용하세요\n지도를 다시 볼때는 /map를 입력하세요\n처음 시작*** 좌표는 ( 0 , 0 )입니다\n";

			if(strncmp(temp_buf, string_of_quit ,strlen(string_of_quit)) == 0) {
				write(client_fd, "bye byte~\n", strlen("bye byte~\n"));
				memset(temp_buf, 0, sizeof(temp_buf));
				close(client_fd);
				exit(0);
			}
			else if(strncmp(temp_buf,string_of_help,strlen(string_of_help))==0){
				write(client_fd, string_of_usage, strlen(string_of_usage));
				memset(temp_buf, 0, sizeof(temp_buf));
				continue;
			}			
			else if(strncmp(temp_buf, string_of_pwd, strlen(string_of_pwd))==0){
				print_pwd(client_fd);
				memset(temp_buf, 0, sizeof(temp_buf));
				continue;
			}
			else if(strncmp(temp_buf, string_of_map, strlen(string_of_map))==0){
				print_map(client_fd);
				memset(temp_buf, 0, sizeof(temp_buf));
				continue;
			}

			if(strlen(temp_buf) == 2){
				switch(*temp_buf){
					case 'e':
						write(client_fd, e_msg, strlen(e_msg));
						user_x += 1;
						break;
					case 'w':
						write(client_fd, w_msg, strlen(w_msg));
						user_x -= 1;
						break;
					case 's':
						write(client_fd, s_msg, strlen(s_msg));
						user_y -= 1;
						break;
					case 'n':
						write(client_fd, n_msg, strlen(n_msg));
						user_y += 1;
						break;
					default:
						write(client_fd, wrong_msg, strlen(wrong_msg));
						break;
				}
			}else{
				write(client_fd, wrong_msg, strlen(wrong_msg));
				memset(temp_buf, 0, sizeof(temp_buf));
				continue;
			}

			if(strncmp(temp_buf,string_of_help,strlen(string_of_help))==0 || 
				strncmp(temp_buf, string_of_quit ,strlen(string_of_quit)) == 0 ||
				strncmp(temp_buf, string_of_pwd, strlen(string_of_pwd))==0 ||
				strncmp(temp_buf, string_of_map, strlen(string_of_map))==0){
				memset(temp_buf, 0, sizeof(temp_buf));
				continue;
			}

			else if(strlen(temp_buf) != 2 || strlen(temp_buf) > 2 ){
				if(msg_check_flag == 1){
					write(client_fd, wrong_msg, strlen(wrong_msg));
					memset(temp_buf, 0, sizeof(temp_buf));
				}else{
					continue;
				}
			}
			
			if( user_x == -2 && user_y == 1 && check_flag == 0){
				check_flag = 1;
				write(client_fd, enter_of_dungeon, strlen(enter_of_dungeon));
				win_flag = fight_monster(client_fd);

				if (win_flag == 1){
					write(client_fd, "처음 마을으로 돌아갑니다.\n", strlen("처음 마을으로 돌아갑니다.\n"));
					check_flag = 0;
					user_x = 0;
					user_y = 0;
					continue;
				}

			}
			else{
				continue;
			}
			memset(temp_buf, 0, sizeof(temp_buf));
		}
	}

	printf("Server: %s client closed\n", temp);
	close(client_fd);
	close(server_fd);

	return 0;

}
Exemplo n.º 25
0
int
main(int argc, char **argv)
{
	int		c, i;
	int		interval = 1;	/* Interval between displays */
	int		count = 0;	/* Number of times to sample */
	int		write_evts = FALSE;
	int		pos = 0;

#if !defined(TEXT_DOMAIN)
#define	TEXT_DOMAIN	"SYS_TEST"
#endif

	/* For I18N */
	(void) setlocale(LC_ALL, "");
	(void) textdomain(TEXT_DOMAIN);

	pgmname = basename(argv[0]);

	if ((kc = kstat_open()) == NULL) {
		(void) fprintf(stderr, gettext("%s: could not "
			"open /dev/kstat\n"), pgmname);
		exit(1);
	}

	while ((c = getopt(argc, argv, "e:w:r:ahln")) != EOF) {
		switch (c) {
		case 'a':
			delta = FALSE;
			break;
		case 'e':
			(void) print_evt();
			break;
		case 'h':
			usage();
			break;
		case 'l':
			(void) print_dev(argc, argv[argc-1]);
			break;
		case 'n':
			banner = FALSE;
			break;
		case 'r':
			(void) parse_cmd(READ_EVT);
			break;
		case 'w':
			(void) parse_cmd(WRITE_EVT);
			write_evts = TRUE;
			break;
		default:
			(void) fprintf(stderr, gettext("%s: invalid "
				"option\n"), pgmname);
			usage();
			break;
		}
	}

	if ((argc == 1) || (dev_list_head == NULL))
		usage();

	/*
	 * validate remaining operands are numeric.
	 */
	pos = optind;
	while (pos < argc) {
		if (strisnum(argv[pos]) == 0) {
			(void) fprintf(stderr,
				gettext("%s: syntax error\n"),
				pgmname);
			usage();
		}
		pos++;
	}

	if (optind < argc) {
		if ((interval = atoi(argv[optind])) == 0) {
			(void) fprintf(stderr, gettext("%s: invalid "
				"interval value\n"), pgmname);
			exit(1);
		}

		optind++;
		if (optind < argc)
			if ((count = atoi(argv[optind])) <= 0) {
				(void) fprintf(stderr, gettext("%s: "
					"invalid iteration value.\n"),
					    pgmname);
				exit(1);
			}
	}

	set_timer(interval);

	/*
	 * Set events for the first time.
	 */
	if (write_evts == TRUE)
		setup_evts();


	if (count > 0) {
		for (i = 0; i < count; i++) {
			if (banner)
				print_banner();

			check_dr_ops();
			read_evts();
			(void) fflush(stdout);
			(void) pause();
		}
	} else {
		for (;;) {
			if (banner)
				print_banner();

			check_dr_ops();
			read_evts();
			(void) fflush(stdout);
			(void) pause();
		}
	}

	read_evts();
	return (0);
}
Exemplo n.º 26
0
int main( int argc, char** argv )
{
   // parse command-line options
   boost::program_options::options_description option_config("Allowed options");
   option_config.add_options()("data-dir", boost::program_options::value<std::string>(), "configuration data directory")
                              ("help", "display this help message")
                              ("p2p-port", boost::program_options::value<uint16_t>()->default_value(5678), "set port to listen on")
                              ("maximum-number-of-connections", boost::program_options::value<uint16_t>(), "set the maximum number of peers this node will accept at any one time")
                              ("upnp", boost::program_options::value<bool>()->default_value(true), "Enable UPNP")
                              ("connect-to", boost::program_options::value<std::vector<std::string> >(), "set remote host to connect to")
                              ("server", "enable JSON-RPC server")
                              ("daemon", "run in daemon mode with no CLI console")
                              ("rpcuser", boost::program_options::value<std::string>(), "username for JSON-RPC")
                              ("rpcpassword", boost::program_options::value<std::string>(), "password for JSON-RPC")
                              ("rpcport", boost::program_options::value<uint16_t>()->default_value(5679), "port to listen for JSON-RPC connections")
                              ("httpport", boost::program_options::value<uint16_t>()->default_value(5680), "port to listen for HTTP JSON-RPC connections")
                              ("genesis-config", boost::program_options::value<std::string>()->default_value("genesis.dat"), 
                               "generate a genesis state with the given json file (only accepted when the blockchain is empty)")
                              ("clear-peer-database", "erase all information in the peer database")
                              ("resync-blockchain", "delete our copy of the blockchain at startup, and download a fresh copy of the entire blockchain from the network")
                              ("version", "print the version information for bts_xt_client");


   boost::program_options::positional_options_description positional_config;
   positional_config.add("data-dir", 1);

   boost::program_options::variables_map option_variables;
   try
   {
     boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
       options(option_config).positional(positional_config).run(), option_variables);
     boost::program_options::notify(option_variables);
   }
   catch (boost::program_options::error&)
   {
     std::cerr << "Error parsing command-line options\n\n";
     std::cerr << option_config << "\n";
     return 1;
   }

   if (option_variables.count("help"))
   {
     std::cout << option_config << "\n";
     return 0;
   }

   if (option_variables.count("version"))
   {
     std::cout << "bts_xt_client built on " << __DATE__ << " at " << __TIME__ << "\n";
     std::cout << "  bitshares_toolkit revision: " << bts::utilities::git_revision_sha << "\n";
     std::cout << "                              committed " << fc::get_approximate_relative_time_string(fc::time_point_sec(bts::utilities::git_revision_unix_timestamp)) << "\n";
     std::cout << "                 fc revision: " << fc::git_revision_sha << "\n";
     std::cout << "                              committed " << fc::get_approximate_relative_time_string(fc::time_point_sec(bts::utilities::git_revision_unix_timestamp)) << "\n";
     return 0;
   }

   try {
      print_banner();
      fc::path datadir = get_data_dir(option_variables);
      ::configure_logging(datadir);

      auto cfg   = load_config(datadir);
      auto chain = load_and_configure_chain_database(datadir, option_variables);
      auto wall  = std::make_shared<bts::wallet::wallet>(chain);
      wall->set_data_directory( datadir );

      bts::client::client_ptr client = std::make_shared<bts::client::client>( chain );
      _global_client = client.get();
      client->set_wallet( wall );
      client->run_delegate();

      bts::rpc::rpc_server_ptr rpc_server = std::make_shared<bts::rpc::rpc_server>();
      rpc_server->set_client(client);

      if( option_variables.count("server") )
      {
        // the user wants us to launch the RPC server.
        // First, override any config parameters they
        bts::rpc::rpc_server::config rpc_config(cfg.rpc);
        if (option_variables.count("rpcuser"))
          rpc_config.rpc_user = option_variables["rpcuser"].as<std::string>();
        if (option_variables.count("rpcpassword"))
          rpc_config.rpc_password = option_variables["rpcpassword"].as<std::string>();
        // for now, force binding to localhost only
        if (option_variables.count("rpcport"))
          rpc_config.rpc_endpoint = fc::ip::endpoint(fc::ip::address("127.0.0.1"), option_variables["rpcport"].as<uint16_t>());
        else
          rpc_config.rpc_endpoint = fc::ip::endpoint(fc::ip::address("127.0.0.1"), uint16_t(9988));
        if (option_variables.count("httpport"))
          rpc_config.httpd_endpoint = fc::ip::endpoint(fc::ip::address("127.0.0.1"), option_variables["httpport"].as<uint16_t>());
        std::cout<<"Starting json rpc server on "<< std::string( rpc_config.rpc_endpoint ) <<"\n";
        std::cout<<"Starting http json rpc server on "<< std::string( rpc_config.httpd_endpoint ) <<"\n";
        bool rpc_success = rpc_server->configure(rpc_config);
        if (!rpc_success)
        {
            std::cerr << "Error starting rpc server\n\n";
        }
      }
      else
      {
         std::cout << "Not starting rpc server, use --server to enable the rpc interface\n";
      }

      client->configure( datadir );

      if (option_variables.count("maximum-number-of-connections"))
      {
        fc::mutable_variant_object params;
        params["maximum_number_of_connections"] = option_variables["maximum-number-of-connections"].as<uint16_t>();
        client->network_set_advanced_node_parameters(params);
      }

      if (option_variables.count("p2p-port"))
      {
         auto p2pport = option_variables["p2p-port"].as<uint16_t>();
         std::cout << "Listening to P2P connections on port "<<p2pport<<"\n";
         client->listen_on_port(p2pport);

         if( option_variables["upnp"].as<bool>() )
         {
            std::cout << "Attempting to map UPNP port...\n";
            auto upnp_service = new bts::net::upnp_service();
            upnp_service->map_port( p2pport );
            fc::usleep( fc::seconds(3) );
         }
      }

      if (option_variables.count("clear-peer-database"))
      {
        std::cout << "Erasing old peer database\n";
        client->get_node()->clear_peer_database();
      }

      client->connect_to_p2p_network();
      if (option_variables.count("connect-to"))
      {
         std::vector<std::string> hosts = option_variables["connect-to"].as<std::vector<std::string>>();
         for( auto peer : hosts )
         {
            client->connect_to_peer( peer );
         }
      }
      else
      {
            client->connect_to_peer( "107.170.30.182:5678" );
      }

      if( !option_variables.count("daemon") )
      {
         auto cli = std::make_shared<bts::cli::cli>( client, rpc_server );
         cli->wait();
      }
      else if( option_variables.count( "server" ) ) // daemon & server
      {
         rpc_server->wait_on_quit();
      }
      else // daemon  !server
      {
         std::cerr << "You must start the rpc server in daemon mode\n";
      }
   }
   catch ( const fc::exception& e )
   {
      std::cerr << "------------ error --------------\n" 
                << e.to_detail_string() << "\n";
      wlog( "${e}", ("e", e.to_detail_string() ) );
   }
   return 0;
}
Exemplo n.º 27
0
int bootup_main(int argc, char **argv) {
    FILE *fp;
    DIR *dp;
    struct dirent *dt;
    int t=0, rc;
    char cmd[1024], buf[1024], name[1024];
    time_t curtime;
    struct tm *loctime;
    signal(SIGINT,SIG_IGN);
    putenv("PATH=/bin");
    putenv("TERM=linux");
    umask(0770);
    chdir("/");
    putchar('\n');
    print_banner();
    putchar('\n');
    xsystem("mount -t proc -o ro virtual /proc");
    xsystem("mount -t sysfs -o ro virtual /sys");

    // STAGE 1
    calculate_mem();
    fprintf_stdout("* Creating Mybox filesystem (%d kB) on shared memory...\n",RAMSIZE);
    xsystem("mount -t tmpfs -o \"rw,size=%dk\" virtual /ramd",RAMSIZE);
    chmod("/ramd",S_IREAD | S_IWRITE | S_IEXEC);
    chdir("/ramd");
    if((dp=opendir("/")) == NULL) {
        perror("opendir");
        exit(1);
    }
    while((dt=readdir(dp))!=NULL) {
        if(!strcmp(dt->d_name,".") || !strcmp(dt->d_name,"..") ||
                !strcmp(dt->d_name,"lost+found") ||
                !strcmp(dt->d_name,"ramd") ||
                !strcmp(dt->d_name,"proc") ||
                !strcmp(dt->d_name,"dev") ||
                !strcmp(dt->d_name,"sys")) continue;
        xsystem("cp -dpR /%s /ramd/",dt->d_name);
    }
    closedir(dp);
    xmkdir("dev/pts");
    xmkdir("initrd");
    umount("/proc");
    umount("/sys");

    // STAGE 2
    rc=pivot_root(".","initrd");
    if(rc==-1) {
        fprintf_stdout("#### ERROR: Change root file system failed!\n");
        exit(1);
    }
    chdir("/");
    xmkdir("proc");
    xmkdir("sys");
    xsystem("mount -t proc -o rw virtual /proc");
    xsystem("mount -t sysfs -o rw virtual /sys");
    save_to_file("/proc/sys/kernel/printk","0 0 0 0\n");
    if((dp=opendir("/tmp")) == NULL) {
        perror("opendir");
        exit(1);
    }
    fprintf_stdout("-> Extracting base tools: ");
    while((dt=readdir(dp))!=NULL) {
        if(!strcmp(dt->d_name,".") || !strcmp(dt->d_name,"..")) continue;
        if(strstr(dt->d_name,".mpk")) {
            fprintf_stdout("#");
            xsystem("tar -C / -axf /tmp/%s",dt->d_name);
        }
    }
    free(dt);
    closedir(dp);
    fprintf_stdout("\r* Extracting base tools. Done.%s\n",SPACE);
    save_to_file("/proc/sys/kernel/modprobe","/bin/modprobe\n");
    xsystem("depmod -a");

    // STAGE 3
    chdir("/");
    xsystem("mdev -s");
    xsystem("mount -t devpts /dev/devpts /dev/pts -o \"rw,gid=0,mode=620\"");
    rename("/dev/random","/dev/random-block");
    symlink("/dev/urandom","/dev/random");
    xsystem("chmod 700 *");
    if((fp=fopen("/etc/inittab","w"))!=NULL) {
        fprintf(fp,"::sysinit:/etc/init.boot/rc.init\n");
        fprintf(fp,"tty1::respawn:/bin/getty -h -n -L tty1 115200 linux\n");
        fprintf(fp,"ttyS0::respawn:/bin/getty -h -n -L ttyS0 115200 vt100\n");
        fprintf(fp,"tty7::respawn:/bin/chkprog\n");
        fprintf(fp,"tty8::respawn:/bin/trafficd\n");
        fprintf(fp,"::restart:/bin/init\n");
        fprintf(fp,"::ctrlaltdel:/bin/bootdown\n");
        fprintf(fp,"::ctrlaltdel:/bin/reset\n");
        fprintf(fp,"::ctrlaltdel:/bin/reboot\n");
        fprintf(fp,"::shutdown:/bin/bootdown\n");
        fclose(fp);
    }
    curtime=time(NULL);
    loctime=localtime(&curtime);
    strftime(cmd, sizeof(cmd), "[%d/%m/%Y %T] TYPE=INFO MSG=****** SYSTEM LOADING ******\n",loctime);
    append_to_file("/tmp/bootup",cmd);
    if(file_exists("/bin/getkey")) {
        if(system("getkey -c 3 -m \"-> Starting Init: %d\" R")==0) {
            fprintf_stdout("\r#### WARNING: LOGIN DISABLED\n");
            xtouch("/etc/noconsole");
        } else {
            fprintf_stdout("\r* Starting Init. Done.\n");
        }
    }
    memset(buf,0x0,sizeof(buf));
    snprintf(buf,sizeof(buf),"%s\n","/bin/mdev");
    save_to_file("/proc/sys/kernel/hotplug",buf);
    do_chroot();
    signal(SIGINT,SIG_DFL);
    fprintf_stdout("#### ERROR: Failed to boot file system!\n");
    fprintf_stdout("#### ERROR: Press Ctrl+Alt+Del or switch off/on for reboot.\n");
    while(1);
    exit(0);
}
Exemplo n.º 28
0
int main( int argc, char** argv )
{
   // parse command-line options
   boost::program_options::options_description option_config("Allowed options");
   option_config.add_options()("data-dir", boost::program_options::value<std::string>(), "configuration data directory")
                              ("help", "display this help message")
                              ("p2p", "enable p2p mode")
                              ("port", boost::program_options::value<uint16_t>(), "set port to listen on")
                              ("connect-to", boost::program_options::value<std::string>(), "set remote host to connect to")
                              ("server", "enable JSON-RPC server")
                              ("rpcuser", boost::program_options::value<std::string>(), "username for JSON-RPC")
                              ("rpcpassword", boost::program_options::value<std::string>(), "password for JSON-RPC")
                              ("rpcport", boost::program_options::value<uint16_t>(), "port to listen for JSON-RPC connections")
                              ("httpport", boost::program_options::value<uint16_t>(), "port to listen for HTTP JSON-RPC connections")
                              ("trustee-private-key", boost::program_options::value<std::string>(), "act as a trustee using the given private key")
                              ("trustee-address", boost::program_options::value<std::string>(), "trust the given BTS address to generate blocks")
                              ("genesis-json", boost::program_options::value<std::string>(), "generate a genesis block with the given json file (only for testing, only accepted when the blockchain is empty)");

   boost::program_options::positional_options_description positional_config;
   positional_config.add("data-dir", 1);

   boost::program_options::variables_map option_variables;
   try
   {
     boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
       options(option_config).positional(positional_config).run(), option_variables);
     boost::program_options::notify(option_variables);
   }
   catch (boost::program_options::error&)
   {
     std::cerr << "Error parsing command-line options\n\n";
     std::cerr << option_config << "\n";
     return 1;
   }

   if (option_variables.count("help"))
   {
     std::cout << option_config << "\n";
     return 0;
   }
   
   bool p2p_mode = option_variables.count("p2p") != 0;

   try {
      print_banner();
      fc::path datadir = get_data_dir(option_variables);
      ::configure_logging(datadir);

      auto cfg   = load_config(datadir);
      auto chain = load_and_configure_chain_database(datadir, option_variables);
      auto wall  = std::make_shared<bts::wallet::wallet>();
      wall->set_data_directory( datadir );

      auto c = std::make_shared<bts::client::client>(p2p_mode);
      c->set_chain( chain );
      c->set_wallet( wall );

      if (option_variables.count("trustee-private-key"))
      {
         auto key = fc::variant(option_variables["trustee-private-key"].as<std::string>()).as<fc::ecc::private_key>();
         c->run_trustee(key);
      }
      else if( fc::exists( "trustee.key" ) )
      {
         auto key = fc::json::from_file( "trustee.key" ).as<fc::ecc::private_key>();
         c->run_trustee(key);
      }

      bts::rpc::rpc_server_ptr rpc_server = std::make_shared<bts::rpc::rpc_server>();
      rpc_server->set_client(c);


      if( option_variables.count("server") )
      {
        // the user wants us to launch the RPC server.
        // First, override any config parameters they 
        bts::rpc::rpc_server::config rpc_config(cfg.rpc);
        if (option_variables.count("rpcuser"))
          rpc_config.rpc_user = option_variables["rpcuser"].as<std::string>();
        if (option_variables.count("rpcpassword"))
          rpc_config.rpc_password = option_variables["rpcpassword"].as<std::string>();
        // for now, force binding to localhost only
        if (option_variables.count("rpcport"))
          rpc_config.rpc_endpoint = fc::ip::endpoint(fc::ip::address("127.0.0.1"), option_variables["rpcport"].as<uint16_t>());
        if (option_variables.count("httpport"))
          rpc_config.httpd_endpoint = fc::ip::endpoint(fc::ip::address("127.0.0.1"), option_variables["httpport"].as<uint16_t>());
        std::cerr<<"starting json rpc server on "<< std::string( rpc_config.rpc_endpoint ) <<"\n";
        std::cerr<<"starting http json rpc server on "<< std::string( rpc_config.httpd_endpoint ) <<"\n";
        rpc_server->configure(rpc_config);
      }
      
      if (p2p_mode)
      {
        c->configure( datadir );
        if (option_variables.count("port"))
          c->listen_on_port(option_variables["port"].as<uint16_t>());
        c->connect_to_p2p_network();
        if (option_variables.count("connect-to"))
          c->connect_to_peer(option_variables["connect-to"].as<std::string>());
      }
      else
      {
        if (option_variables.count("connect-to"))
          c->add_node(option_variables["connect-to"].as<std::string>());
        else
           c->add_node( "127.0.0.1:4569" );
      }

      auto cli = std::make_shared<bts::cli::cli>( c, rpc_server );
      cli->wait();

   } 
   catch ( const fc::exception& e ) 
   {
      wlog( "${e}", ("e", e.to_detail_string() ) );
   }
   return 0;
}
Exemplo n.º 29
0
int repl()
{
  global_env = null_import_environment();
  environment_t *env = global_env;

  print_banner(env);

  #if HAVE_LIBREADLINE
  init_readline();
  #endif

  for(;;) {
    static char *input = reinterpret_cast<char*>(1);

    /*
     * input == 1 is the ugliest hack ever to
     * disoplay the imported_defaults message below,
     * and also because of ANOTHER hack, the home-brewed
     * exception system using longjumps.  I think I need to
     * rewrite... :)
     */
    if ( input != reinterpret_cast<char*>(1) ) {
      if ( (input = readline("#; mickey> ")) == NULL )
        break; // end of input stream

      if ( *trimr(input) == '\0' )
        continue; // empty command

      #ifdef HAVE_LIBREADLINE
      add_history(input);
      #endif

      if ( exception_raised() ) {
        backtrace();
        backtrace_clear();
        continue;
      }
    } else
      input = strdup("");

    TRY {
      /*
       * Must wrap import_defaults in try-catch
       */
      {
        static bool imported_defaults = false;
        if ( !imported_defaults ) {
          printf("\n");
          printf("   To quit, hit CTRL+D or type (exit).  Use (help) for an introduction.\n");
          printf("   Distributed under the LGPL 2.1; see LICENSE\n");
          printf("\n");
          printf("   WARNING: There's no garbage collector in Mickey yet!\n");
          printf("|#\n\n");

          import_defaults(env);
          imported_defaults = true;

          // import (help) and (top-level) etc.
          if ( !global_opts.empty_repl_env )
            import(env, exports_repl, "(scheme repl)");
        }
      }

      program_t *p = parse(input, env);

      if ( p->parens < 0 )
        raise(runtime_exception(format(
          "parser: unbalanced parenthesis -> %ld", p->parens)));

      // Read until we have balanced parenthesis
      std::string s(input);
      while ( p->parens != 0 ) {
        if ( (input = readline("")) == NULL ) break;
        if ( *trimr(input) == '\0' ) continue;

        s += " ";
        s += input;
        delete p;

        #ifdef HAVE_LIBREADLINE
        free(input);
        input = NULL;
        #endif

        p = parse(s.c_str(), env);
      }

      #ifdef HAVE_LIBREADLINE
      if ( input ) free(input);
      #endif

      for ( cons_t *i = p->root; !nullp(i); i = cdr(i) ) {
        cons_t *result = eval(car(i), p->globals);

        if ( circularp(result) ) {
          fflush(stdout);
          fprintf(stderr, "Warning: List is circular\n");
          cons_t *l = list(), *end = l;

          for ( int n=0; n < MAX_CIRCULAR_DISPLAY_ITEMS; ++n ) {
            end->car = car(result);
            end->cdr = cons(nil());
            end = cdr(end);
            result = cdr(result);
          }

          end->car = symbol("...etc");
          end->cdr = cons(nil());
          printf("%s\n", sprint(l).c_str());
        } else {
          std::string s = sprint(result);

          if ( !s.empty() )
            printf("%s\n", s.c_str());
        }
      }

      delete p;
    }
    CATCH (const exception_t& e) {
      if ( *e.what() != '\0' )
        fprintf(stderr, "%s\n", e.what());
      backtrace();
      backtrace_clear();
    }
  }

  printf("\n");
  return 0;
}
Exemplo n.º 30
0
/*
 * Entry point.
 * Parse PROM boot string, load the kernel and jump into it
 */
int
main(unsigned int memsize)
{
	char **namep, *dev, *kernel, *bi_addr;
	char bootpath[PATH_MAX];
	int win;
	u_long marks[MARK_MAX];
	void (*entry)(unsigned int, u_int, char *);

	struct btinfo_flags bi_flags;
	struct btinfo_symtab bi_syms;
	struct btinfo_bootpath bi_bpath;
	struct btinfo_howto bi_howto;
	int addr, speed, howto;

	try_bootp = 1;

	/* Initialize boot info early */
	dev = NULL;
	kernel = NULL;
	howto = 0x0;
	bi_flags.bi_flags = 0x0;
	bi_addr = bi_init();

	lcd_init();
	cobalt_id = read_board_id();
	prominit(memsize);
	if (cninit(&addr, &speed) != NULL)
		bi_flags.bi_flags |= BI_SERIAL_CONSOLE;

	print_banner(memsize);

	memset(marks, 0, sizeof marks);
	get_bsdbootname(&dev, &kernel, &howto);

	if (kernel != NULL) {
		DPRINTF(("kernel: %s\n", kernel));
		kernelnames[0] = kernel;
		kernelnames[1] = NULL;
	} else {
		DPRINTF(("kernel: NULL\n"));
	}

	win = 0;
	DPRINTF(("Kernel names: %p\n", kernelnames));
	for (namep = kernelnames, win = 0; (*namep != NULL) && !win; namep++) {
		kernel = *namep;

		bootpath[0] = '\0';

		strcpy(bootpath, dev ? dev : DEFBOOTDEV);
		strcat(bootpath, ":");
		strcat(bootpath, kernel);

		lcd_loadfile(bootpath);
		printf("Loading: %s", bootpath);
		if (howto)
			printf(" (howto 0x%x)", howto);
		printf("\n");
		patch_bootstring(bootpath);
		win = (loadfile(bootpath, marks, LOAD_ALL) != -1);
	}

	if (win) {
		strncpy(bi_bpath.bootpath, kernel, BTINFO_BOOTPATH_LEN);
		bi_add(&bi_bpath, BTINFO_BOOTPATH, sizeof(bi_bpath));

		entry = (void *)marks[MARK_ENTRY];
		bi_syms.nsym = marks[MARK_NSYM];
		bi_syms.ssym = marks[MARK_SYM];
		bi_syms.esym = marks[MARK_END];
		bi_add(&bi_syms, BTINFO_SYMTAB, sizeof(bi_syms));

		bi_add(&bi_flags, BTINFO_FLAGS, sizeof(bi_flags));

		bi_howto.bi_howto = howto;
		bi_add(&bi_howto, BTINFO_HOWTO, sizeof(bi_howto));

		entry = (void *)marks[MARK_ENTRY];

		DPRINTF(("Bootinfo @ 0x%lx\n", (u_long)bi_addr));
		printf("Starting at 0x%lx\n\n", (u_long)entry);
		(*entry)(memsize, BOOTINFO_MAGIC, bi_addr);
	}

	delay(20000);
	lcd_failed();
	(void)printf("Boot failed! Rebooting...\n");
	return 0;
}