Esempio n. 1
2
int
main(int argc, char **argv)
{
	char *cp, **ap;
	int ch, disc;
	FILE *wfd = NULL;
	char *dialerstring = 0, buf[BUFSIZ];
	int unitnum, keepal = 0, outfill = 0;
	char unitname[32];
	char *password;
	char *upscript = NULL, *downscript = NULL;
	int first = 1, tries = 0;
	time_t fintimeout;
	long lpid;
	pid_t pid;
	struct termios t;
	int result;

	while ((ch = getopt(argc, argv, "dhlb:s:t:w:A:U:D:W:K:O:S:L")) != -1)
		switch (ch) {
		case 'd':
			debug = 1;
			break;
		case 'b':
			speed = atoi(optarg);
			break;
		case 's':
			if (diali >= MAXDIALS)
				errx(1, "max dial strings number (%d) exceeded", MAXDIALS);
			dials[diali++] = strdup(optarg);
			break;
		case 't':
			script_timeout = atoi(optarg);
			break;
		case 'w':
			wait_time = atoi(optarg);
			break;
		case 'W':
			MAXTRIES = atoi(optarg);
			break;
		case 'A':
			annex = strdup(optarg);
			break;
		case 'U':
			upscript = strdup(optarg);
			break;
		case 'D':
			downscript = strdup(optarg);
			break;
		case 'L':
			uucp_lock = 1;
			break;
		case 'l':
			modem_control = 0;
			break;
		case 'h':
			flowcontrol = FC_HW;
			break;
		case 'K':
			keepal = atoi(optarg);
			break;
		case 'O':
			outfill = atoi(optarg);
			break;
		case 'S':
			sl_unit = atoi(optarg);
			break;
		case '?':
		default:
			usage();
		}
	argc -= optind;
	argv += optind;

	if (argc != 3)
		usage();

	/*
	 * Copy these so they exist after we clobber them.
	 */
	devicename = strdup(argv[0]);
	username = strdup(argv[1]);
	password = strdup(argv[2]);

	/*
	 * Security hack.  Do not want private information such as the
	 * password and possible phone number to be left around.
	 * So we clobber the arguments.
	 */
	for (ap = argv - optind + 1; ap < argv + 3; ap++)
		for (cp = *ap; *cp != 0; cp++)
			*cp = '\0';

	openlog("startslip", LOG_PID|LOG_PERROR, LOG_DAEMON);

	if (debug)
		setbuf(stdout, NULL);

	signal(SIGTERM, sigterm);
	if ((dvname = strrchr(devicename, '/')) == NULL)
		dvname = devicename;
	else
		dvname++;

	result = snprintf(my_pidfile, sizeof(my_pidfile),
			  PIDFILE, _PATH_VARRUN, dvname);
	if (result < 0 || (unsigned int)result >= sizeof(my_pidfile))
		usage();

	if ((pfd = fopen(my_pidfile, "r")) != NULL) {
		if (fscanf(pfd, "%ld\n", &lpid) == 1) {
			pid = lpid;
			if (pid == lpid && pid > 0)
				kill(pid, SIGTERM);
		}
		fclose(pfd);
		pfd = NULL;     /* not remove pidfile yet */
		sleep(5);       /* allow down script to be completed */
	} else
restart:
	signal(SIGHUP, SIG_IGN);
	signal(SIGURG, SIG_IGN);
	hup = 0;
	if (wfd) {
		printd("fclose, ");
		fclose(wfd);
		conn_time = time(NULL) - start_time;
		if (uucp_lock)
			uu_unlock(dvname);
		locked = 0;
		wfd = NULL;
		fd = -1;
		sleep(5);
	} else if (fd >= 0) {
		printd("close, ");
		close(fd);
		conn_time = time(NULL) - start_time;
		if (uucp_lock)
			uu_unlock(dvname);
		locked = 0;
		fd = -1;
		sleep(5);
	}
	if (logged_in) {
		syslog(LOG_INFO, "%s: connection time elapsed: %ld secs",
		    username, (long)conn_time);
		sprintf(buf, "LINE=%d %s %s down",
		diali ? (dialc - 1) % diali : 0,
		downscript ? downscript : "/sbin/ifconfig" , unitname);
		system(buf);
		logged_in = 0;
	}
	if (terminate)
		down(0);
	tries++;
	if (MAXTRIES > 0 && tries > MAXTRIES) {
		syslog(LOG_ERR, "%s: exiting login after %d tries", username, tries);
		/* ???
		if (first)
		*/
			down(3);
	}
	if (tries > 1) {
		syslog(LOG_INFO, "%s: sleeping %d seconds (%d tries)",
			username, wait_time * (tries - 1), tries);
		sleep(wait_time * (tries - 1));
		if (terminate)
			goto restart;
	}

	if (daemon(1, debug) < 0) {
		syslog(LOG_ERR, "%s: daemon: %m", username);
		down(2);
	}

	pid = getpid();
	printd("restart: pid %ld: ", (long)pid);
	if ((pfd = fopen(my_pidfile, "w")) != NULL) {
		fprintf(pfd, "%ld\n", (long)pid);
		fclose(pfd);
	}
	printd("open");
	if (uucp_lock) {
		int res;
		if ((res = uu_lock(dvname)) != UU_LOCK_OK) {
			if (res != UU_LOCK_INUSE)
				syslog(LOG_ERR, "uu_lock: %s", uu_lockerr(res));
			syslog(LOG_ERR, "%s: can't lock %s", username, devicename);
			goto restart;
		}
		locked = 1;
	}
	if ((fd = open(devicename, O_RDWR | O_NONBLOCK)) < 0) {
		syslog(LOG_ERR, "%s: open %s: %m", username, devicename);
		if (first)
			down(1);
		else {
			if (uucp_lock)
				uu_unlock(dvname);
			locked = 0;
			goto restart;
		}
	}
	printd(" %d", fd);
	signal(SIGHUP, sighup);
	if (ioctl(fd, TIOCSCTTY, 0) < 0) {
		syslog(LOG_ERR, "%s: ioctl (TIOCSCTTY): %m", username);
		down(2);
	}
	if (tcsetpgrp(fd, getpid()) < 0) {
		syslog(LOG_ERR, "%s: tcsetpgrp failed: %m", username);
		down(2);
	}
	printd(", ioctl\n");
	if (tcgetattr(fd, &t) < 0) {
		syslog(LOG_ERR, "%s: tcgetattr(%s): %m", username, devicename);
		down(2);
	}
	cfmakeraw(&t);
	switch (flowcontrol) {
	case FC_HW:
		t.c_cflag |= (CRTS_IFLOW|CCTS_OFLOW);
		break;
	case FC_NONE:
		t.c_cflag &= ~(CRTS_IFLOW|CCTS_OFLOW);
		break;
	}
	if (modem_control)
		t.c_cflag |= HUPCL;
	else
		t.c_cflag &= ~(HUPCL);
	t.c_cflag |= CLOCAL;    /* until modem commands passes */
	cfsetispeed(&t, speed);
	cfsetospeed(&t, speed);
	if (tcsetattr(fd, TCSAFLUSH, &t) < 0) {
		syslog(LOG_ERR, "%s: tcsetattr(%s): %m", username, devicename);
		down(2);
	}
	sleep(2);		/* wait for flakey line to settle */
	if (hup || terminate)
		goto restart;

	wfd = fdopen(fd, "w+");
	if (wfd == NULL) {
		syslog(LOG_ERR, "%s: can't fdopen %s: %m", username, devicename);
		down(2);
	}
	setbuf(wfd, NULL);

	if (diali > 0)
		dialerstring = dials[dialc++ % diali];
	if (dialerstring) {
		syslog(LOG_INFO, "%s: dialer string: %s\\r", username, dialerstring);
		fprintf(wfd, "%s\r", dialerstring);
	}
	printd("\n");

	fintimeout = time(NULL) + script_timeout;
	if (modem_control) {
		printd("waiting for carrier\n");
		while (time(NULL) < fintimeout && !carrier()) {
			sleep(1);
			if (hup || terminate)
				goto restart;
		}
		if (!carrier())
			goto restart;
		t.c_cflag &= ~(CLOCAL);
		if (tcsetattr(fd, TCSANOW, &t) < 0) {
			syslog(LOG_ERR, "%s: tcsetattr(%s): %m", username, devicename);
			down(2);
		}
		/* Only now we able to receive HUP on carrier drop! */
	}

	/*
	 * Log in
	 */
	printd("look for login: "******"slip\r");
				printd("Sent \"slip\"\n");
				continue;
			}
			if (bcmp(&buf[1], "sername:", 8) == 0) {
				fprintf(wfd, "%s\r", username);
				printd("Sent login: %s\n", username);
				continue;
			}
			if (bcmp(&buf[1], "assword:", 8) == 0) {
				fprintf(wfd, "%s\r", password);
				printd("Sent password: %s\n", password);
				break;
			}
		} else {
			if (strstr(&buf[1], "ogin:") != NULL) {
				fprintf(wfd, "%s\r", username);
				printd("Sent login: %s\n", username);
				continue;
			}
			if (strstr(&buf[1], "assword:") != NULL) {
				fprintf(wfd, "%s\r", password);
				printd("Sent password: %s\n", password);
				break;
			}
		}
	}

	sleep(5);       /* Wait until login completed */
	if (hup || terminate)
		goto restart;
	start_time = time(NULL);
	/*
	 * Attach
	 */
	printd("setd");
	disc = SLIPDISC;
	if (ioctl(fd, TIOCSETD, &disc) < 0) {
		syslog(LOG_ERR, "%s: ioctl (%s, TIOCSETD): %m",
		    username, devicename);
		down(2);
	}
	if (sl_unit >= 0 && ioctl(fd, SLIOCSUNIT, &sl_unit) < 0) {
		syslog(LOG_ERR, "%s: ioctl(SLIOCSUNIT): %m", username);
		down(2);
	}
	if (ioctl(fd, SLIOCGUNIT, &unitnum) < 0) {
		syslog(LOG_ERR, "%s: ioctl(SLIOCGUNIT): %m", username);
		down(2);
	}
	sprintf(unitname, "sl%d", unitnum);

	if (keepal > 0) {
		signal(SIGURG, sigurg);
		if (ioctl(fd, SLIOCSKEEPAL, &keepal) < 0) {
			syslog(LOG_ERR, "%s: ioctl(SLIOCSKEEPAL): %m", username);
			down(2);
		}
	}
	if (outfill > 0 && ioctl(fd, SLIOCSOUTFILL, &outfill) < 0) {
		syslog(LOG_ERR, "%s: ioctl(SLIOCSOUTFILL): %m", username);
		down(2);
	}

	sprintf(buf, "LINE=%d %s %s up",
		diali ? (dialc - 1) % diali : 0,
		upscript ? upscript : "/sbin/ifconfig" , unitname);
	system(buf);

	printd(", ready\n");
	if (!first)
		syslog(LOG_INFO, "%s: reconnected on %s (%d tries)", username, unitname, tries);
	else
		syslog(LOG_INFO, "%s: connected on %s", username, unitname);
	first = 0;
	tries = 0;
	logged_in = 1;
	while (hup == 0 && terminate == 0) {
		sigpause(0L);
		printd("sigpause return\n");
	}
	goto restart;
	return(0); /* not reached */
}
Esempio n. 2
0
static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
  char *endptr;
  static unsigned char pattern[16];

  switch (key)
    {
    case 'c':
      count = ping_cvt_number (arg, 0, 0);
      break;

    case 'd':
      socket_type |= SO_DEBUG;
      break;

    case 'f':
      if (!is_root)
        error (EXIT_FAILURE, 0, "flooding needs root privilege");

      options |= OPT_FLOOD;
      setbuf (stdout, (char *) NULL);
      break;

    case 'i':
      options |= OPT_INTERVAL;
      interval = ping_cvt_number (arg, 0, 0);
      break;

    case 'l':
      if (!is_root)
        error (EXIT_FAILURE, 0, "preloading needs root privilege");

      preload = strtoul (arg, &endptr, 0);
      if (*endptr || preload > INT_MAX)
        error (EXIT_FAILURE, 0, "preload size too large");

      break;

    case 'n':
      options |= OPT_NUMERIC;
      break;

    case 'p':
      decode_pattern (arg, &pattern_len, pattern);
      patptr = pattern;
      break;

    case 'q':
      options |= OPT_QUIET;
      break;

    case 'r':
      socket_type |= SO_DONTROUTE;
      break;

    case 'w':
      timeout = ping_cvt_number (arg, INT_MAX, 0);
      break;

    case 's':
      data_length = ping_cvt_number (arg, PING_MAX_DATALEN, 1);
      break;

    case ARGP_KEY_NO_ARGS:
      argp_error (state, "missing host operand");

    default:
      return ARGP_ERR_UNKNOWN;
    }

  return 0;
}
Esempio n. 3
0
int main(int argc, char *argv[]) {
    struct  sockaddr_in peer;
    int     sd,
            len;
    u_short port = PORT;
    u_char  buff[BUFFSZ],
            info[] =
                "\x00\x00"
                "\x02\x00\x00\x00\x00"
                "\x0A"      // size
                "\x05\x00"
                "\x0A"      // size, same of before
                "WING"
                "\x00\x00"  // build version (leave it empty)
                "\x00";


    setbuf(stdout, NULL);

    fputs("\n"
        "SOLDNER Secret Wars <= 30830 socket termination "VER"\n"
        "by Luigi Auriemma\n"
        "e-mail: [email protected]\n"
        "web:    http://aluigi.altervista.org\n"
        "\n", stdout);

    if(argc < 2) {
        printf("\n"
            "Usage: %s <host> [port(%d)]\n"
            "\n", argv[0], port);
        exit(1);
    }

#ifdef WIN32
    WSADATA    wsadata;
    WSAStartup(MAKEWORD(1,0), &wsadata);
#endif

    if(argc > 2) port = atoi(argv[2]);

    peer.sin_addr.s_addr = resolv(argv[1]);
    peer.sin_port        = htons(port);
    peer.sin_family      = AF_INET;

    printf("- target   %s : %hu\n",
        inet_ntoa(peer.sin_addr), port);

    fputs("- check server:\n", stdout);
    sd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sd < 0) std_err();

    *(u_short *)info = crc16(info + 2, sizeof(info) - 3);
    SEND(info, sizeof(info) - 1);
    RECV;

    if(memcmp(buff + 11, "WING", 4)) {
        fputs("\nAlert: the server doesn't seem a valid Soldner server\n", stdout);
    }
    printf("  Build version   %d\n", ntohs(*(u_short *)(buff + 18)));

    printf("\n- send BOOM packet (%d bytes)\n", BOOMSZ);
    memset(buff, 0x00, BOOMSZ);
    SEND(buff, BOOMSZ);

    fputs("- check server again:\n", stdout);
    SEND(info, sizeof(info) - 1);
    if(timeout(sd) < 0) {
        fputs("\nServer IS vulnerable!!!\n\n", stdout);
    } else {
        fputs("\nServer doesn't seem vulnerable\n\n", stdout);
    }

    close(sd);

    return(0);
}
Esempio n. 4
0
int main(int argc, char **argv) {
	// Recovery needs to install world-readable files, so clear umask
	// set by init
	umask(0);

	Log_Offset = 0;

	// Set up temporary log file (/tmp/recovery.log)
	freopen(TMP_LOG_FILE, "a", stdout);
	setbuf(stdout, NULL);
	freopen(TMP_LOG_FILE, "a", stderr);
	setbuf(stderr, NULL);

	// Handle ADB sideload
	if (argc == 3 && strcmp(argv[1], "--adbd") == 0) {
		adb_main(argv[2]);
		return 0;
	}

	char crash_prop_val[PROPERTY_VALUE_MAX];
	int crash_counter;
	property_get("twrp.crash_counter", crash_prop_val, "-1");
	crash_counter = atoi(crash_prop_val) + 1;
	snprintf(crash_prop_val, sizeof(crash_prop_val), "%d", crash_counter);
	property_set("twrp.crash_counter", crash_prop_val);

	time_t StartupTime = time(NULL);
	printf("Starting TWRP %s on %s", TW_VERSION_STR, ctime(&StartupTime));

	// Load default values to set DataManager constants and handle ifdefs
	DataManager::SetDefaultValues();
	printf("Starting the UI...");
	gui_init();
	printf("=> Linking mtab\n");
	symlink("/proc/mounts", "/etc/mtab");
	if (TWFunc::Path_Exists("/etc/twrp.fstab")) {
		if (TWFunc::Path_Exists("/etc/recovery.fstab")) {
			printf("Renaming regular /etc/recovery.fstab -> /etc/recovery.fstab.bak\n");
			rename("/etc/recovery.fstab", "/etc/recovery.fstab.bak");
		}
		printf("Moving /etc/twrp.fstab -> /etc/recovery.fstab\n");
		rename("/etc/twrp.fstab", "/etc/recovery.fstab");
	}
	printf("=> Processing recovery.fstab\n");
	if (!PartitionManager.Process_Fstab("/etc/recovery.fstab", 1)) {
		LOGERR("Failing out of recovery due to problem with recovery.fstab.\n");
		return -1;
	}
	PartitionManager.Output_Partition_Logging();
	// Load up all the resources
	gui_loadResources();

#ifdef HAVE_SELINUX
	if (TWFunc::Path_Exists("/prebuilt_file_contexts")) {
		if (TWFunc::Path_Exists("/file_contexts")) {
			printf("Renaming regular /file_contexts -> /file_contexts.bak\n");
			rename("/file_contexts", "/file_contexts.bak");
		}
		printf("Moving /prebuilt_file_contexts -> /file_contexts\n");
		rename("/prebuilt_file_contexts", "/file_contexts");
	}
	struct selinux_opt selinux_options[] = {
		{ SELABEL_OPT_PATH, "/file_contexts" }
	};
	selinux_handle = selabel_open(SELABEL_CTX_FILE, selinux_options, 1);
	if (!selinux_handle)
		printf("No file contexts for SELinux\n");
	else
		printf("SELinux contexts loaded from /file_contexts\n");
	{ // Check to ensure SELinux can be supported by the kernel
		char *contexts = NULL;

		if (PartitionManager.Mount_By_Path("/cache", true) && TWFunc::Path_Exists("/cache/recovery")) {
			lgetfilecon("/cache/recovery", &contexts);
			if (!contexts) {
				lsetfilecon("/cache/recovery", "test");
				lgetfilecon("/cache/recovery", &contexts);
			}
		} else {
			LOGINFO("Could not check /cache/recovery SELinux contexts, using /sbin/teamwin instead which may be inaccurate.\n");
			lgetfilecon("/sbin/teamwin", &contexts);
		}
		if (!contexts) {
			gui_print_color("warning", "Kernel does not have support for reading SELinux contexts.\n");
		} else {
			free(contexts);
			gui_print("Full SELinux support is present.\n");
		}
	}
#else
	gui_print_color("warning", "No SELinux support (no libselinux).\n");
#endif

	PartitionManager.Mount_By_Path("/cache", true);

	string Zip_File, Reboot_Value;
	bool Cache_Wipe = false, Factory_Reset = false, Perform_Backup = false;

	{
		TWPartition* misc = PartitionManager.Find_Partition_By_Path("/misc");
		if (misc != NULL) {
			if (misc->Current_File_System == "emmc") {
				set_device_type('e');
				set_device_name(misc->Actual_Block_Device.c_str());
			} else if (misc->Current_File_System == "mtd") {
				set_device_type('m');
				set_device_name(misc->MTD_Name.c_str());
			} else {
				LOGERR("Unknown file system for /misc\n");
			}
		}
		get_args(&argc, &argv);

		int index, index2, len;
		char* argptr;
		char* ptr;
		printf("Startup Commands: ");
		for (index = 1; index < argc; index++) {
			argptr = argv[index];
			printf(" '%s'", argv[index]);
			len = strlen(argv[index]);
			if (*argptr == '-') {argptr++; len--;}
			if (*argptr == '-') {argptr++; len--;}
			if (*argptr == 'u') {
				ptr = argptr;
				index2 = 0;
				while (*ptr != '=' && *ptr != '\n')
					ptr++;
				// skip the = before grabbing Zip_File
				while (*ptr == '=')
					ptr++;
				if (*ptr) {
					Zip_File = ptr;
				} else
					LOGERR("argument error specifying zip file\n");
			} else if (*argptr == 'w') {
				if (len == 9)
					Factory_Reset = true;
				else if (len == 10)
					Cache_Wipe = true;
			} else if (*argptr == 'n') {
				Perform_Backup = true;
			} else if (*argptr == 's') {
				ptr = argptr;
				index2 = 0;
				while (*ptr != '=' && *ptr != '\n')
					ptr++;
				if (*ptr) {
					Reboot_Value = *ptr;
				}
			}
		}
		printf("\n");
	}

	if(crash_counter == 0) {
		property_list(Print_Prop, NULL);
		printf("\n");
	} else {
		printf("twrp.crash_counter=%d\n", crash_counter);
	}

	// Check for and run startup script if script exists
	TWFunc::check_and_run_script("/sbin/runatboot.sh", "boot");
	TWFunc::check_and_run_script("/sbin/postrecoveryboot.sh", "boot");

#ifdef TW_INCLUDE_INJECTTWRP
	// Back up TWRP Ramdisk if needed:
	TWPartition* Boot = PartitionManager.Find_Partition_By_Path("/boot");
	LOGINFO("Backing up TWRP ramdisk...\n");
	if (Boot == NULL || Boot->Current_File_System != "emmc")
		TWFunc::Exec_Cmd("injecttwrp --backup /tmp/backup_recovery_ramdisk.img");
	else {
		string injectcmd = "injecttwrp --backup /tmp/backup_recovery_ramdisk.img bd=" + Boot->Actual_Block_Device;
		TWFunc::Exec_Cmd(injectcmd);
	}
	LOGINFO("Backup of TWRP ramdisk done.\n");
#endif

	bool Keep_Going = true;
	if (Perform_Backup) {
		DataManager::SetValue(TW_BACKUP_NAME, "(Auto Generate)");
		if (!OpenRecoveryScript::Insert_ORS_Command("backup BSDCAE\n"))
			Keep_Going = false;
	}
	if (Keep_Going && !Zip_File.empty()) {
		string ORSCommand = "install " + Zip_File;

		if (!OpenRecoveryScript::Insert_ORS_Command(ORSCommand))
			Keep_Going = false;
	}
	if (Keep_Going) {
		if (Factory_Reset) {
			if (!OpenRecoveryScript::Insert_ORS_Command("wipe data\n"))
				Keep_Going = false;
		} else if (Cache_Wipe) {
			if (!OpenRecoveryScript::Insert_ORS_Command("wipe cache\n"))
				Keep_Going = false;
		}
	}

	TWFunc::Update_Log_File();
	// Offer to decrypt if the device is encrypted
	if (DataManager::GetIntValue(TW_IS_ENCRYPTED) != 0) {
		LOGINFO("Is encrypted, do decrypt page first\n");
		if (gui_startPage("decrypt") != 0) {
			LOGERR("Failed to start decrypt GUI page.\n");
		}
	}

	// Read the settings file
	DataManager::ReadSettingsFile();

	// Fixup the RTC clock on devices which require it
	if(crash_counter == 0)
		TWFunc::Fixup_Time_On_Boot();

	// Run any outstanding OpenRecoveryScript
	if (DataManager::GetIntValue(TW_IS_ENCRYPTED) == 0 && (TWFunc::Path_Exists(SCRIPT_FILE_TMP) || TWFunc::Path_Exists(SCRIPT_FILE_CACHE))) {
		OpenRecoveryScript::Run_OpenRecoveryScript();
	}

	// Launch the main GUI
	gui_start();

	// Check for su to see if the device is rooted or not
	if (PartitionManager.Mount_By_Path("/system", false)) {
		// Disable flashing of stock recovery
		if (TWFunc::Path_Exists("/system/recovery-from-boot.p")) {
			rename("/system/recovery-from-boot.p", "/system/recovery-from-boot.bak");
			gui_print("Renamed stock recovery file in /system to prevent\nthe stock ROM from replacing TWRP.\n");
		}
		if (TWFunc::Path_Exists("/supersu/su") && !TWFunc::Path_Exists("/system/bin/su") && !TWFunc::Path_Exists("/system/xbin/su") && !TWFunc::Path_Exists("/system/bin/.ext/.su")) {
			// Device doesn't have su installed
			DataManager::SetValue("tw_busy", 1);
			if (gui_startPage("installsu") != 0) {
				LOGERR("Failed to start SuperSU install page.\n");
			}
		} else if (TWFunc::Check_su_Perms() > 0) {
			// su perms are set incorrectly
			LOGINFO("Root permissions appear to be lost... fixing. (This will always happen on 4.3+ ROMs with SELinux.\n");
			TWFunc::Fix_su_Perms();
		}
		sync();
		PartitionManager.UnMount_By_Path("/system", false);
	}

	// Reboot
	TWFunc::Update_Intent_File(Reboot_Value);
	TWFunc::Update_Log_File();
	gui_print("Rebooting...\n");
	string Reboot_Arg;
	DataManager::GetValue("tw_reboot_arg", Reboot_Arg);
	if (Reboot_Arg == "recovery")
		TWFunc::tw_reboot(rb_recovery);
	else if (Reboot_Arg == "poweroff")
		TWFunc::tw_reboot(rb_poweroff);
	else if (Reboot_Arg == "bootloader")
		TWFunc::tw_reboot(rb_bootloader);
	else if (Reboot_Arg == "download")
		TWFunc::tw_reboot(rb_download);
	else
		TWFunc::tw_reboot(rb_system);

#ifdef ANDROID_RB_RESTART
	android_reboot(ANDROID_RB_RESTART, 0, 0);
#else
	reboot(RB_AUTOBOOT);
#endif
	return 0;
}
Esempio n. 5
0
int main( int argc, char *argv[] )
{
    char *fout;
    int   i, j,k,iethpo, pothie;
    FILE *outfp = 0;



    printf("\nPORTA - a POlyhedron Representation Transformation Algorithm\n");
    printf(  "Version %s\n\n", VERSION );

    printf( "Written by Thomas Christof (Uni Heidelberg)\n" );
    printf( "Revised by Andreas Loebel (ZIB Berlin)\n\n" );

    printf( "PORTA is free software and comes with ABSOLUTELY NO WARRENTY! You are welcome\n" );
    printf( "to use, modify, and redistribute it under the GNU General Public Lincese.\n\n" ); 
    
    printf( "This is the program VALID from the PORTA package.\n\n" );

    if( argc <= 2 )
    {
        fprintf( stderr,
                "For more information read the manpages about porta.\n\n");
        exit(-1);
    }
            
    /* 17.01.1994: include logging on file porta.log */
    if( !(logfile = fopen( "porta.log", "a" )) )
        fprintf( stderr, "can't open logfile porta.log\n" );
    else
    {
        porta_log( "\n\n\nlog for " );
        for( i = 0; i < argc; i++ )
            porta_log( "%s ", argv[i] );
        porta_log( "\n\n" );
    }
            

    initialize();
    set_I_functions();
    SET_MP_not_ready;
    
    prt = stdout;
    get_options(&argc,&argv);
    
    if (option & Protocol_to_file) 
    {
        strcat(*argv,".prt");
        prt = fopen(*argv,"w");
        (*argv)[strlen(*argv)-4] = '\0';
    }
    setbuf(prt,CP 0);
    
    if (is_set(Vint) && !strcmp(*argv+strlen(*argv)-4,".ieq")) 
    {  
            char *cp1,*cp2;
        cp1=strdup("LOWER_BOUNDS");
        cp2=strdup("UPPER_BOUNDS");
        if(!cp1||!cp2)
            msg("allocation of new space failed", "", 0 );   
        points = read_input_file(*argv,outfp,&dim,&ar1,(int *)&nel_ar1,
            cp1,&lowbds,cp2,&upbds,"\0",(RAT **)&i);
        free(cp1);free(cp2);
        sort_eqie_cvce(ar1,points,dim+2,&equa,&ineq);
        valid_ints( dim, ar1, equa, dim+2, dim,
                    ar1+(dim+2)*equa, ineq, dim+2, *argv );
    }
    else 
    {
        pothie = !strcmp(*argv+strlen(*argv)-4,".poi") 
            && !strcmp(*(argv+1)+strlen(*(argv+1))-4,".ieq");
        iethpo = !strcmp(*argv+strlen(*argv)-4,".ieq") 
            && !strcmp(*(argv+1)+strlen(*(argv+1))-4,".poi");
        if (!iethpo && !pothie)
            msg("invalid format of command line", "", 0 );
        
        if (iethpo) 
        {
            ineq = read_input_file(*argv,outfp,&dim,&ar1,(int *)&nel_ar1,
                                   "\0",(int **)&i,"\0",(int **)&i,"\0",(RAT **)&i );
            points = read_input_file(*(argv+1),outfp,&j,&ar2,(int *)&nel_ar2,
                                     "\0",(int **)&i,"\0",(int **)&i,"\0",(RAT **)&i );
        }
        else 
        {
            ineq = read_input_file(*(argv+1),outfp,&dim,&ar1, (int *)&nel_ar1,
                                   "\0", (int **)&i,"\0", (int **)&i,"\0", (RAT **)&i );
            points = read_input_file(*argv,outfp,&j,&ar2, (int *)&nel_ar2,
                                     "\0", (int **)&i,"\0", (int **)&i,"\0", (RAT **)&i );
        }
        if (j != dim) 
            msg("dimensions in input files are different", "", 0 ); 
        
        if (is_set(Iespo)) 
        {
            sort_eqie_cvce(ar1,ineq,dim+2,&equa,&ineq);
            valid_ieqs(dim,ar1,ineq+equa,&equa,&ineq,dim+2,
                       ar2,points,dim+1,(char **)(pothie?*argv:*(argv+1)));
        }
        else if (is_set(Posie) || is_set(Cfctp)) 
        {
            fout = iethpo?*argv:*(argv+1);
            sort_eqie_cvce(ar2,points,dim+1,&cone,&conv);
            if (is_set(Posie))
                valid_points(dim,ar2,points,dim+1,
                             ar1,ineq,dim+2,0,(char **)fout);
            else 
            {
                char fname[100];
                char command[100];
                RAT *ar1p;
                sort_eqie_cvce(ar1,ineq,dim+2,&equa,&ineq);
                if (equa )
                    msg( "only inequalities are allowed", "" , 0 );
                
                for (i = 0,ar1p = ar1; i < ineq; i++, ar1p += dim+2) 
                {
                    sprintf(fname,"%s%i",fout,i+1);
                    fprintf(prt,"I n e q u a l i t y   %2i :\n",i+1);
                    fprintf(prt,"==========================\n\n");
                    
                    /* 17.01.1994: include logging on file porta.log */
                    porta_log( "I n e q u a l i t y   %2i :\n",i+1);
                    porta_log( "==========================\n\n");
                    
                    fprintf(prt,"computing points  i n v a l i d  for the inequality :\n");
                    fprintf(prt,"=====================================================\n");

                    /* 17.01.1994: include logging on file porta.log */
                    porta_log( "computing points  i n v a l i d  for the inequality :\n");
                    porta_log( "=====================================================\n");

                    var[3].num = -1; var[3].den.i = 1;
                    scal_mul(var+3,ar1p,ar1p,dim+1);
                    j = valid_points(dim,ar2,points,dim+1,
                                     ar1p,1,dim+2,1, (char **)fname);
                    (ar1p+dim+1)->num = 0;
                    fprintf(prt,"computing points satisfying inequalitiy with equation :\n");
                    fprintf(prt,"=======================================================\n");
                    
                    /* 17.01.1994: include logging on file porta.log */
                    porta_log( "computing points satisfying inequalitiy with equation :\n");
                    porta_log( "=======================================================\n");
                    
                    if (j) strcat(fname,".poi");
                    k = valid_points(dim,ar2,points,dim+1,
                                     ar1p,1,dim+2,0, (char **)fname);
                    strcat(fname,".poi");
                    if (!j && k) 
                    {
                        sprintf(command,"dim %s",fname);
                        fprintf(prt,"dimension of the points :\n");
                        fprintf(prt,"=========================\n");
                        fflush(prt);
                        
                        /* 17.01.1994: include logging on file porta.log */
                        porta_log( "dimension of the points :\n");
                        porta_log( "=========================\n");
                        fflush( logfile );
                        
                        system(command);
                    }
                }
                
            }
        }
        else 
            msg( "invalid format of command line", "", 0 );
    } 

    return 0;
}
double R_rlm_rand(double *X, double *y, int *N, int *P,
		int *Boot_Samp, int *Nres,
		int *M, int *size_boot, double *ours, double *full,
		double *Beta_m, double *Beta_s, double *Scale,
		int *Seed, int *calc_full,
		double *C, double *Psi_c, int *max_it,
		int *converged_mm,
		int *groups, int *n_group, int *k_fast_s)
{
void initialize_mat(double **a, int n, int m);
void initialize_vec(double *a, int n);
void R_S_rlm(double *X, double *y, int *n, int *P,
		int *nres, int *max_it,
		double *SCale, double *beta_s, double *beta_m,
		int *converged_mm,
		int *seed_rand, double *C, double *Psi_c,
		int *Groups, int *N_group, int *K_fast_s);
double Psi_reg(double,double);
double Psi_reg_prime(double,double);
double Chi_prime(double,double);
double Chi(double,double);
void sampler_i(int, int, int *);
int inverse(double **,double **, int);
void matias_vec_vec(double **, double *, double *, int);
void scalar_mat(double **, double, double **, int, int);
void scalar_vec(double *, double, double *, int);
void sum_mat(double **,double **, double **, int, int);
void sum_vec(double *, double *, double *, int);
void dif_mat(double **, double **, double **, int , int );
void dif_vec(double *, double *, double *, int);
void mat_vec(double **, double *, double *, int, int);
void mat_mat(double **, double **, double **, int, int, int);
// void disp_vec(double *, int);
// void disp_mat(double **, int, int);
// void disp_mat_i(int **, int, int);
// void disp_vec(double *, int);
/* double **xb; */
double *Xb, **xb;
int **boot_samp;
double **x, **x2, **x3, **x4, *beta_m, *beta_s,*beta_aux;
double *Fi, *res, *res_s, *w, *ww, dummyscale, scale;
double *v, *v2, *v_aux, *yb; // , timefinish, timestart;
double u,u2,s,c,Psi_constant;
// double test_chi=0, test_psi=0;
int n,p,m,seed; // ,*indices;
int nboot=*size_boot;
// int fake_p = 0;
register int i,j,k;
setbuf(stdout,NULL);
c = *C; Psi_constant = *Psi_c;
n = *N; p = *P; m = *M; seed = *Seed;
boot_samp = (int **) malloc(m * sizeof(int*) );
for(i=0;i<m;i++)
	boot_samp[i] = (int*) malloc(nboot *sizeof(int));
// indices = (int *) malloc( n * sizeof(int) );
v = (double *) malloc( p * sizeof(double) );
v2 = (double *) malloc( p * sizeof(double) );
v_aux = (double *) malloc( p * sizeof(double) );
yb = (double *) malloc( n * sizeof(double) );
Xb = (double*) malloc( n * p * sizeof(double) );
x =  (double **) malloc ( n * sizeof(double *) );
xb =  (double **) malloc ( n * sizeof(double *) );
Fi  = (double *) malloc ( n * sizeof(double) );
res = (double *) malloc ( n * sizeof(double) );
res_s = (double *) malloc ( n * sizeof(double) );
ww  = (double *) malloc ( n * sizeof(double) );
w   = (double *) malloc ( n * sizeof(double) );
x2 = (double **) malloc ( p * sizeof(double *) );
x3 = (double **) malloc ( p * sizeof(double *) );
x4 = (double **) malloc ( p * sizeof(double *) );
beta_aux = (double *) malloc( p * sizeof(double) );
beta_m = (double *) malloc( p * sizeof(double) );
beta_s = (double *) malloc( p * sizeof(double) );
for(i=0;i<n;i++) {
	x[i] =  (double*) malloc (p * sizeof(double) );
	xb[i] =  (double*) malloc ((p+1) * sizeof(double) );
	};
for(i=0;i<p;i++) {
	x2[i] = (double*) malloc (p * sizeof(double) );
	x3[i] = (double*) malloc (p * sizeof(double) );
	x4[i] = (double*) malloc (p * sizeof(double) );
};
/* copy X into x for easier handling */
for(i=0;i<n;i++)
        for(j=0;j<p;j++)
                x[i][j]=X[j*n+i];
/* calculate robust regression estimates */

for(i=0;i<m;i++)
	for(j=0;j<nboot;j++)
		boot_samp[i][j]=Boot_Samp[j*m+i]-1;

R_S_rlm(X, y, N, P, Nres, max_it, &scale, Beta_s, Beta_m,
		converged_mm, &seed, &c,
		Psi_c, groups, n_group, k_fast_s);

*Scale = scale;
/* get M-fitted values in Fi */
mat_vec(x,Beta_m,Fi,n,p);
/* get residuals of M-est in res */
dif_vec(y,Fi,res,n);
/* get S-fitted values in res_s */
mat_vec(x,Beta_s,res_s,n,p);
/* get residuals of S-est in res_s */
dif_vec(y,res_s,res_s,n);
/* set auxiliary matrices to zero */

initialize_mat(x3, p, p);
initialize_mat(x4, p, p);
initialize_vec(v, p);
u2 = 0.0;
/* calculate correction matrix */

for(i=0;i<n;i++) {
	u = res[i]/scale ;
	w[i]  = Psi_reg(u,Psi_constant)/res[i];
        matias_vec_vec(x2,x[i],x[i],p);
	scalar_mat(x2,Psi_reg_prime(u,Psi_constant),
                x2,p,p);
        sum_mat(x3,x2,x3,p,p);
        matias_vec_vec(x2,x[i],x[i],p);
        scalar_mat(x2,w[i],x2,p,p);
        sum_mat(x4,x2,x4,p,p);
	scalar_vec(x[i],Psi_reg_prime(u,Psi_constant)*u,v_aux,p);
	sum_vec(v,v_aux,v,p);
	u2 += Chi_prime(u, c) * u;
};

/* scalar_vec(v, .5 * (double) (n-p) * scale / u2 , v, p);  */
scalar_vec(v, .5 * (double) n * scale / u2 , v, p);
inverse(x3,x2,p);
mat_mat(x2,x4,x3,p,p,p);
mat_vec(x2,v,v2,p,p);
scalar_mat(x3,scale,x3,p,p);
/* the correction matrix is now in x3 */
/* the correction vector is now in v2 */

/* start the bootstrap replications */
for(i=0;i<m;i++) {
	/* change the seed! */
	++seed;
	// sampler_i(n,nboot,indices);
	// for(j=0;j<nboot; j++)
	// 	indices[j]=boot_samp[i][j];
	/* get pseudo observed y's */
	for(j=0;j<nboot;j++) /* xb[j][p] = */
			yb[j] = y[boot_samp[i][j]];
	for(j=0;j<nboot;j++)
		for(k=0;k<p;k++) {
			// xb[j][k] = x[boot_samp[i][j]][k];
			// Xb[k*nboot+j] = X[k*n + indices[j]];
			Xb[k*nboot+j] = x[boot_samp[i][j]][k];
			xb[j][k] = Xb[k*nboot+j];
		};

	/* calculate full bootstrap estimate */

	if( *calc_full == 1 )
	R_S_rlm(Xb,yb,&nboot,P,Nres,max_it,&dummyscale,
			beta_s,beta_m,converged_mm,&seed,&c,
			Psi_c, groups, n_group, k_fast_s);

/* void R_S_rlm(double *X, double *y, int *n, int *P,
		int *nres, int *max_it,
		double *SCale, double *beta_s, double *beta_m,
		int *converged_mm,
		int *seed_rand, double *C, double *Psi_c,
		int *Groups, int *N_group, int *K_fast_s) */

	/*	double *C, double *Psi_c, int *max_it,
		int *groups, int *n_group, int *k_fast_s); */

	// HERE

	/* disp_mat(xb, nboot,p); */
	// disp_vec(yb,nboot);
	// Rprintf("\nfull scale: %f", dummyscale);

	/* calculate robust bootsrap */

	scalar_vec(v,0.0,v,p);	 	/* v <- 0 */
	scalar_mat(x2,0.0,x2,p,p);	/* x2 <- 0 */
	s = 0.0;
	for(j=0;j<nboot;j++) {
		scalar_vec(xb[j],yb[j]*w[boot_samp[i][j]],v_aux,p);
		sum_vec(v,v_aux,v,p);
		matias_vec_vec(x4,xb[j],xb[j],p);
		scalar_mat(x4,w[boot_samp[i][j]],x4,p,p);
		sum_mat(x2,x4,x2,p,p);
		s += Chi(res_s[boot_samp[i][j]] / scale , c);
	};
	/* s = s * scale / .5 / (double) (nboot - p)  ;  */
	s = s * scale / .5 / (double) n;
	inverse(x2,x4,p);		/* x4 <- x2^-1 */
	mat_vec(x4,v,v_aux,p,p);	/* v_aux <- x4 * v */
	dif_vec(v_aux,Beta_m,v_aux,p); 	/* v_aux <- v_aux - beta_m */
	/* v has the robust bootstrapped vector, correct it */
	mat_vec(x3,v_aux,v,p,p);	/* v <- x3 * v_aux */
	scalar_vec(v2,s-scale,v_aux,p);
	sum_vec(v_aux,v,v,p);

	/* store the betas (splus-wise!) */
	for(j=0;j<p;j++) {
		ours[j*m+i]=v[j];
		if( *calc_full == 1 )
			// full[j*m+i]=beta_m[j]-Beta_m[j];
			full[j*m+i]=beta_m[j];
	};
};
for(i=0;i<m;i++)
	free(boot_samp[i]);
free(boot_samp);
for(i=0;i<n;i++) {
	free(x[i]);
	free(xb[i]);
	};
for(i=0;i<p;i++) {
	free(x2[i]);
	free(x3[i]);
	free(x4[i]);
	};
free(x) ;free(x2);free(xb);
free(x3);free(x4);
free(beta_aux);free(beta_m);free(beta_s);
free(w);free(ww);free(Fi);free(res);
free(v);free(v2);free(v_aux);free(yb);
free(res_s);
free(Xb);
return(0);
}
Esempio n. 7
0
int main()
{
   setbuf(stdout, NULL);

   for (long l = 5; l <= 60; l += 5) {
      // for (long n = 1024; n <= 65536; n *= 2) {
      for (long idx = 0; idx < 13; idx ++) {
         long n  = 1024*(1L << idx/2);
         if (idx & 1) n += n/2;
           SetSeed((ZZ(l) << 64) + ZZ(n));

	   long p;

	   RandomLen(p, l);
           if (p % 2 == 0) p++;
	   zz_p::init(p);


	   zz_pX a, b, c, f;

	   random(a, n);
	   random(b, n);
           random(f, n);
           SetCoeff(f, n);

           zz_pXModulus F(f);
           zz_pXMultiplier B(b, F);

	   double t;

	   MulMod(c, a, B, F);

	   long iter = 1;
	   do {
	      t = GetTime();
	      for (long i = 0; i < iter; i++) MulMod(c, a, B, F);
	      t = GetTime() - t;
	      iter *= 2;
	   } while (t < 3);
	   iter /= 2;

	   t = GetTime();
	   for (long i = 0; i < iter; i++) MulMod(c, a, B, F);
	   t = GetTime()-t;
	   double NTLTime = t;



         Flintzz_pX f_a(a), f_b(b), f_c, f_f(f), f_finv;
         nmod_poly_reverse(f_finv.value, f_f.value, f_f.value->length);
         nmod_poly_inv_series_newton(f_finv.value, f_finv.value, f_f.value->length);

         nmod_poly_mulmod_preinv(f_c.value, f_a.value, f_b.value, f_f.value, f_finv.value);


         t = GetTime();
         for (long i = 0; i < iter; i++)
            nmod_poly_mulmod_preinv(f_c.value, f_a.value, f_b.value, f_f.value, f_finv.value);
         t = GetTime()-t;
         double FlintTime = t;


         printf("%8.2f", FlintTime/NTLTime);
      }

      printf("\n");
   }
}
Esempio n. 8
0
int main(int argc, char **argv)
{
	setbuf(stdout, NULL);
	setbuf(stderr, NULL);
	
	{
		WSADATA wsaData;
		assert(WSAStartup(MAKEWORD(1,1), &wsaData) == 0);
	}
	
	int sockets[MAX_SOCKETS];
	int n_sockets = 0;
	
	for(int i = 1; i < argc; i += 3)
	{
		BOOL bcast       = FALSE;
		BOOL recv_bcast  = TRUE;
		BOOL reuse       = FALSE;
		int filter_ptype = -1;
		
		while(argv[i][0] == '-')
		{
			if(strcmp(argv[i], "-b") == 0)
			{
				bcast = TRUE;
			}
			else if(strcmp(argv[i], "-B") == 0)
			{
				recv_bcast = FALSE;
			}
			else if(strcmp(argv[i], "-r") == 0)
			{
				reuse = TRUE;
			}
			else if(strcmp(argv[i], "-f") == 0)
			{
				filter_ptype = atoi(argv[++i]);
			}
			else{
				usage(argv[0]);
			}
			
			++i;
		}
		
		if((argc - i) < 3)
		{
			usage(argv[0]);
		}
		
		int sock = socket(AF_IPX, SOCK_DGRAM, NSPROTO_IPX);
		assert(sock != -1);
		
		assert(setsockopt(sock, SOL_SOCKET,  SO_BROADCAST,          (void*)(&bcast),      sizeof(bcast)) == 0);
		assert(setsockopt(sock, NSPROTO_IPX, IPX_RECEIVE_BROADCAST, (void*)(&recv_bcast), sizeof(recv_bcast)) == 0);
		assert(setsockopt(sock, SOL_SOCKET,  SO_REUSEADDR,          (void*)(&reuse),      sizeof(reuse)) == 0);
		
		if(filter_ptype >= 0)
		{
			assert(setsockopt(sock, NSPROTO_IPX, IPX_FILTERPTYPE, (void*)(&filter_ptype), sizeof(filter_ptype)) == 0);
		}
		
		struct sockaddr_ipx bind_addr = read_sockaddr(argv[i], argv[i + 1], argv[i + 2]);
		assert(bind(sock, (struct sockaddr*)(&bind_addr), sizeof(bind_addr)) == 0);
		
		int addrlen = sizeof(bind_addr);
		assert(getsockname(sock, (struct sockaddr*)(&bind_addr), &addrlen) == 0);
		
		char formatted_addr[IPX_SADDR_SIZE];
		ipx_to_string(formatted_addr,
			addr32_in(bind_addr.sa_netnum), addr48_in(bind_addr.sa_nodenum), bind_addr.sa_socket);
		
		printf("Bound socket %d to local address: %s\n", sock, formatted_addr);
		
		if(n_sockets == MAX_SOCKETS)
		{
			fprintf(stderr, "Too many bind addresses given\n");
			fprintf(stderr, "Compile with a bigger MAX_SOCKETS\n");
			
			return 1;
		}
		
		sockets[n_sockets++] = sock;
	}
	
	if(n_sockets == 0)
	{
		usage(argv[0]);
	}
	
	printf("Ready\n");
	
	while(1)
	{
		fd_set read_fds;
		FD_ZERO(&read_fds);
		
		for(int i = 0; i < n_sockets; ++i)
		{
			FD_SET(sockets[i], &read_fds);
		}
		
		assert(select(n_sockets, &read_fds, NULL, NULL, NULL) > 0);
		
		for(int i = 0; i < n_sockets; ++i)
		{
			if(FD_ISSET(sockets[i], &read_fds))
			{
				struct sockaddr_ipx recv_addr;
				int addrlen = sizeof(recv_addr);
				
				char buf[BUFSIZE + 1];
				int len;
				
				assert((len = recvfrom(sockets[i], buf, BUFSIZE, 0, (struct sockaddr*)(&recv_addr), &addrlen)) > 0);
				buf[len] = '\0';
				
				char formatted_addr[IPX_SADDR_SIZE];
				ipx_to_string(formatted_addr,
					addr32_in(recv_addr.sa_netnum), addr48_in(recv_addr.sa_nodenum), recv_addr.sa_socket);
				
				printf("Received %d bytes (%s) on socket %d from %s\n",
					len, buf, sockets[i], formatted_addr);
			}
		}
	}
	
	for(int i = 0; i < n_sockets; ++i)
	{
		closesocket(sockets[i]);
	}
	
	WSACleanup();
	
	return 0;
}
Esempio n. 9
0
int main(int argc, char **argv)
{
    setbuf(stdout, NULL);
    signal(SIGINT, INThandler);

    unsigned char ply = 6;

    int opt;
    while ((opt = getopt(argc, argv, "p:")) != -1) {
        switch (opt) {
        case 'p':
            ply = atoi(optarg);
            break;
        default:
            fprintf(stderr, "Usage: %s [-p ply]\n", argv[0]);
            exit(EXIT_FAILURE);
        }
    }

    struct position pos;
    init_position(&pos);
    assert(consistency(&pos));

    struct timespec realt_old, realt_new;

    tt = new_trans_tables();

#ifdef _USE_HISTORY
    hist = init_history();
#endif

#ifdef _DEBUG
    testing();
#endif

#ifndef _XBOARD
    print_position(&pos);
#endif

    while (1) {
        if (is_check(&pos)) {
            fprintf(stderr, "check.\n");
        }

        user_input(&pos);
#ifndef _XBOARD
        print_position(&pos);
#endif
        assert(consistency(&pos));

        if (is_check(&pos)) {
            fprintf(stderr, "check.\n");
        }

        current_utc_time(&realt_old);
        computer_move(&pos, ply);
        assert(consistency(&pos));
        current_utc_time(&realt_new);

#ifndef _XBOARD
        fprintf(stderr, "One second: %12llu ns\n",
            (long long unsigned)BILLION);
        fprintf(stderr, "Real  time: %12llu ns\n",
            (long long unsigned)minus_time(&realt_new, &realt_old));

        print_position(&pos);
#endif
    }

    return (0);
}
Esempio n. 10
0
int
ttyrec_main (int game, char *username, char *ttyrec_path, char* ttyrec_filename)
{
  char dirname[100];

  /* Note our PID to let children kill the main dgl process for idling */
  dgl_parent = getpid();
  child = subchild = input_child = 0;

  if (!ttyrec_path) {
      child = fork();
      if (child < 0) {
	  perror ("fork");
	  fail ();
      }
      if (child == 0) {
	  execvp (myconfig[game]->game_path, myconfig[game]->bin_args);
      } else {
	  int status;
	  (void) wait(&status);
      }
      return 0;
  }

  if (ttyrec_path[strlen(ttyrec_path)-1] == '/')
      snprintf (dirname, 100, "%s%s", ttyrec_path, ttyrec_filename);
  else
      snprintf (dirname, 100, "%s/%s", ttyrec_path, ttyrec_filename);

  atexit(&remove_ipfile);
  if ((fscript = fopen (dirname, "w")) == NULL)
    {
      perror (dirname);
      fail ();
    }
  setbuf (fscript, NULL);

  fixtty ();

  (void) signal (SIGCHLD, finish);
  child = fork ();
  if (child < 0)
    {
      perror ("fork");
      fail ();
    }
  if (child == 0)
    {
      subchild = child = fork ();
      if (child < 0)
        {
          perror ("fork");
          fail ();
        }
      if (child)
        {
          close (slave);
          ipfile = gen_inprogress_lock (game, child, ttyrec_filename);
	  ttyrec_id(game, username, ttyrec_filename);
          dooutput (myconfig[game]->max_idle_time);
        }
      else
	  doshell (game, username);
    }

  (void) fclose (fscript);

  wait_for_menu = 1;
  input_child = fork();
  if (input_child < 0)
  {
      perror ("fork2");
      fail ();
  }
  if (!input_child)
      doinput ();
  else
  {
      while (wait_for_menu)
	  sleep(1);
  }

  remove_ipfile();
  child = 0;

  return 0;
}
Esempio n. 11
0
int main(int argc, char *argv[])
{
    if ( argc != 3 )
    {
        return 1; //not enough arguments
    }

    const char ltr = argv[2][0];
    const char *imagefile = argv[1];

    status = STATUS_IDLE;
    hVolume = INVALID_HANDLE_VALUE;
    hFile = INVALID_HANDLE_VALUE;
    hRawDisk = INVALID_HANDLE_VALUE;
    sectorData = NULL;
    sectorsize = 0ul;

    if (strcmp( imagefile, "") != 0)
    {
        if(INVALID_FILE_ATTRIBUTES == GetFileAttributes(imagefile) && GetLastError()==ERROR_FILE_NOT_FOUND)
        {
            return 2; // .img not found
        }
        else
        {
            status = STATUS_WRITING;

            unsigned long long i, availablesectors, numsectors;
            int volumeID = ltr - 'A';
            int deviceID = getDriveNumberFromLetter(ltr);
            if( deviceID == -1 )
            {
                return 3; // device not found
            }

            hVolume = getHandleOnVolume(volumeID, GENERIC_WRITE);
            if (hVolume == INVALID_HANDLE_VALUE)
            {
                status = STATUS_IDLE;
                return 4; // invalid handle value for volume
            }
            if (!getLockOnVolume(hVolume))
            {
                CloseHandle(hVolume);
                status = STATUS_IDLE;
                hVolume = INVALID_HANDLE_VALUE;
                return 5; // can't get lock on volume
            }
            if (!unmountVolume(hVolume))
            {
                removeLockOnVolume(hVolume);
                CloseHandle(hVolume);
                status = STATUS_IDLE;
                hVolume = INVALID_HANDLE_VALUE;
                return 6; // can't unmount volume
            }
            hFile = getHandleOnFile(imagefile, GENERIC_READ);
            if (hFile == INVALID_HANDLE_VALUE)
            {
                removeLockOnVolume(hVolume);
                CloseHandle(hVolume);
                status = STATUS_IDLE;
                hVolume = INVALID_HANDLE_VALUE;
                return 7; // invalid handle value for file
            }
            hRawDisk = getHandleOnDevice(deviceID, GENERIC_WRITE);
            if (hRawDisk == INVALID_HANDLE_VALUE)
            {
                removeLockOnVolume(hVolume);
                CloseHandle(hFile);
                CloseHandle(hVolume);
                status = STATUS_IDLE;
                hVolume = INVALID_HANDLE_VALUE;
                hFile = INVALID_HANDLE_VALUE;
                return 8; // invalid handle value for disk
            }
            availablesectors = getNumberOfSectors(hRawDisk, &sectorsize);
            numsectors = getFileSizeInSectors(hFile, sectorsize);
            if (numsectors > availablesectors)
            {
                return 9; // not enough space on volume
            }

            char total_string[32];
            sprintf(total_string, "%d", numsectors);

            for (i = 0ul; i < numsectors && status == STATUS_WRITING; i += 1024ul)
            {
                if( i % 100 == 0 )
                {
                    char i_string[32];
                    sprintf(i_string, "%d", i);
                    printf(i_string);
                    printf("/");
                    printf(total_string);
                    setbuf(stdout, NULL);
                }

                sectorData = readSectorDataFromHandle(hFile, i, (numsectors - i >= 1024ul) ? 1024ul:(numsectors - i), sectorsize);
                if (sectorData == NULL)
                {
                    removeLockOnVolume(hVolume);
                    CloseHandle(hRawDisk);
                    CloseHandle(hFile);
                    CloseHandle(hVolume);
                    status = STATUS_IDLE;
                    hRawDisk = INVALID_HANDLE_VALUE;
                    hFile = INVALID_HANDLE_VALUE;
                    hVolume = INVALID_HANDLE_VALUE;
                    return 10; // sector data is null
                }
                if (!writeSectorDataToHandle(hRawDisk, sectorData, i, (numsectors - i >= 1024ul) ? 1024ul:(numsectors - i), sectorsize))
                {
                    delete[] sectorData;
                    removeLockOnVolume(hVolume);
                    CloseHandle(hRawDisk);
                    CloseHandle(hFile);
                    CloseHandle(hVolume);
                    status = STATUS_IDLE;
                    sectorData = NULL;
                    hRawDisk = INVALID_HANDLE_VALUE;
                    hFile = INVALID_HANDLE_VALUE;
                    hVolume = INVALID_HANDLE_VALUE;
                    return 11; // error whilst writing
                }
                delete[] sectorData;
                sectorData = NULL;
            }
            removeLockOnVolume(hVolume);
            CloseHandle(hRawDisk);
            CloseHandle(hFile);
            CloseHandle(hVolume);
            hRawDisk = INVALID_HANDLE_VALUE;
            hFile = INVALID_HANDLE_VALUE;
            hVolume = INVALID_HANDLE_VALUE;
        }
        return 0; // success
    }
    else
    {
        return 1; // not enough arguments
    }
    status = STATUS_IDLE;
    return 11; // error whilst writing
}
Esempio n. 12
0
int main(int argc,char *argv[])
{
  char euclid_output[100],target_output[100];
  Real sse;
  FILE *f;
  Real clampNoise=0.1;
  char feature[1000][30];
  char name[255];
  int time=4;
  int wrongs=0,wrong=0,wrongtot;
  char weightFile[4000];
  int reset=1;
  ExampleSet *examples;
  Example *ex;
  int i,count;
  Real error;
  Real epsilon,range;
  int runfor=TICKS;


  f=fopen("key","r");
  if (f==NULL)
    {
      fprintf(stderr,"can't open key file\n");
      exit(-1);
    }

  i=0;
  fscanf(f,"%s",feature[i++]);
  while(!feof(f))
    fscanf(f,"%s",feature[i++]);
  fclose(f);

  /* don't buffer output */
  setbuf(stdout,NULL);

  /* set random number seed to process id
     (only unix machines have getpid call) */
#ifdef unix
  mikenet_set_seed(getpid()); 
#endif

  /* a default learning rate */
  epsilon=0.01;
  
  /* default weight range */
  range=0.01;

  /* what are the command line arguments? */
  for(i=1;i<argc;i++)
    {
      if (strcmp(argv[i],"-seed")==0)
	{
	  mikenet_set_seed(atol(argv[i+1]));
	  i++;
	}
      else if (strncmp(argv[i],"-epsilon",5)==0)
	{
	  epsilon=atof(argv[i+1]);
	  i++;
	}
      else if (strcmp(argv[i],"-clampNoise")==0)
	{
	  clampNoise=atof(argv[i+1]);
	  i++;
	}
      else if (strncmp(argv[i],"-noreset",5)==0)
	{
	  reset=0;
	}
      else if (strncmp(argv[i],"-runfor",5)==0)
	{
	  runfor=atoi(argv[i+1]);
	  i++;
	}
      else if (strncmp(argv[i],"-time",5)==0)
	{
	  time=atoi(argv[i+1]);
	  i++;
	}
      else if (strcmp(argv[i],"-range")==0)
	{
	  range=atof(argv[i+1]);
	  i++;
	}
      else if ((strncmp(argv[i],"-weight",5)==0) ||
	       (strncmp(argv[i],"-load",5)==0))
	{
	  strcpy(weightFile,argv[i+1]);
	  i++;
	}
      else if (strcmp(argv[i],"-errorRadius")==0)
	{
	  default_errorRadius=atof(argv[i+1]);
	  i++;
	}
      else
	{
	  fprintf(stderr,"unknown argument: %s\n",argv[i]);
	  exit(-1);
	}
    }

  build_hearing_model();
  hearing->integrationConstant=(float)time/(float)TICKS;
  hearing->runfor=runfor;
  sp->integrationConstant=(float)time/(float)TICKS;
  sp->runfor=runfor;

  examples=load_examples("sp.pat",TICKS);
  load_weights(hearing,weightFile);

  load_phonemes();

  error=0.0;
  count=1;
  wrongs=0;
  wrongtot=0;
  /* loop for ITER number of times */
  for(i=0;i<examples->numExamples;i++)
    {
      /* get j'th example from exampleset */
      ex=&examples->examples[i];
      get_name(ex->name,name);
      printf("%s\t",name);
      /* do forward propagation */
      crbp_forward(sp,ex);
      wrong=0;
      sse=0.0;
      euclid(phonology->outputs[runfor-1],euclid_output);
      printf("%s\t",euclid_output);
      euclid(ex->targets[phonology->index][runfor-1],target_output);
      printf("%s\t",target_output);
      if (strcmp(target_output,euclid_output)!=0)
	{
	  printf("[WRONG]\n");
	  wrongs++;
	}
      else printf("\n");
    }
  printf("%d wrong\n",wrongs);
  return 0;
}
int main(int argc, char* argv[])
{
    char hostName[200] = DEFAULT_HOSTNAME;
    int port = DEFAULT_RESMGR_TPM_PORT; //DEFAULT_TPM_PORT;
    char *contextFilePath = NULL;
    char *keyContextFilePath = NULL;

    setbuf(stdout, NULL);
    setvbuf (stdout, NULL, _IONBF, BUFSIZ);

    int opt = -1;
    const char *optstring = "hvH:c:k:C:P:K:f:o:p:d:";
    struct option long_options[] = {
      {"help",0,NULL,'h'},
      {"version",0,NULL,'v'},
      {"handle",1,NULL,'H'},
      {"context",1,NULL,'c'},
      {"keyHandle",1,NULL,'k'},
      {"keyContext",1,NULL,'C'},
      {"Password",1,NULL,'P'},
      {"keyPassword",1,NULL,'K'},
      {"inFile",1,NULL,'f'},
      {"outFile",1,NULL,'o'},
      {"port",1,NULL,'p'},
      {"debugLevel",1,NULL,'d'},
      {0,0,0,0},
    };

    int returnVal = 0;
    int flagCnt = 0;
    int h_flag = 0,
        v_flag = 0,
        H_flag = 0,
        c_flag = 0,
        k_flag = 0,
        C_flag = 0,
        K_flag = 0,
        P_flag = 0,
        f_flag = 0,
        o_flag = 0;

    if(argc == 1)
    {
        showHelp(argv[0]);
        return 0;
    }

    cmdAuth.hmac.t.size = 0;
    cmdAuth2.hmac.t.size = 0;

    while((opt = getopt_long(argc,argv,optstring,long_options,NULL)) != -1)
    {
        switch(opt)
        {
        case 'h':
            h_flag = 1;
            break;
        case 'v':
            v_flag = 1;
            break;
        case 'H':
            if(getSizeUint32Hex(optarg,&activateHandle) != 0)
            {
                returnVal = -1;
                break;
            }
            H_flag = 1;
            break;
        case 'c':
            contextFilePath = optarg;
            if(contextFilePath == NULL || contextFilePath[0] == '\0')
            {
                returnVal = -2;
                break;
            }
            printf("contextFile = %s\n", contextFilePath);
            c_flag = 1;
            break;
        case 'k':
            if(getSizeUint32Hex(optarg,&keyHandle) != 0)
            {
                returnVal = -3;
                break;
            }
            k_flag = 1;
            break;
        case 'C':
            keyContextFilePath = optarg;
            if(keyContextFilePath == NULL || keyContextFilePath[0] == '\0')
            {
                returnVal = -4;
                break;
            }
            printf("keyContextFile = %s\n", keyContextFilePath);
            C_flag = 1;
            break;
        case 'P':
            cmdAuth.hmac.t.size = sizeof(cmdAuth.hmac.t) - 2;
            if(str2ByteStructure(optarg,&cmdAuth.hmac.t.size,cmdAuth.hmac.t.buffer) != 0)
            {
                returnVal = -5;
                break;
            }
            P_flag = 1;
            break;
        case 'K':
            cmdAuth2.hmac.t.size = sizeof(cmdAuth2.hmac.t) - 2;
            if(str2ByteStructure(optarg,&cmdAuth2.hmac.t.size,cmdAuth2.hmac.t.buffer) != 0)
            {
                returnVal = -6;
                break;
            }
            K_flag = 1;
            break;
        case 'f':
            if(readCrtSecFromFile(optarg,&credentialBlob,&secret) != 0)
            {
                returnVal = -7;
                break;
            }
            f_flag = 1;
            break;
        case 'o':
            safeStrNCpy(outFilePath, optarg, sizeof(outFilePath));
#if 0
            if(checkOutFile(outFilePath) != 0)
            {
                returnVal = -1;
                break;
            }
#endif
            o_flag = 1;
            break;
        case 'p':
            if( getPort(optarg, &port) )
            {
                printf("Incorrect port number.\n");
                returnVal = -8;
            }
            break;
        case 'd':
            if( getDebugLevel(optarg, &debugLevel) )
            {
                printf("Incorrect debug level.\n");
                returnVal = -9;
            }
            break;
        case ':':
//              printf("Argument %c needs a value!\n",optopt);
            returnVal = -10;
            break;
        case '?':
//              printf("Unknown Argument: %c\n",optopt);
            returnVal = -11;
            break;
        //default:
        //  break;
        }
        if(returnVal)
            break;
    };

    if(returnVal != 0)
        return returnVal;
    flagCnt = h_flag + v_flag + H_flag + c_flag + k_flag + C_flag + f_flag + o_flag;

    if(flagCnt == 1)
    {
        if(h_flag == 1)
            showHelp(argv[0]);
        else if(v_flag == 1)
            showVersion(argv[0]);
        else
        {
            showArgMismatch(argv[0]);
            return -12;
        }
    }
    else if((flagCnt == 4) && (H_flag == 1 || c_flag == 1) && (k_flag == 1 || C_flag == 1) && (f_flag == 1) && (o_flag == 1))
    {
        prepareTest(hostName, port, debugLevel);

        if(c_flag)
            returnVal = loadTpmContextFromFile(sysContext, &activateHandle, contextFilePath);
        if(C_flag && returnVal == 0)
            returnVal = loadTpmContextFromFile(sysContext, &keyHandle, keyContextFilePath);
        if(returnVal == 0)
            returnVal = activateCredential();

        finishTest();

        if(returnVal)
            return -13;
    }
    else
    {
        showArgMismatch(argv[0]);
        return -14;
    }
    return 0;
}
Esempio n. 14
0
File: main.c Progetto: infoburp/gawk
int
main(int argc, char **argv)
{
	/*
	 * The + on the front tells GNU getopt not to rearrange argv.
	 */
	const char *optlist = "+F:f:v:W;bcCd::D::e:E:gh:i:l:L:nNo::Op::MPrStVY";
	bool stopped_early = false;
	int old_optind;
	int i;
	int c;
	char *scan, *src;
	char *extra_stack;
	int have_srcfile = 0;
	SRCFILE *s;

	/* do these checks early */
	if (getenv("TIDYMEM") != NULL)
		do_flags |= DO_TIDY_MEM;

#ifdef HAVE_MCHECK_H
#ifdef HAVE_MTRACE
	if (do_tidy_mem)
		mtrace();
#endif /* HAVE_MTRACE */
#endif /* HAVE_MCHECK_H */

#if defined(LC_CTYPE)
	setlocale(LC_CTYPE, "");
#endif
#if defined(LC_COLLATE)
	setlocale(LC_COLLATE, "");
#endif
#if defined(LC_MESSAGES)
	setlocale(LC_MESSAGES, "");
#endif
#if defined(LC_NUMERIC) && defined(HAVE_LOCALE_H)
	/*
	 * Force the issue here.  According to POSIX 2001, decimal
	 * point is used for parsing source code and for command-line
	 * assignments and the locale value for processing input,
	 * number to string conversion, and printing output.
	 *
	 * 10/2005 --- see below also; we now only use the locale's
	 * decimal point if do_posix in effect.
	 *
	 * 9/2007:
	 * This is a mess. We need to get the locale's numeric info for
	 * the thousands separator for the %'d flag.
	 */
	setlocale(LC_NUMERIC, "");
	init_locale(& loc);
	setlocale(LC_NUMERIC, "C");
#endif
#if defined(LC_TIME)
	setlocale(LC_TIME, "");
#endif

#if MBS_SUPPORT
	/*
	 * In glibc, MB_CUR_MAX is actually a function.  This value is
	 * tested *a lot* in many speed-critical places in gawk. Caching
	 * this value once makes a speed difference.
	 */
	gawk_mb_cur_max = MB_CUR_MAX;
	/* Without MBS_SUPPORT, gawk_mb_cur_max is 1. */
#ifdef LIBC_IS_BORKED
{
	const char *env_lc;

	env_lc = getenv("LC_ALL");
	if (env_lc == NULL)
		env_lc = getenv("LANG");
	if (env_lc != NULL && env_lc[1] == '\0' && tolower(env_lc[0]) == 'c')
		gawk_mb_cur_max = 1;
}
#endif

	/* init the cache for checking bytes if they're characters */
	init_btowc_cache();
#endif

	(void) bindtextdomain(PACKAGE, LOCALEDIR);
	(void) textdomain(PACKAGE);

	(void) signal(SIGFPE, catchsig);
#ifdef SIGBUS
	(void) signal(SIGBUS, catchsig);
#endif
#ifdef SIGPIPE
	/*
	 * Ignore SIGPIPE so that writes to pipes that fail don't
	 * kill the process but instead return -1 and set errno.
	 * That lets us print a fatal message instead of dieing suddenly.
	 *
	 * Note that this requires ignoring EPIPE when writing and
	 * flushing stdout/stderr in other parts of the program. E.g.,
	 *
	 * 	gawk 'BEGIN { print "hi" }' | exit
	 *
	 * should not give us "broken pipe" messages --- mainly because
	 * it did not do so in the past and people would complain.
	 */
	signal(SIGPIPE, SIG_IGN);
#endif

	(void) sigsegv_install_handler(catchsegv);
#define STACK_SIZE (16*1024)
	emalloc(extra_stack, char *, STACK_SIZE, "main");
	(void) stackoverflow_install_handler(catchstackoverflow, extra_stack, STACK_SIZE);
#undef STACK_SIZE

	myname = gawk_name(argv[0]);
	os_arg_fixup(&argc, &argv); /* emulate redirection, expand wildcards */

	if (argc < 2)
		usage(EXIT_FAILURE, stderr);

	/* initialize the null string */
	Nnull_string = make_string("", 0);

	/* Robustness: check that file descriptors 0, 1, 2 are open */
	init_fds();

	/* init array handling. */
	array_init();

	/* init the symbol tables */
	init_symbol_table();

	output_fp = stdout;

	/* we do error messages ourselves on invalid options */
	opterr = false;

	/* copy argv before getopt gets to it; used to restart the debugger */  
	save_argv(argc, argv);

	/* initialize global (main) execution context */
	push_context(new_context());

	/* option processing. ready, set, go! */
	for (optopt = 0, old_optind = 1;
	     (c = getopt_long(argc, argv, optlist, optab, NULL)) != EOF;
	     optopt = 0, old_optind = optind) {
		if (do_posix)
			opterr = true;

		switch (c) {
		case 'F':
			add_preassign(PRE_ASSIGN_FS, optarg);
			break;

		case 'E':
			disallow_var_assigns = true;
			/* fall through */
		case 'f':
			/*
			 * Allow multiple -f options.
			 * This makes function libraries real easy.
			 * Most of the magic is in the scanner.
			 *
			 * The following is to allow for whitespace at the end
			 * of a #! /bin/gawk line in an executable file
			 */
			scan = optarg;
			if (argv[optind-1] != optarg)
				while (isspace((unsigned char) *scan))
					scan++;
			src = (*scan == '\0' ? argv[optind++] : optarg);
			(void) add_srcfile((src && src[0] == '-' && src[1] == '\0') ?
					SRC_STDIN : SRC_FILE,
					src, srcfiles, NULL, NULL);

			break;

		case 'v':
			add_preassign(PRE_ASSIGN, optarg);
			break;

		case 'b':
			do_binary = true;
			break;

		case 'c':
			do_flags |= DO_TRADITIONAL;
			break;

		case 'C':
			copyleft();
			break;

		case 'd':
			do_flags |= DO_DUMP_VARS;
			if (optarg != NULL && optarg[0] != '\0')
				varfile = optarg;
			break;

		case 'D':
			do_flags |= DO_DEBUG;
			if (optarg != NULL && optarg[0] != '\0')
				command_file = optarg;
			break;

		case 'e':
			if (optarg[0] == '\0')
				warning(_("empty argument to `-e/--source' ignored"));
			else
				(void) add_srcfile(SRC_CMDLINE, optarg, srcfiles, NULL, NULL);
			break;

		case 'g':
			do_flags |= DO_INTL;
			break;

		case 'h':
			/* write usage to stdout, per GNU coding stds */
			usage(EXIT_SUCCESS, stdout);
			break;

		case 'i':
			(void) add_srcfile(SRC_INC, optarg, srcfiles, NULL, NULL);
			break;

		case 'l':
			(void) add_srcfile(SRC_EXTLIB, optarg, srcfiles, NULL, NULL);
			break;

#ifndef NO_LINT
		case 'L':
			do_flags |= DO_LINT_ALL;
			if (optarg != NULL) {
				if (strcmp(optarg, "fatal") == 0)
					lintfunc = r_fatal;
				else if (strcmp(optarg, "invalid") == 0) {
					do_flags &= ~DO_LINT_ALL;
					do_flags |= DO_LINT_INVALID;
				}
			}
			break;

		case 't':
			do_flags |= DO_LINT_OLD;
			break;
#else
		case 'L':
		case 't':
			break;
#endif

		case 'n':
			do_flags |= DO_NON_DEC_DATA;
			break;

		case 'N':
			use_lc_numeric = true;
			break;

		case 'O':
			do_optimize = true;
			break;

		case 'p':
			do_flags |= DO_PROFILE;
			/* fall through */
		case 'o':
			do_flags |= DO_PRETTY_PRINT;
			if (optarg != NULL)
				set_prof_file(optarg);
			else
				set_prof_file(DEFAULT_PROFILE);
			break;

		case 'M':
#ifdef HAVE_MPFR
			do_flags |= DO_MPFR;
#endif
			break;

		case 'P':
			do_flags |= DO_POSIX;
			break;

		case 'r':
			do_flags |= DO_INTERVALS;
 			break;
 
		case 'S':
			do_flags |= DO_SANDBOX;
  			break;

		case 'V':
			do_version = true;
			break;

		case 'W':       /* gawk specific options - now in getopt_long */
			fprintf(stderr, _("%s: option `-W %s' unrecognized, ignored\n"),
				argv[0], optarg);
			break;

		case 0:
			/*
			 * getopt_long found an option that sets a variable
			 * instead of returning a letter. Do nothing, just
			 * cycle around for the next one.
			 */
			break;

		case 'Y':
#if defined(YYDEBUG) || defined(GAWKDEBUG)
			if (c == 'Y') {
				yydebug = 2;
				break;
			}
#endif
			/* if not debugging, fall through */
		case '?':
		default:
			/*
			 * If not posix, an unrecognized option stops argument
			 * processing so that it can go into ARGV for the awk
			 * program to see. This makes use of ``#! /bin/gawk -f''
			 * easier.
			 *
			 * However, it's never simple. If optopt is set,
			 * an option that requires an argument didn't get the
			 * argument. We care because if opterr is 0, then
			 * getopt_long won't print the error message for us.
			 */
			if (! do_posix
			    && (optopt == '\0' || strchr(optlist, optopt) == NULL)) {
				/*
				 * can't just do optind--. In case of an
				 * option with >= 2 letters, getopt_long
				 * won't have incremented optind.
				 */
				optind = old_optind;
				stopped_early = true;
				goto out;
			} else if (optopt != '\0') {
				/* Use POSIX required message format */
				fprintf(stderr,
					_("%s: option requires an argument -- %c\n"),
					myname, optopt);
				usage(EXIT_FAILURE, stderr);
			}
			/* else
				let getopt print error message for us */
			break;
		}
		if (c == 'E')	/* --exec ends option processing */
			break;
	}
out:

	if (do_nostalgia)
		nostalgia();

	/* check for POSIXLY_CORRECT environment variable */
	if (! do_posix && getenv("POSIXLY_CORRECT") != NULL) {
		do_flags |= DO_POSIX;
		if (do_lint)
			lintwarn(
	_("environment variable `POSIXLY_CORRECT' set: turning on `--posix'"));
	}

	if (do_posix) {
		use_lc_numeric = true;
		if (do_traditional)	/* both on command line */
			warning(_("`--posix' overrides `--traditional'"));
		else
			do_flags |= DO_TRADITIONAL;
			/*
			 * POSIX compliance also implies
			 * no GNU extensions either.
			 */
	}

	if (do_traditional && do_non_decimal_data) {
		do_flags &= ~DO_NON_DEC_DATA;
		warning(_("`--posix'/`--traditional' overrides `--non-decimal-data'"));
	}

	if (do_lint && os_is_setuid())
		warning(_("running %s setuid root may be a security problem"), myname);

#if MBS_SUPPORT
	if (do_binary) {
		if (do_posix)
			warning(_("`--posix' overrides `--characters-as-bytes'"));
		else
			gawk_mb_cur_max = 1;	/* hands off my data! */
#if defined(LC_ALL)
		setlocale(LC_ALL, "C");
#endif
	}
#endif

	if (do_debug)	/* Need to register the debugger pre-exec hook before any other */
		init_debug();

#ifdef HAVE_MPFR
	/* Set up MPFR defaults, and register pre-exec hook to process arithmetic opcodes */ 
	if (do_mpfr)
		init_mpfr(DEFAULT_PREC, DEFAULT_ROUNDMODE);
#endif

	/* load group set */
	init_groupset();

#ifdef HAVE_MPFR
	if (do_mpfr) {
		mpz_init(Nnull_string->mpg_i);
		Nnull_string->flags = (MALLOC|STRCUR|STRING|MPZN|NUMCUR|NUMBER);
	} else
#endif
	{
		Nnull_string->numbr = 0.0;
		Nnull_string->flags = (MALLOC|STRCUR|STRING|NUMCUR|NUMBER);
	}

	/*
	 * Tell the regex routines how they should work.
	 * Do this before initializing variables, since
	 * they could want to do a regexp compile.
	 */
	resetup();

	/* Set up the special variables */
	init_vars();

	/* Set up the field variables */
	init_fields();

	/* Now process the pre-assignments */
	for (i = 0; i <= numassigns; i++) {
		if (preassigns[i].type == PRE_ASSIGN)
			(void) arg_assign(preassigns[i].val, true);
		else	/* PRE_ASSIGN_FS */
			cmdline_fs(preassigns[i].val);
		efree(preassigns[i].val);
	}

	if (preassigns != NULL)
		efree(preassigns);

	if ((BINMODE & BINMODE_INPUT) != 0)
		if (os_setbinmode(fileno(stdin), O_BINARY) == -1)
			fatal(_("can't set binary mode on stdin (%s)"), strerror(errno));
	if ((BINMODE & BINMODE_OUTPUT) != 0) {
		if (os_setbinmode(fileno(stdout), O_BINARY) == -1)
			fatal(_("can't set binary mode on stdout (%s)"), strerror(errno));
		if (os_setbinmode(fileno(stderr), O_BINARY) == -1)
			fatal(_("can't set binary mode on stderr (%s)"), strerror(errno));
	}

#ifdef GAWKDEBUG
	setbuf(stdout, (char *) NULL);	/* make debugging easier */
#endif
	if (os_isatty(fileno(stdout)))
		output_is_tty = true;

	/* initialize API before loading extension libraries */
	init_ext_api();

	/* load extension libs */
        for (s = srcfiles->next; s != srcfiles; s = s->next) {
                if (s->stype == SRC_EXTLIB)
			load_ext(s->fullpath);
		else if (s->stype != SRC_INC)
			have_srcfile++;
        }

	/* do version check after extensions are loaded to get extension info */
	if (do_version)
		version();

	/* No -f or --source options, use next arg */
	if (! have_srcfile) {
		if (optind > argc - 1 || stopped_early) /* no args left or no program */
			usage(EXIT_FAILURE, stderr);
		(void) add_srcfile(SRC_CMDLINE, argv[optind], srcfiles, NULL, NULL);
		optind++;
	}

	/* Select the interpreter routine */
	init_interpret();

	init_args(optind, argc,
			do_posix ? argv[0] : myname,
			argv);

#if defined(LC_NUMERIC)
	/*
	 * FRAGILE!  CAREFUL!
	 * Pre-initing the variables with arg_assign() can change the
	 * locale.  Force it to C before parsing the program.
	 */
	setlocale(LC_NUMERIC, "C");
#endif
	/* Read in the program */
	if (parse_program(& code_block) != 0)
		exit(EXIT_FAILURE);
	
	if (do_intl)
		exit(EXIT_SUCCESS);

	if (do_lint)
		shadow_funcs();

	if (do_lint && code_block->nexti->opcode == Op_atexit)
		lintwarn(_("no program text at all!"));

	load_symbols();

	if (do_profile)
		init_profiling_signals();

#if defined(LC_NUMERIC)
	/*
	 * See comment above about using locale's decimal point.
	 *
	 * 10/2005:
	 * Bitter experience teaches us that most people the world over
	 * use period as the decimal point, not whatever their locale
	 * uses.  Thus, only use the locale's decimal point if being
	 * posixly anal-retentive.
	 *
	 * 7/2007:
	 * Be a little bit kinder. Allow the --use-lc-numeric option
	 * to also use the local decimal point. This avoids the draconian
	 * strictness of POSIX mode if someone just wants to parse their
	 * data using the local decimal point.
	 */
	if (use_lc_numeric)
		setlocale(LC_NUMERIC, "");
#endif
	
	init_io();
	output_fp = stdout;

	if (do_debug)
		debug_prog(code_block);
	else if (do_pretty_print && ! do_profile)
		;	/* run pretty printer only. */
	else
		interpret(code_block);

	if (do_pretty_print) {
		dump_prog(code_block);
		dump_funcs();
	}

	if (do_dump_vars)
		dump_vars(varfile);

	if (do_tidy_mem)
		release_all_vars();
	
	/* keep valgrind happier */
	if (extra_stack)
		efree(extra_stack);

	final_exit(exit_val);
	return exit_val;	/* to suppress warnings */
}
Esempio n. 15
0
int
main( int argc, char **argv )
{
	int status, retval, num_tests = 1, tmp;
	int EventSet1 = PAPI_NULL;
	long long **values;
	long long elapsed_us, elapsed_cyc, elapsed_virt_us, elapsed_virt_cyc;
	char event_name[PAPI_MAX_STR_LEN];;
	const PAPI_hw_info_t *hw_info;
	const PAPI_component_info_t *cmpinfo;
	pid_t pid;

	/* Fork before doing anything with the PMU */

	setbuf(stdout,NULL);
	pid = fork(  );
	if ( pid < 0 )
		test_fail( __FILE__, __LINE__, "fork()", PAPI_ESYS );
	if ( pid == 0 )
		exit( wait_for_attach_and_loop(  ) );

	tests_quiet( argc, argv );	/* Set TESTS_QUIET variable */


	/* Master only process below here */

	retval = PAPI_library_init( PAPI_VER_CURRENT );
	if ( retval != PAPI_VER_CURRENT )
		test_fail_exit( __FILE__, __LINE__, "PAPI_library_init", retval );

	if ( ( cmpinfo = PAPI_get_component_info( 0 ) ) == NULL )
		test_fail_exit( __FILE__, __LINE__, "PAPI_get_component_info", 0 );

	if ( cmpinfo->attach == 0 )
		test_skip( __FILE__, __LINE__, "Platform does not support attaching",
				   0 );

	hw_info = PAPI_get_hardware_info(  );
	if ( hw_info == NULL )
		test_fail_exit( __FILE__, __LINE__, "PAPI_get_hardware_info", 0 );

	/* add PAPI_TOT_CYC and one of the events in PAPI_FP_INS, PAPI_FP_OPS or
	   PAPI_TOT_INS, depending on the availability of the event on the
	   platform */
	retval = PAPI_create_eventset(&EventSet1);
	if ( retval != PAPI_OK )
		test_fail_exit( __FILE__, __LINE__, "PAPI_attach", retval );

	/* Force addition of component */

	retval = PAPI_assign_eventset_component( EventSet1, 0 );
	if ( retval != PAPI_OK )
		test_fail( __FILE__, __LINE__, "PAPI_assign_eventset_component",
				   retval );

	/* The following call causes this test to fail for perf_events */

	retval = PAPI_attach( EventSet1, ( unsigned long ) pid );
	if ( retval != PAPI_OK )
		test_fail_exit( __FILE__, __LINE__, "PAPI_attach", retval );

	sprintf(event_name,"PAPI_TOT_CYC");

	retval = PAPI_add_event(EventSet1, PAPI_TOT_CYC);
	if ( retval != PAPI_OK )
		test_fail_exit( __FILE__, __LINE__, "PAPI_add_event", retval );
	retval = PAPI_add_event(EventSet1, PAPI_FP_INS);
	if ( retval == PAPI_ENOEVNT ) {
		test_warn( __FILE__, __LINE__, "PAPI_FP_INS", retval);
	} else if ( retval != PAPI_OK ) {
		test_fail_exit( __FILE__, __LINE__, "PAPI_add_event", retval );
	}
	
	values = allocate_test_space( 1, 2);

	elapsed_us = PAPI_get_real_usec(  );

	elapsed_cyc = PAPI_get_real_cyc(  );

	elapsed_virt_us = PAPI_get_virt_usec(  );

	elapsed_virt_cyc = PAPI_get_virt_cyc(  );

	printf("must_ptrace is %d\n",cmpinfo->attach_must_ptrace);
	pid_t  child = wait( &status );
	printf( "Debugger exited wait() with %d\n",child );
	  if (WIFSTOPPED( status ))
	    {
	      printf( "Child has stopped due to signal %d (%s)\n",
		      WSTOPSIG( status ), strsignal(WSTOPSIG( status )) );
	    }
	  if (WIFSIGNALED( status ))
	    {
	      printf( "Child %ld received signal %d (%s)\n",
		      (long)child,
		      WTERMSIG(status) , strsignal(WTERMSIG( status )) );
	    }
	printf("After %d\n",retval);

	retval = PAPI_start( EventSet1 );
	if ( retval != PAPI_OK )
		test_fail_exit( __FILE__, __LINE__, "PAPI_start", retval );

	printf("Continuing\n");
#if defined(__FreeBSD__)
	if ( ptrace( PT_CONTINUE, pid, (caddr_t) 1, 0 ) == -1 ) {
#else
	if ( ptrace( PTRACE_CONT, pid, NULL, NULL ) == -1 ) {
#endif
	  perror( "ptrace(PTRACE_CONT)" );
	  return 1;
	}


	do {
	  child = wait( &status );
	  printf( "Debugger exited wait() with %d\n", child);
	  if (WIFSTOPPED( status ))
	    {
	      printf( "Child has stopped due to signal %d (%s)\n",
		      WSTOPSIG( status ), strsignal(WSTOPSIG( status )) );
	    }
	  if (WIFSIGNALED( status ))
	    {
	      printf( "Child %ld received signal %d (%s)\n",
		      (long)child,
		      WTERMSIG(status) , strsignal(WTERMSIG( status )) );
	    }
	} while (!WIFEXITED( status ));

	printf("Child exited with value %d\n",WEXITSTATUS(status));
	if (WEXITSTATUS(status) != 0) 
	  test_fail_exit( __FILE__, __LINE__, "Exit status of child to attach to", PAPI_EMISC);

	retval = PAPI_stop( EventSet1, values[0] );
	if ( retval != PAPI_OK )
	  test_fail_exit( __FILE__, __LINE__, "PAPI_stop", retval );

	elapsed_virt_us = PAPI_get_virt_usec(  ) - elapsed_virt_us;

	elapsed_virt_cyc = PAPI_get_virt_cyc(  ) - elapsed_virt_cyc;

	elapsed_us = PAPI_get_real_usec(  ) - elapsed_us;

	elapsed_cyc = PAPI_get_real_cyc(  ) - elapsed_cyc;

	retval = PAPI_cleanup_eventset(EventSet1);
	if (retval != PAPI_OK)
	  test_fail_exit( __FILE__, __LINE__, "PAPI_cleanup_eventset", retval );

	retval = PAPI_destroy_eventset(&EventSet1);
	if (retval != PAPI_OK)
	  test_fail_exit( __FILE__, __LINE__, "PAPI_destroy_eventset", retval );

	printf( "Test case: 3rd party attach start, stop.\n" );
	printf( "-----------------------------------------------\n" );
	tmp = PAPI_get_opt( PAPI_DEFDOM, NULL );
	printf( "Default domain is: %d (%s)\n", tmp, stringify_all_domains( tmp ) );
	tmp = PAPI_get_opt( PAPI_DEFGRN, NULL );
	printf( "Default granularity is: %d (%s)\n", tmp,
			stringify_granularity( tmp ) );
	printf( "Using %d iterations of c += a*b\n", NUM_FLOPS );
	printf
		( "-------------------------------------------------------------------------\n" );

	printf( "Test type    : \t           1\n" );

	printf( TAB1, "PAPI_TOT_CYC : \t", ( values[0] )[0] );
	printf( TAB1, "PAPI_FP_INS  : \t", ( values[0] )[1] );
	printf( TAB1, "Real usec    : \t", elapsed_us );
	printf( TAB1, "Real cycles  : \t", elapsed_cyc );
	printf( TAB1, "Virt usec    : \t", elapsed_virt_us );
	printf( TAB1, "Virt cycles  : \t", elapsed_virt_cyc );

	printf
		( "-------------------------------------------------------------------------\n" );

	printf( "Verification: none\n" );

	test_pass( __FILE__, values, num_tests );
	exit( 1 );
}
Esempio n. 16
0
int
main(int argc, char *argv[])
{
	LOGINREC *login;
	DBPROCESS *dbproc;
	int i;
	RETCODE ret;
	int big_endian = 1;

	char *out_file = "t0017.out";
	static const char in_file_le[] = FREETDS_SRCDIR "/t0017.in";
	static const char in_file_be[] = FREETDS_SRCDIR "/t0017.in.be";
	const char *in_file = in_file_le;
	const char *err_file = "t0017.err";
	DBINT rows_copied;
	int num_cols = 0;
	int col_type[256];
	DBBOOL col_varylen[256];
	int prefix_len;

	if (((char *) &big_endian)[0] == 1)
		big_endian = 0;
	if (big_endian)
		in_file = in_file_be;

	setbuf(stdout, NULL);
	setbuf(stderr, NULL);

	set_malloc_options();

	read_login_info(argc, argv);
	printf("Starting %s\n", software_version);
	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	printf("About to logon ... ");

	login = dblogin();
	assert(login);
	BCP_SETL(login, TRUE);
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "t0017");
	printf("done\n");

	printf("Opening \"%s\" for \"%s\" ... ", SERVER, USER);
	dbproc = dbopen(login, SERVER);
	assert(dbproc);
	if (strlen(DATABASE)) {
		dbuse(dbproc, DATABASE);
	}
	dbloginfree(login);
	printf("done\n");

	printf("Creating table ... ");
	dbcmd(dbproc, "create table #dblib0017 (c1 int null, c2 text)");
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}
	printf("done\n");

	dbcmd(dbproc, "insert into #dblib0017(c1,c2) values(1144201745,'prova di testo questo testo dovrebbe andare a finire in un campo text')");
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	/* BCP out */
	printf("bcp_init... ");
	ret = bcp_init(dbproc, "#dblib0017", out_file, err_file, DB_OUT);
	if (ret != SUCCEED)
		failed = 1;
	printf("done\n");

	printf("Issuing SELECT ... ");
	dbcmd(dbproc, "select * from #dblib0017 where 0=1");
	dbsqlexec(dbproc);
	printf("done\nFetching metadata ... ");
	if (dbresults(dbproc) != FAIL) {
		num_cols = dbnumcols(dbproc);
		for (i = 0; i < num_cols; ++i) {
			col_type[i] = dbcoltype(dbproc, i + 1);
			col_varylen[i] = dbvarylen(dbproc, i + 1);
		}
		while (dbnextrow(dbproc) != NO_MORE_ROWS) {
		}
	}
	printf("done\n");

	printf("bcp_columns ... ");
	ret = bcp_columns(dbproc, num_cols);
	if (ret != SUCCEED)
		failed = 1;
	for (i = 0; i < num_cols; i++) {
		prefix_len = 0;
		if (col_type[i] == SYBIMAGE || col_type[i] == SYBTEXT) {
			prefix_len = 4;
		} else if (col_varylen[i]) {
			prefix_len = 1;
		}
		printf("bind %d prefix %d col_type %s\n", i, prefix_len, col_type[i] == SYBIMAGE ? "image" : "other");
		ret = bcp_colfmt(dbproc, i + 1, col_type[i], prefix_len, -1, NULL, 0, i + 1);
		if (ret == FAIL) {
			fprintf(stderr, "return from bcp_colfmt = %d\n", ret);
			failed = 1;
		}
	}
	printf("done\n");

	rows_copied = -1;
	printf("bcp_exec ... ");
	ret = bcp_exec(dbproc, &rows_copied);
	if (ret != SUCCEED || rows_copied != 1)
		failed = 1;

	printf("%d rows copied\n", rows_copied);

	/* delete rows */
	dbcmd(dbproc, "delete from #dblib0017");
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	/* 
	 * BCP in 
	 */
	printf("bcp_init... ");
	ret = bcp_init(dbproc, "#dblib0017", in_file, err_file, DB_IN);
	if (ret != SUCCEED)
		failed = 1;
	printf("done\n");

	printf("Issuing SELECT ... ");
	dbcmd(dbproc, "select * from #dblib0017 where 0=1");
	dbsqlexec(dbproc);
	printf("done\nFetching metadata ... ");
	if (dbresults(dbproc) != FAIL) {
		num_cols = dbnumcols(dbproc);
		for (i = 0; i < num_cols; i++) {
			col_type[i] = dbcoltype(dbproc, i + 1);
			col_varylen[i] = dbvarylen(dbproc, i + 1);
		}
		while (dbnextrow(dbproc) != NO_MORE_ROWS) {
		}
	}
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}
	printf("done\n");

	printf("bcp_columns ... ");
	ret = bcp_columns(dbproc, num_cols);
	if (ret != SUCCEED)
		failed = 1;
	for (i = 0; i < num_cols; i++) {
		prefix_len = 0;
		if (col_type[i] == SYBIMAGE || col_type[i] == SYBTEXT) {
			prefix_len = 4;
		} else if (col_varylen[i]) {
			prefix_len = 1;
		}
		ret = bcp_colfmt(dbproc, i + 1, col_type[i], prefix_len, -1, NULL, 0, i + 1);
		if (ret == FAIL) {
			fprintf(stderr, "return from bcp_colfmt = %d\n", ret);
			failed = 1;
		}
	}
	printf("done\n");

	printf("bcp_exec ... ");
	rows_copied = -1;
	ret = bcp_exec(dbproc, &rows_copied);
	if (ret != SUCCEED || rows_copied != 1)
		failed = 1;
	printf("done\n");


	/* test we inserted correctly row */
	if (!failed) {
		dbcmd(dbproc, "SET NOCOUNT ON DECLARE @n INT SELECT @n = COUNT(*) FROM #dblib0017 WHERE c1=1144201745 AND c2 LIKE 'prova di testo questo testo dovrebbe andare a finire in un campo text' IF @n <> 1 SELECT 0");
		dbsqlexec(dbproc);
		while (dbresults(dbproc) != NO_MORE_RESULTS) {
			while ((ret=dbnextrow(dbproc)) != NO_MORE_ROWS) {
				fprintf(stderr, "Invalid dbnextrow result %d executing query\n", ret);
				failed = 1;
			}
		}
	}

	printf("%d rows copied\n", rows_copied);
	dbclose(dbproc);
	dbexit();

	printf("dblib %s on %s\n", (failed ? "failed!" : "okay"), __FILE__);
	return failed ? 1 : 0;
}
int main (int argc, char **argv)
{
	cups_file_t	*fp_input =  NULL;			/* input file: stdin or physical file */	
    char   line[LINE_SIZE] = {0};
	
	get_LogLevel();
	setbuf (stderr, NULL);
	fprintf (stderr, "HP PS filter starting : %s \n", *argv);
	
	int i =  0;
	/* Logging cups filter arguments */
	for (   i = 0; i < argc; i++)
	{
		fprintf (stderr, "DEBUG: hppsfilter: argv[%d] = %s\n", i, argv[i]);
	}
	
	/* Logging debug information and creating outfile for debug */
	if (g_savepsfile & SAVE_PS_FILE)
	{
		/* opening ps debug file */
		open_dbg_outfile(argv[1]);
	}
	
	/* Check command-line...  */
	if (argc < 6 || argc > 7)
	{
		fputs("ERROR: hppsfilter job-id user title copies options [file]\n", stderr);
		return (1);
	}

	/* If we have 7 arguments, print the file named on the command-line.
	* Otherwise, send stdin instead...  */
	if (argc == 6)
		fp_input = cupsFileStdin();
	else
	{
		/* Try to open the print file...    */
		if ((fp_input = cupsFileOpen(argv[6], "r")) == NULL)
		{
  			fprintf(stderr, "ERROR: Unable to open print file \"%s\" - %s\n",
              argv[6], strerror);
  			return (1);
		}
	}

	int len  =  0;
	int ibodwritten = 0;
	int ireqire_bod = require_bod();
    while ( ( len = cupsFileGetLine(fp_input, line, sizeof(line) )) > 0)
    {
		hpwrite (line, len);
		/* if BOD is reqire, writting BOD command */
		if ( !ibodwritten && (!strncmp(line, "@PJL JOB NAME", 13)) && ireqire_bod)
		{
			fprintf (stderr, "HP PS filter: Matched start PJL\n");				
			ibodwritten = 1;
			emmit_bod_command();
		}
    }

    if ( (argc == 7) && (fp_input != NULL) )
        cupsFileClose (fp_input);
	
	if(g_fp_outdbgps != NULL)
	{
	    fclose (g_fp_outdbgps);		
	}
			   
	fprintf (stderr, "HP PS filter Ends\n");	
    return 0;
}
Esempio n. 18
0
/* Function for accepting password input from users
*/
char*
getpasswd(const char *prompt)
{
    static char     pwbuf[MAX_PASS_LEN + 1] = {0};
    char           *ptr;    
    int             c;

#ifndef WIN32
    FILE           *fp;
	sigset_t        sig, old_sig;
    struct termios  ts, old_ts;

    if((fp = fopen(ctermid(NULL), "r+")) == NULL)
        return(NULL);

    setbuf(fp, NULL);

    /* Setup blocks for SIGINT and SIGTSTP and save the original signal
     * mask.
    */
    sigemptyset(&sig);
    sigaddset(&sig, SIGINT);
    sigaddset(&sig, SIGTSTP);
    sigprocmask(SIG_BLOCK, &sig, &old_sig);

    /* Save current tty state for later restoration after we disable echo
     * of characters to the tty.
    */
    tcgetattr(fileno(fp), &ts);
    old_ts = ts;
    ts.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
    tcsetattr(fileno(fp), TCSAFLUSH, &ts);

    fputs(prompt, fp);
#endif

    /* Read in the password.
    */
    ptr = pwbuf;
#ifdef WIN32
	_cputs(prompt);
    while((c = _getch()) != '\r')
	{
		/* Handle a backspace without backing up too far.
		*/
		if(c == '\b')
		{
			if(ptr != pwbuf)
				*ptr--;

			continue;
		}

		/* Handle a Ctrl-U to clear the password entry and start over
		 * (like it works under Unix).
	    */
		if(c == 0x15)
		{
			ptr = pwbuf;
			continue;
		}
#else
	while((c = getc(fp)) != EOF && c != '\n')
	{
#endif
        if(ptr < &pwbuf[MAX_PASS_LEN])
            *ptr++ = c;
	}

	/* Null terminate the password.
    */
    *ptr = 0;

#ifndef WIN32
    /* we can go ahead and echo out a newline.
    */
    putc('\n', fp);

	/* Restore our tty state and signal handlers.
    */
    tcsetattr(fileno(fp), TCSAFLUSH, &old_ts);
    sigprocmask(SIG_BLOCK, &old_sig, NULL);

    fclose(fp);
#else
	/* In Windows, it would be a CR-LF
	*/
	_putch('\r');
	_putch('\n');
#endif

    return(pwbuf);
}

/* Function for accepting password input from from a file
*/
char*
getpasswd_file(const char *pw_file, const char *server_str)
{
    FILE           *pwfile_ptr;
    unsigned int    numLines = 0, i = 0, found_dst;

    static char     pwbuf[MAX_PASS_LEN + 1]     = {0};
    char            conf_line_buf[MAX_LINE_LEN] = {0};
    char            tmp_char_buf[MAX_LINE_LEN]  = {0};
    char           *lptr;

    if ((pwfile_ptr = fopen(pw_file, "r")) == NULL)
    {
        fprintf(stderr, "Could not open config file: %s\n", pw_file);
        exit(1);
    }

    while ((fgets(conf_line_buf, MAX_LINE_LEN, pwfile_ptr)) != NULL)
    {
        numLines++;
        conf_line_buf[MAX_LINE_LEN-1] = '\0';
        lptr = conf_line_buf;

        memset(tmp_char_buf, 0x0, MAX_LINE_LEN);

        while (*lptr == ' ' || *lptr == '\t' || *lptr == '=')
            lptr++;

        /* Get past comments and empty lines.
        */
        if (*lptr == '#' || *lptr == '\n' || *lptr == '\r' || *lptr == '\0' || *lptr == ';')
            continue;

        /* Look for a line like "<SPA destination IP>: <password>" - this allows
        * multiple keys to be placed within the same file, and the client will
        * reference the matching one for the SPA server we are contacting
        */
        found_dst = 1;
        for (i=0; i < strlen(server_str); i++)
            if (*lptr++ != server_str[i])
                found_dst = 0;

        if (! found_dst)
            continue;

        if (*lptr == ':')
            lptr++;
        else
            continue;

        /* Skip whitespace until we get to the password
        */
        while (*lptr == ' ' || *lptr == '\t' || *lptr == '=')
            lptr++;

        i = 0;
        while (*lptr != '\0' && *lptr != '\n') {
            pwbuf[i] = *lptr;
            lptr++;
            i++;
        }
        pwbuf[i] = '\0';
    }

    fclose(pwfile_ptr);

    if (pwbuf[0] == '\0') {
        fprintf(stderr, "Could not get password for IP: %s from: %s\n",
            server_str, pw_file);
        exit(1);
    }

    return pwbuf;
}
Esempio n. 19
0
int					/* O - Exit code */
main(int  argc,				/* I - Number of command-line args */
     char *argv[])			/* I - Command-line arguments */
{
    int		i;			/* Looping var */
    int		request_id;		/* Request ID */
    int		timeout;		/* Timeout in seconds */
    const char	*server_bin;		/* CUPS_SERVERBIN environment variable */
    char		filename[1024];		/* Backend directory filename */
    cups_dir_t	*dir;			/* Directory pointer */
    cups_dentry_t *dent;			/* Directory entry */
    double	current_time,		/* Current time */
            end_time;		/* Ending time */
    int		num_options;		/* Number of options */
    cups_option_t	*options;		/* Options */
    cups_array_t	*requested,		/* requested-attributes values */
                    *exclude,		/* exclude-schemes values */
                    *include;		/* include-schemes values */
#if defined(HAVE_SIGACTION) && !defined(HAVE_SIGSET)
    struct sigaction action;		/* Actions for POSIX signals */
#endif /* HAVE_SIGACTION && !HAVE_SIGSET */


    setbuf(stderr, NULL);

    /*
     * Check the command-line...
     */

    if (argc != 6)
    {
        fputs("Usage: cups-deviced request-id limit timeout user-id options\n", stderr);

        return (1);
    }

    request_id = atoi(argv[1]);
    if (request_id < 1)
    {
        fprintf(stderr, "ERROR: [cups-deviced] Bad request ID %d!\n", request_id);

        return (1);
    }

    device_limit = atoi(argv[2]);
    if (device_limit < 0)
    {
        fprintf(stderr, "ERROR: [cups-deviced] Bad limit %d!\n", device_limit);

        return (1);
    }

    timeout = atoi(argv[3]);
    if (timeout < 1)
    {
        fprintf(stderr, "ERROR: [cups-deviced] Bad timeout %d!\n", timeout);

        return (1);
    }

    normal_user = (uid_t)atoi(argv[4]);
    if (normal_user <= 0)
    {
        fprintf(stderr, "ERROR: [cups-deviced] Bad user %d!\n", normal_user);

        return (1);
    }

    num_options = cupsParseOptions(argv[5], 0, &options);
    requested   = cupsdCreateStringsArray(cupsGetOption("requested-attributes",
                                          num_options, options));
    exclude     = cupsdCreateStringsArray(cupsGetOption("exclude-schemes",
                                          num_options, options));
    include     = cupsdCreateStringsArray(cupsGetOption("include-schemes",
                                          num_options, options));

    if (!requested || cupsArrayFind(requested, "all") != NULL)
    {
        send_class = send_info = send_make_and_model = send_uri = send_id =
                                     send_location = 1;
    }
    else
    {
        send_class          = cupsArrayFind(requested, "device-class") != NULL;
        send_info           = cupsArrayFind(requested, "device-info") != NULL;
        send_make_and_model = cupsArrayFind(requested, "device-make-and-model") != NULL;
        send_uri            = cupsArrayFind(requested, "device-uri") != NULL;
        send_id             = cupsArrayFind(requested, "device-id") != NULL;
        send_location       = cupsArrayFind(requested, "device-location") != NULL;
    }

    /*
     * Listen to child signals...
     */

#ifdef HAVE_SIGSET /* Use System V signals over POSIX to avoid bugs */
    sigset(SIGCHLD, sigchld_handler);
#elif defined(HAVE_SIGACTION)
    memset(&action, 0, sizeof(action));

    sigemptyset(&action.sa_mask);
    sigaddset(&action.sa_mask, SIGCHLD);
    action.sa_handler = sigchld_handler;
    sigaction(SIGCHLD, &action, NULL);
#else
    signal(SIGCLD, sigchld_handler);	/* No, SIGCLD isn't a typo... */
#endif /* HAVE_SIGSET */

    /*
     * Try opening the backend directory...
     */

    if ((server_bin = getenv("CUPS_SERVERBIN")) == NULL)
        server_bin = CUPS_SERVERBIN;

    snprintf(filename, sizeof(filename), "%s/backend", server_bin);

    if ((dir = cupsDirOpen(filename)) == NULL)
    {
        fprintf(stderr, "ERROR: [cups-deviced] Unable to open backend directory "
                "\"%s\": %s", filename, strerror(errno));

        return (1);
    }

    /*
     * Setup the devices array...
     */

    devices = cupsArrayNew((cups_array_func_t)compare_devices, NULL);

    /*
     * Loop through all of the device backends...
     */

    while ((dent = cupsDirRead(dir)) != NULL)
    {
        /*
         * Skip entries that are not executable files...
         */

        if (!S_ISREG(dent->fileinfo.st_mode) ||
                !isalnum(dent->filename[0] & 255) ||
                (dent->fileinfo.st_mode & (S_IRUSR | S_IXUSR)) != (S_IRUSR | S_IXUSR))
            continue;

        /*
         * Skip excluded or not included backends...
         */

        if (cupsArrayFind(exclude, dent->filename) ||
                (include && !cupsArrayFind(include, dent->filename)))
            continue;

        /*
         * Backends without permissions for normal users run as root,
         * all others run as the unprivileged user...
         */

        start_backend(dent->filename, !(dent->fileinfo.st_mode & (S_IWGRP | S_IRWXO)));
    }

    cupsDirClose(dir);

    /*
     * Collect devices...
     */

    if (getenv("SOFTWARE"))
        puts("Content-Type: application/ipp\n");

    cupsdSendIPPHeader(IPP_OK, request_id);
    cupsdSendIPPGroup(IPP_TAG_OPERATION);
    cupsdSendIPPString(IPP_TAG_CHARSET, "attributes-charset", "utf-8");
    cupsdSendIPPString(IPP_TAG_LANGUAGE, "attributes-natural-language", "en-US");

    end_time = get_current_time() + timeout;

    while (active_backends > 0 && (current_time = get_current_time()) < end_time)
    {
        /*
         * Collect the output from the backends...
         */

        timeout = (int)(1000 * (end_time - current_time));

        if (poll(backend_fds, (nfds_t)num_backends, timeout) > 0)
        {
            for (i = 0; i < num_backends; i ++)
                if (backend_fds[i].revents && backends[i].pipe)
                {
                    cups_file_t *bpipe = backends[i].pipe;
                    /* Copy of pipe for backend... */

                    do
                    {
                        if (get_device(backends + i))
                        {
                            backend_fds[i].fd     = 0;
                            backend_fds[i].events = 0;
                            break;
                        }
                    }
                    while (bpipe->ptr && memchr(bpipe->ptr, '\n', (size_t)(bpipe->end - bpipe->ptr)));
                }
        }

        /*
         * Get exit status from children...
         */

        if (dead_children)
            process_children();
    }

    cupsdSendIPPTrailer();

    /*
     * Terminate any remaining backends and exit...
     */

    if (active_backends > 0)
    {
        for (i = 0; i < num_backends; i ++)
            if (backends[i].pid)
                kill(backends[i].pid, SIGTERM);
    }

    return (0);
}
Esempio n. 20
0
int main (int argc, char *argv[]) {

  char input[STR_BUFF], *p, output[STR_BUFF];
  char readbuff[STR_BUFF];
  move_s move, comp_move;
  int depth = 4;
  bool force_mode, show_board;
  double nps, elapsed;
  clock_t cpu_start, cpu_end;
  move_s game_history[600];
  move_x game_history_x[600];
  int is_edit_mode, edit_color;
  int confirm_moves;
  int pingnum;
  int braindeadinterface;
  int automode;
  rtime_t xstart_time;

  read_rcfile();
  initialize_zobrist();
 
  Variant = Normal;
  //Variant = Crazyhouse;

  memcpy(material, std_material, sizeof(std_material));
  //memcpy(material, zh_material, sizeof(zh_material));

  if (!init_book())
    printf("No .OPN opening book found.\n");

  lrn_standard = learn_open("standard", "standard");
  lrn_zh	   = learn_open("crazyhouse", "bug");
  lrn_suicide  = learn_open("suicide", "suicide");
  lrn_losers   = learn_open("losers", "losers");

  start_up ();
  init_game ();

  initialize_hash();
  clear_tt();
  reset_ecache();
  
  if (init_segtb())
    SEGTB = TRUE;
  else
    SEGTB = FALSE;
  
  EGTBProbes = 0;
  EGTBHits = 0;
  ECacheProbes = 0;
  ECacheHits = 0;
  TTProbes = 0;
  TTStores = 0;
  TTHits = 0;
  bookidx = 0;
  total_moves = 0;
  ply = 0;
  braindeadinterface = 0;
  moves_to_tc = 40;
  min_per_game = 5;
  time_left = 30000;
  my_rating = opp_rating = 2000;
  maxdepth = 40;
  must_go = 1;
  tradefreely = 1;
  automode = 0;
 
  xb_mode = FALSE;
  force_mode = FALSE;
  comp_color = 0;
  show_board = TRUE;
  is_pondering = FALSE;
  allow_pondering = TRUE;
  is_analyzing = FALSE;
  is_edit_mode = FALSE;
  have_partner = FALSE;
  must_sit = FALSE;
  go_fast = FALSE;
  fixed_time = FALSE;
  phase = Opening;
  root_to_move = WHITE;
  kibitzed = FALSE;
  confirm_moves = FALSE;

  move_number = 0;
  memset(game_history, 0, sizeof(game_history));
  memset(game_history_x, 0, sizeof(game_history_x));

  hash_history[move_number] = hash;
  
  setbuf (stdout, NULL);
  setbuf (stdin, NULL);

  /* keep looping for input, and responding to it: */
  while (TRUE) {

    /* case where it's the computer's turn to move: */
    if (!is_edit_mode && (comp_color == white_to_move || automode) 
	&& !force_mode && !must_sit && !result) {

      /* whatever happens, never allow pondering in normal search */
      is_pondering = FALSE;
  
      cpu_start = clock ();
      comp_move = think ();
      cpu_end = clock();

      ply = 0;

      /* must_sit can be changed by search */
      if (!must_sit || must_go != 0)
	{
	  /* check for a game end: */
	  if ((
	      ((Variant == Losers || Variant == Suicide)
	        && 
	      ((result != white_is_mated) && (result != black_is_mated)))
	      || 
	      ((Variant == Normal || Variant == Crazyhouse || Variant == Bughouse)
	      && ((comp_color == 1 && result != white_is_mated) 
	         ||
	         (comp_color == 0 && result != black_is_mated)
	        ))) 
	      && result != stalemate 
	      && result != draw_by_fifty 
	      && result != draw_by_rep) 
	  {
	    
	    comp_to_coord (comp_move, output);
	   
	    hash_history[move_number] = hash;
	    
	    game_history[move_number] = comp_move;
	    make (&comp_move, 0);
	   
	    /* saves state info */
	    game_history_x[move_number++] = path_x[0];
	    
	    userealholdings = 0;
	    must_go--;
	    
            /* check to see if we draw by rep/fifty after our move: */
	    if (is_draw ()) {
	    	result = draw_by_rep;
	    }
	    else if (fifty > 100) {
	        result = draw_by_fifty;
	    }
	    
	    root_to_move ^= 1;

	    reset_piece_square ();
	    
	    if (book_ply < 40) {
	      if (!book_ply) {
		strcpy(opening_history, output);
	      }
	      else {
		strcat(opening_history, output);
	      }
	    }
	    
	    book_ply++;
	    
	    printf ("\nNodes: %d (%0.2f%% qnodes)\n", nodes,
		    (float) ((float) qnodes / (float) nodes * 100.0));
	    
	    elapsed = (cpu_end-cpu_start)/(double) CLOCKS_PER_SEC;
	    nps = (float) nodes/(float) elapsed;
	    
	    if (!elapsed)
	      printf ("NPS: N/A\n");
	    else
	      printf ("NPS: %d\n", (int32_t) nps);
	    
	    printf("ECacheProbes : %d   ECacheHits : %d   HitRate : %f%%\n", 
		   ECacheProbes, ECacheHits, 
		   ((float)ECacheHits/((float)ECacheProbes+1)) * 100);
	    
	    printf("TTStores : %d TTProbes : %d   TTHits : %d   HitRate : %f%%\n", 
		   TTStores, TTProbes, TTHits, 
		   ((float)TTHits/((float)TTProbes+1)) * 100);
	    
	    printf("NTries : %d  NCuts : %d  CutRate : %f%%  TExt: %d\n", 
		   NTries, NCuts, (((float)NCuts*100)/((float)NTries+1)), TExt);
	    
	    printf("Check extensions: %d  Razor drops : %d  Razor Material : %d\n", ext_check, razor_drop, razor_material);

            printf("EGTB Hits: %d  EGTB Probes: %d  Efficiency: %3.1f%%\n", EGTBHits, EGTBProbes,
		(((float)EGTBHits*100)/(float)(EGTBProbes+1)));
	    
	    printf("Move ordering : %f%%\n", (((float)FHF*100)/(float)(FH+1)));
	    
	    printf("Material score: %d   Eval : %d  White hand: %d  Black hand : %d\n", 
		   Material, (int)eval(), white_hand_eval, black_hand_eval);
	    
	    printf("Hash : %X  HoldHash : %X\n", (unsigned)hash, (unsigned)hold_hash);

	    /* check to see if we mate our opponent with our current move: */
	    if (!result) {
	      if (xb_mode) {

		/* safety in place here */
		if (comp_move.from != dummy.from || comp_move.target != dummy.target)
		    printf ("move %s\n", output);

		if (Variant == Bughouse)
		  {
		    CheckBadFlow(FALSE);
		  }	
	      }
	      else {
		if (comp_move.from != dummy.from || comp_move.target != dummy.target)
		printf ("\n%s\n", output);
      	      }
	    }
	    else {
	      if (xb_mode) {
		if (comp_move.from != dummy.from || comp_move.target != dummy.target)
		    printf ("move %s\n", output);
	      }
	      else {
		if (comp_move.from != dummy.from || comp_move.target != dummy.target)
		printf ("\n%s\n", output);
	      }
	      if (result == white_is_mated) {
		printf ("0-1 {Black Mates}\n");
	      }
	      else if (result == black_is_mated) {
		printf ("1-0 {White Mates}\n");
	      }
	      else if (result == draw_by_fifty) {
	        printf ("1/2-1/2 {Fifty move rule}\n");
	      }
	      else if (result == draw_by_rep) {
	        printf ("1/2-1/2 {3 fold repetition}\n");
	      }
	      else {
		printf ("1/2-1/2 {Draw}\n");
	      }
	      automode = 0;
	    }
	  }
	  /* we have been mated or stalemated: */
	  else {
	    if (result == white_is_mated) {
	      printf ("0-1 {Black Mates}\n");
	    }
	    else if (result == black_is_mated) {
	      printf ("1-0 {White Mates}\n");
	    }
            else if (result == draw_by_fifty) {
	      printf ("1/2-1/2 {Fifty move rule}\n");
	    }
	    else if (result == draw_by_rep) {
	      printf ("1/2-1/2 {3 fold repetition}\n");
	    }
	    else {
	      printf ("1/2-1/2 {Draw}\n");
	    }
	    automode = 0;
	  }
	}
    }

    /* get our input: */
    if (!xb_mode) {
      if (show_board) {
	printf ("\n");
	display_board (stdout, 1-comp_color);
      }
      if (!automode)
      {
      	printf ("Sjeng: ");
      	rinput (input, STR_BUFF, stdin);
      }
    }
    else {
      /* start pondering */

      if ((must_sit || (allow_pondering && !is_edit_mode && !force_mode &&
	      move_number != 0) || is_analyzing) && !result && !automode)
	{
	  is_pondering = TRUE;
	  think();
	  is_pondering = FALSE;

	  ply = 0;
	}
      if (!automode)
      {
      	rinput (input, STR_BUFF, stdin);
      }
    }

    /* check to see if we have a move.  If it's legal, play it. */
    if (!is_edit_mode && is_move (&input[0])) {
      if (verify_coord (input, &move)) {
	
	if (confirm_moves) printf ("Legal move: %s\n", input);

	game_history[move_number] = move;
	hash_history[move_number] = hash;
	
        make (&move, 0);
	game_history_x[move_number++] = path_x[0];
	
	reset_piece_square ();
	
	root_to_move ^= 1;
	
	if (book_ply < 40) {
	  if (!book_ply) {
	    strcpy(opening_history, input);
	  }
	  else {
	    strcat(opening_history, input);
	  }
        }
	
	book_ply++;
	
	if (show_board) {
	  printf ("\n");
	  display_board (stdout, 1-comp_color);
	}
      }
      else {
	printf ("Illegal move: %s\n", input);
	}
    }
    else {

      /* make everything lower case for convenience: */
      /* GCP: except for setboard, which is case sensitive */
      if (!strstr(input, "setboard"))
      	for (p = input; *p; p++) *p = tolower (*p);

      /* command parsing: */
      if (!strcmp (input, "quit") || (!input[0] && feof(stdin))) {
	safe_fclose(lrn_standard);
	safe_fclose(lrn_zh);
	safe_fclose(lrn_suicide);
	safe_fclose(lrn_losers);
	free_hash();
	free_ecache();
	exit (EXIT_SUCCESS);
      }
      else if (!strcmp (input, "exit"))
	{
	  if (is_analyzing)
	    {
	      is_analyzing = FALSE;
	      is_pondering = FALSE;
	      time_for_move = 0;
	    }
	  else
	    {
	      safe_fclose(lrn_standard);
	      safe_fclose(lrn_zh);
	      safe_fclose(lrn_suicide);
	      safe_fclose(lrn_losers);
	      free_hash();
	      free_ecache();
	      exit (EXIT_SUCCESS);
	    }
	}
      else if (!strcmp (input, "diagram") || !strcmp (input, "d")) {
	toggle_bool (&show_board);
      }
      else if (!strncmp (input, "perft", 5)) {
	sscanf (input+6, "%d", &depth);
	raw_nodes = 0;
	xstart_time = rtime();
	perft (depth);
	printf ("Raw nodes for depth %d: %d\n", depth, raw_nodes);
	printf("Time : %.2f\n", (float)rdifftime(rtime(), xstart_time)/100.);
      }
	  else if (!strcmp (input, "confirm_moves")) {
		  confirm_moves = TRUE;
		  printf("Will now confirm moves.\n");
	  }
      else if (!strcmp (input, "new")) {

	if (xb_mode)
	  {
	    printf("tellics set 1 Sjeng " VERSION " (2001-9-28/%s)\n", setcode);
	  }

	if (!is_analyzing)
	{	
	  memcpy(material, std_material, sizeof(std_material));
	  Variant = Normal;

	 // memcpy(material, zh_material, sizeof(zh_material));
	  //Variant = Crazyhouse;
	    
	  init_game ();
	  initialize_hash();

	  if (!braindeadinterface)
	  {
	    clear_tt();
	    init_book();
	    reset_ecache();
	  }
  
	  force_mode = FALSE;
	  must_sit = FALSE;
	  go_fast = FALSE;
	  piecedead = FALSE;
	  partnerdead = FALSE;
	  kibitzed = FALSE;
	  fixed_time = FALSE;

	  root_to_move = WHITE;
  
	  comp_color = 0;
	  move_number = 0;
	  hash_history[move_number] = 0;
	  bookidx = 0;
	  my_rating = opp_rating = 2000;
          must_go = 0;
	  tradefreely = 1;
	  automode = 0;
	  
	  CheckBadFlow(TRUE);
	  ResetHandValue();
	}
	else
	{
	  init_game ();
	  move_number = 0;
	}
	
      }
      else if (!strcmp (input, "xboard")) {
	xb_mode = TRUE;
	toggle_bool (&show_board);
	signal (SIGINT, SIG_IGN);
	printf ("\n");
	
	/* Reset f5 in case we left with partner */
	printf("tellics set f5 1=1\n");
	
	BegForPartner();
      }
      else if (!strcmp (input, "nodes")) {
	printf ("Number of nodes: %d (%0.2f%% qnodes)\n", nodes,
		(float) ((float) qnodes / (float) nodes * 100.0));
      }
      else if (!strcmp (input, "nps")) {
	elapsed = (cpu_end-cpu_start)/(double) CLOCKS_PER_SEC;
	nps = (float) nodes/(float) elapsed;
	if (!elapsed)
	  printf ("NPS: N/A\n");
	else
	  printf ("NPS: %d\n", (int32_t) nps);
      }
      else if (!strcmp (input, "post")) {
	toggle_bool (&post);
	if (xb_mode)
	  post = TRUE;
      }
      else if (!strcmp (input, "nopost")) {
	post = FALSE;
      }
      else if (!strcmp (input, "random")) {
	continue;
      }
      else if (!strcmp (input, "hard")) {

	allow_pondering = TRUE;

	continue;
      }
      else if (!strcmp (input, "easy")) {

	allow_pondering = FALSE;

	continue;
      }
      else if (!strcmp (input, "?")) {
	continue;
      }
      else if (!strcmp (input, "white")) {
	white_to_move = 1;
	root_to_move = WHITE;
	comp_color = 0;
      }
      else if (!strcmp (input, "black")) {
	white_to_move = 0;
	root_to_move = BLACK;
	comp_color = 1;
      }
      else if (!strcmp (input, "force")) {
	force_mode = TRUE;
      }
      else if (!strcmp (input, "eval")) {
	check_phase();
	printf("Eval: %d\n", (int)eval());
      }
      else if (!strcmp (input, "go")) {
	comp_color = white_to_move;
	force_mode = FALSE;
      }
      else if (!strncmp (input, "time", 4)) {
	sscanf (input+5, "%d", &time_left);
      }
      else if (!strncmp (input, "otim", 4)) {
	sscanf (input+5, "%d", &opp_time);
      }
      else if (!strncmp (input, "level", 5)) {
         if (strstr(input+6, ":"))
	 {
	   /* time command with seconds */
	   sscanf (input+6, "%d %d:%d %d", &moves_to_tc, &min_per_game, 
		   &sec_per_game, &inc);
	   time_left = (min_per_game*6000) + (sec_per_game * 100);
	   opp_time = time_left;
	 }
	 else
	   {
	     /* extract the time controls: */
	     sscanf (input+6, "%d %d %d", &moves_to_tc, &min_per_game, &inc);
	     time_left = min_per_game*6000;
	     opp_time = time_left;
	   }
	 fixed_time = FALSE;
	 time_cushion = 0; 
      }
      else if (!strncmp (input, "rating", 6)) {
	sscanf (input+7, "%d %d", &my_rating, &opp_rating);
	if (my_rating == 0) my_rating = 2000;
	if (opp_rating == 0) opp_rating = 2000;
      }
      else if (!strncmp (input, "holding", 7)) {
	ProcessHoldings(input);     
      }
      else if (!strncmp (input, "variant", 7)) {
	if (strstr(input, "normal"))
	  {
	    Variant = Normal;
	    memcpy(material, std_material, sizeof(std_material));
	    init_book();
	  }
	else if (strstr(input, "crazyhouse"))
	  {
	    Variant = Crazyhouse;
	    memcpy(material, zh_material, sizeof(zh_material));
	    init_book();
	  }
	else if (strstr(input, "bughouse"))
	  {
	    Variant = Bughouse;
	    memcpy(material, zh_material, sizeof(zh_material));
	    init_book();
	  }
	else if (strstr(input, "suicide"))
	  {
	    Variant = Suicide;
	    Giveaway = FALSE;
	    memcpy(material, suicide_material, sizeof(suicide_material));
	    init_book();
	  }
	else if (strstr(input, "giveaway"))
	  {
	    Variant = Suicide;
	    Giveaway = TRUE;
	    memcpy(material, suicide_material, sizeof(suicide_material));
	    init_book();
	  }
	else if (strstr(input, "losers"))
	  {
	    Variant = Losers;
	    memcpy(material, losers_material, sizeof(losers_material));
	    init_book();
	  }
	
	initialize_hash();
	clear_tt();
	reset_ecache();

      }
      else if (!strncmp (input, "analyze", 7)) {
	is_analyzing = TRUE;
	is_pondering = TRUE;
	think();
	ply = 0;
      }
      else if (!strncmp (input, "undo", 4)) {
	    printf("Move number : %d\n", move_number);
	if (move_number > 0)
	  {
		  ply = 1;
	    path_x[0] = game_history_x[--move_number];
	    unmake(&game_history[move_number], 0);
	    reset_piece_square();
	    root_to_move ^= 1;
	  }
	result = 0;
      }
      else if (!strncmp (input, "remove", 5)) {
	if (move_number > 1)
	  {
		  ply = 1;
	    path_x[0] = game_history_x[--move_number];
	    unmake(&game_history[move_number], 0);
	    reset_piece_square();

		  ply = 1;
	    path_x[0] = game_history_x[--move_number];
	    unmake(&game_history[move_number], 0);
	    reset_piece_square();
	  }
	result = 0;
      }
      else if (!strncmp (input, "edit", 4)) {
	is_edit_mode = TRUE;
	edit_color = WHITE;
      }
      else if (!strncmp (input, ".", 1) && is_edit_mode) {
	is_edit_mode = FALSE;
	if (wking_loc == 30) white_castled = no_castle;
	if (bking_loc == 114) black_castled = no_castle;
	book_ply = 50;
	ep_square = 0;
	move_number = 0;
	memset(opening_history, 0, sizeof(opening_history));
	clear_tt();
	initialize_hash();
	reset_piece_square();
      }
      else if (is_edit_mode && !strncmp (input, "c", 1)) {
	if (edit_color == WHITE) edit_color = BLACK; else edit_color = WHITE;
	}
      else if (is_edit_mode && !strncmp (input, "#", 1)) {
	reset_board();
	move_number = 0;
      }
      else if (is_edit_mode 
	       && isalpha(input[0]) 
	       && isalpha(input[1]) 
	       && isdigit(input[2])) {
	PutPiece(edit_color, input[0], input[1], input[2]);
      }
      else if (!strncmp (input, "partner", 7)) {
	HandlePartner(input+7);
	}
      else if (!strncmp (input, "$partner", 8)) {
	HandlePartner(input+8);
      }
      else if (!strncmp (input, "ptell", 5)) {
	HandlePtell(input);
      }
      else if (!strncmp (input, "test", 4)) {
	run_epd_testsuite();
      }
      else if (!strncmp (input, "st", 2)) {
	sscanf(input+3, "%d", &fixed_time);
	fixed_time = fixed_time * 100;
      }
      else if (!strncmp (input, "book", 4)) {
	build_book();
      }
      else if (!strncmp (input, "speed",  5)) {
	speed_test();
      }
      else if (!strncmp (input, "result", 6)) {
	if (cfg_booklearn)
	  {
	    if (strstr (input+7, "1-0"))
	      {
		if (comp_color == 1)
		  book_learning(WIN);
		else
		  book_learning(LOSS);
	      }
	    else if (strstr(input+7, "0-1"))
	      {
		if (comp_color == 1)
		  book_learning(LOSS);
		else
		  book_learning(WIN);
	      }
	    else if (strstr(input+7, "1/2-1/2"))
	      {
		book_learning(DRAW);
	      };
	  }
	}
      else if (!strncmp (input, "prove", 5)) {
	printf("\nMax time to search (s): ");
	start_time = rtime();
	rinput(readbuff, STR_BUFF, stdin);
	pn_time = atoi(readbuff) * 100;
	printf("\n");
	proofnumbersearch();      
       }
      else if (!strncmp (input, "ping", 4)) {
	sscanf (input+5, "%d", &pingnum);
	printf("pong %d\n", pingnum);
      }
      else if (!strncmp (input, "fritz", 5)) {
	braindeadinterface = TRUE;
      }
      else if (!strncmp (input, "reset", 5)) {
	
	memcpy(material, std_material, sizeof(std_material));
	Variant = Normal;
	
	init_game ();
	initialize_hash();
	
	clear_tt();
	init_book();
	reset_ecache();       
	
	force_mode = FALSE;
	fixed_time = FALSE;
	
	root_to_move = WHITE;
	
	comp_color = 0;
	move_number = 0;
	bookidx = 0;
	my_rating = opp_rating = 2000;
      }
      else if (!strncmp (input, "setboard", 8)) {
	setup_epd_line(input+9);
      }
      else if (!strncmp (input, "buildegtb", 9)) {
        Variant = Suicide;
	gen_all_tables();
      }
      else if (!strncmp (input, "lookup", 6)) {
	Variant = Suicide;
        printf("Value : %d\n", egtb(white_to_move));
      }
      else if (!strncmp (input, ".", 1)) {
        /* periodic updating and were not searching */
	/* most likely due to proven mate */
	continue;
      }
      else if (!strncmp (input, "sd", 2)) {
	sscanf(input+3, "%d", &maxdepth);
	printf("New max depth set to: %d\n", maxdepth);
	continue;
      }
      else if (!strncmp (input, "auto", 4)) {
	automode = 1;
	continue;
      }
      else if (!strncmp (input, "protover", 8)) {
	printf("feature ping=1 setboard=1 playother=0 san=0 usermove=0 time=1\n");
	printf("feature draw=0 sigint=0 sigterm=0 reuse=1 analyze=1\n");
	printf("feature myname=\"Sjeng " VERSION "\"\n");
	printf("feature variants=\"normal,bughouse,crazyhouse,suicide,giveaway,losers\"\n");
	printf("feature colors=1 ics=0 name=0 pause=0 done=1\n");
	xb_mode = 2;
      }
      else if (!strncmp (input, "accepted", 8)) {
	/* do nothing as of yet */
      }
      else if (!strncmp (input, "rejected", 8)) {
	printf("Interface does not support a required feature...expect trouble.\n");
      }
      else if (!strncmp (input, "warranty", 8)) {
	  printf("\n  BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\n"
		 "FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\n"
		 "OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\n"
		 "PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\n"
		 "OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n"
		 "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\n"
		 "TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\n"
		 "PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\n"
		 "REPAIR OR CORRECTION.\n"
		 "\n");
	  printf("  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\n"
		 "WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\n"
		 "REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\n"
		 "INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\n"
		 "OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\n"
		 "TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\n"
		 "YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\n"
		 "PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\n"
		 "POSSIBILITY OF SUCH DAMAGES.\n\n");

	}
      else if (!strncmp (input, "distribution", 12)) {
	printf("\n  You may copy and distribute verbatim copies of the Program's\n"
	       "source code as you receive it, in any medium, provided that you\n"
	       "conspicuously and appropriately publish on each copy an appropriate\n"
	       "copyright notice and disclaimer of warranty; keep intact all the\n"
	       "notices that refer to this License and to the absence of any warranty;\n"
	       "and give any other recipients of the Program a copy of this License\n"
	       "along with the Program.\n"
	       "\n"
	       "You may charge a fee for the physical act of transferring a copy, and\n"
	       "you may at your option offer warranty protection in exchange for a fee.\n\n");

	}
      else if (!strcmp (input, "help")) {
	printf ("\n%s\n\n", divider);
	printf ("diagram/d:       toggle diagram display\n");
	printf ("exit/quit:       terminate Sjeng\n");
	printf ("go:              make Sjeng play the side to move\n");
	printf ("new:             start a new game\n");
	printf ("level <x>:       the xboard style command to set time\n");
	printf ("  <x> should be in the form: <a> <b> <c> where:\n");
	printf ("  a -> moves to TC (0 if using an ICS style TC)\n");
	printf ("  b -> minutes per game\n");
	printf ("  c -> increment in seconds\n");
	printf ("nodes:           outputs the number of nodes searched\n");
	printf ("nps:             outputs Sjeng's NPS in search\n");
	printf ("perft <x>:       compute raw nodes to depth x\n");
	printf ("post:            toggles thinking output\n");
	printf ("xboard:          put Sjeng into xboard mode\n");
	printf ("test:            run an EPD testsuite\n");
	printf ("speed:           test movegen and evaluation speed\n");
	printf ("warranty:        show warranty details\n");
	printf ("distribution:    show distribution details\n");
	printf( "proof:           try to prove or disprove the current pos\n");
	printf( "sd <x>:          limit thinking to depth x\n");
	printf( "st <x>:          limit thinking to x centiseconds\n");
	printf( "setboard <FEN>:  set board to a specified FEN string\n");
	printf( "undo:            back up a half move\n");
	printf( "remove:          back up a full move\n");
	printf( "force:           disable computer moving\n");
	printf( "auto:            computer plays both sides\n");
	printf ("\n%s\n\n", divider);
	
        show_board = 0;
      }
      else if (!xb_mode) {
	printf ("Illegal move: %s\n", input);
      }

    }

  }

  return 0;

}
Esempio n. 21
0
int main(int argc, char* argv[])
{

	// Print help if necessary
	bool help = read_bool(argc, argv, "--help", false);
	if ((argc < 2) || (help)) {
		usage(argv);
		return 0;
	}

	// Use parameters struct for passing parameters to kernels efficiently
	parameters prm;

	// Parse inputs
	prm.matDims[0] = read_int(argc, argv, "--m", 2);
	prm.matDims[1] = read_int(argc, argv, "--k", 2);
	prm.matDims[2] = read_int(argc, argv, "--n", 2);
	prm.rank = read_int(argc, argv, "--rank", 7);
	prm.method = read_string(argc, argv, "--method", (char *)"als");
	int maxIters = read_int(argc, argv, "--maxiters", 1000);
	int maxSecs = read_int(argc, argv, "--maxsecs", 1000);
	double tol = read_double(argc, argv, "--tol", 1e-8);
	int printItn = read_int(argc, argv, "--printitn", 0);
	double printTol = read_double(argc, argv, "--printtol", 1.0);
	int seed = read_int(argc, argv, "--seed", 0);
	int numSeeds = read_int(argc, argv, "--numseeds", 1);
	bool verbose = read_bool(argc, argv, "--verbose", false);
	prm.rnd_maxVal = read_double(argc,argv,"--maxval",1.0);
	prm.rnd_pwrOfTwo = read_int(argc,argv,"--pwrof2",0);
	bool roundFinal = read_bool(argc, argv, "--rndfin",false);
	prm.alpha = read_double(argc,argv, "--alpha", 0.1);
	int M = read_int(argc,argv, "--M", 0);
	if (M)
	{
		prm.M[0] = M;
		prm.M[1] = M;
		prm.M[2] = M;
	} else {	    
		prm.M[0] = read_int(argc, argv, "--M0", -1);
		prm.M[1] = read_int(argc, argv, "--M1", -1);
		prm.M[2] = read_int(argc, argv, "--M2", -1);
	}
	char * infile = read_string(argc, argv, "--input", NULL);
	char * outfile = read_string(argc, argv, "--output", NULL);

	if (verbose) {
		setbuf(stdout, NULL);
		printf("\n\n---------------------------------------------------------\n");
		printf("PARAMETERS\n");
		printf("dimensions = %d %d %d\n",prm.matDims[0],prm.matDims[1],prm.matDims[2]);
		printf("rank       = %d\n",prm.rank);
		printf("method     = %s\n",prm.method);
		if (infile)
			printf("input      = %s\n",infile);
		else
		{
			if (numSeeds == 1)
				printf("input      = seed %d\n",seed); 
			else
				printf("inputs     = seeds %d-%d\n",seed,seed+numSeeds-1);
		}
		if (outfile)
			printf("output     = %s\n",outfile);
		else
			printf("output     = none\n"); 
		if (!strcmp(prm.method,"als"))
		{
			printf("tol        = %1.2e\n",tol);
			printf("alpha      = %1.2e\n",prm.alpha);
			printf("maval      = %1.2e\n",prm.rnd_maxVal);
			printf("M's        = (%d,%d,%d)\n",prm.M[0],prm.M[1],prm.M[2]);
			printf("maxiters   = %d\n",maxIters);
			printf("maxsecs    = %d\n",maxSecs);
			printf("printitn   = %d\n",printItn);
			printf("printtol   = %1.2e\n",printTol);
		}
		printf("---------------------------------------------------------\n");
	}

	// Initialize other variables
	int i, j, k, numIters, mkn, tidx[3];
	double err, errOld, errChange = 0.0, start_als, start_search, elapsed, threshold;

	// Compute tensor dimensions
	prm.dims[0] = prm.matDims[0]*prm.matDims[1];
	prm.dims[1] = prm.matDims[1]*prm.matDims[2];
	prm.dims[2] = prm.matDims[0]*prm.matDims[2];

	// Compute tensor's nnz, total number of entries, and Frobenius norm
	mkn = prm.matDims[0]*prm.matDims[1]*prm.matDims[2];
	prm.mkn2 = mkn*mkn;
	prm.xNorm = sqrt(mkn);

	// Compute number of columns in matricized tensors
	for (i = 0; i < 3; i++)
		prm.mtCols[i] = prm.mkn2 / prm.dims[i];

	// Construct three matricizations of matmul tensor
	prm.X = (double**) malloc( 3 * sizeof(double*) );
	for (i = 0; i < 3; i++)
		prm.X[i] = (double*) calloc( prm.mkn2, sizeof(double) );
	for (int mm = 0; mm < prm.matDims[0]; mm++)
		for (int kk = 0; kk < prm.matDims[1]; kk++)
			for (int nn = 0; nn < prm.matDims[2]; nn++)
			{
				tidx[0] = mm + kk*prm.matDims[0];
				tidx[1] = kk + nn*prm.matDims[1];
				tidx[2] = mm + nn*prm.matDims[0];
				prm.X[0][tidx[0]+prm.dims[0]*(tidx[1]+prm.dims[1]*tidx[2])] = 1;
				prm.X[1][tidx[1]+prm.dims[1]*(tidx[0]+prm.dims[0]*tidx[2])] = 1;
				prm.X[2][tidx[2]+prm.dims[2]*(tidx[0]+prm.dims[0]*tidx[1])] = 1;
			}

	// Allocate factor weights and matrices: working, initial, and model
	prm.lambda = (double*) malloc( prm.rank * sizeof(double) );
	prm.U  = (double**) malloc( 3 * sizeof(double*) );
	double** U0 = (double**) malloc( 3 * sizeof(double*) );
	prm.model = (double**) malloc( 3 * sizeof(double*) );
	for (i = 0; i < 3; i++)
	{
		prm.U[i] =  (double*) calloc( prm.mkn2, sizeof(double) );
		U0[i] = (double*) calloc( prm.dims[i]*prm.rank, sizeof(double) );
		prm.model[i] = (double*) calloc( prm.dims[i]*prm.rank, sizeof(double) );
	}

	// Allocate coefficient matrix within ALS (Khatri-Rao product) 
	int maxMatDim = prm.matDims[0];
	if (maxMatDim < prm.matDims[1]) maxMatDim = prm.matDims[1];
	if (maxMatDim < prm.matDims[2]) maxMatDim = prm.matDims[2];
	prm.A = (double*) malloc( maxMatDim*mkn*prm.rank * sizeof(double) );

	// Allocate workspaces
	prm.tau = (double*) malloc( mkn * sizeof(double) );
	prm.lwork = maxMatDim*mkn*prm.rank;
	prm.work = (double*) malloc( prm.lwork * sizeof(double) );
	prm.iwork = (int*) malloc( prm.mkn2 * sizeof(int) );    

	// Allocate matrices for normal equations 
	int maxDim = prm.dims[0];
	if (maxDim < prm.dims[1]) maxDim = prm.dims[1];
	if (maxDim < prm.dims[2]) maxDim = prm.dims[2];
	prm.NE_coeff = (double*) malloc( prm.rank*prm.rank * sizeof(double) );
	prm.NE_rhs = (double*) malloc( maxDim*prm.rank * sizeof(double) );
	prm.residual = (double*) malloc( prm.mkn2 * sizeof(double) );

	//--------------------------------------------------
	// Search Loop
	//--------------------------------------------------
	int mySeed = seed, numGoodSeeds = 0, statusCnt = 0, status = 1;
	start_search = wall_time(); 
	for (int seed_cnt = 0; seed_cnt < numSeeds; ++seed_cnt)
	{
		// Set starting point from random seed (match Matlab Tensor Toolbox)
		RandomMT cRMT(mySeed);
		for (i = 0; i < 3; i++)
			for (j = 0; j < prm.dims[i]; j++)
				for (k = 0; k < prm.rank; k++)
					U0[i][j+k*prm.dims[i]] = cRMT.genMatlabMT();
		for (i = 0; i < prm.rank; i++)
			prm.lambda[i] = 1.0;  

		// Copy starting point
		for (i = 0; i < 3; i++)
			cblas_dcopy(prm.dims[i]*prm.rank,U0[i],1,prm.U[i],1); 

		// read from file if input is given    
		if( infile )
			read_input( infile, prm ); 

		if (verbose)
		{ 
			printf("\nSTARTING POINT...\n");
			for (i = 0; i < 3; i++)
			{
				printf("Factor matrix %d:\n",i);
				print_matrix(prm.U[i],prm.dims[i],prm.rank,prm.dims[i]);
			}
			printf("\n");
		}   

		//--------------------------------------------------
		// Main ALS Loop
		//--------------------------------------------------
		start_als = wall_time();
		err = 1.0; 
		threshold = 1e-4;
		for (numIters = 0; numIters < maxIters && (wall_time()-start_als) < maxSecs; numIters++)
		{
			errOld = err;

			if (!strcmp(prm.method,"als"))
			{
				// Perform an iteration of ALS using NE with Smirnov's penalty term
				err = als( prm );
			}
			else if (!strcmp(prm.method,"sparsify"))
			{   
				// print stats before sparsifying
				printf("Old residual: %1.2e\n",compute_residual(prm,2,true));
				printf("Old nnz (larger than %1.1e): %d %d %d\n", threshold, nnz(prm.U[0],prm.dims[0]*prm.rank,threshold), nnz(prm.U[1],prm.dims[1]*prm.rank,threshold), nnz(prm.U[2],prm.dims[2]*prm.rank,threshold) );

				// sparsify and return
				printf("\nSparsifying...\n\n");
				sparsify( prm );
				numIters = maxIters;

				// print stats after sparsifying
				printf("New residual: %1.2e\n",compute_residual(prm,2,true));
				printf("New nnz (larger than %1.1e): %d %d %d\n", threshold, nnz(prm.U[0],prm.dims[0]*prm.rank,threshold), nnz(prm.U[1],prm.dims[1]*prm.rank,threshold), nnz(prm.U[2],prm.dims[2]*prm.rank,threshold) );
			}
			else if (!strcmp(prm.method,"round"))
			{
				// print stats before rounding
				printf("Old residual: %1.2e\n",compute_residual(prm,2,true));
				printf("Old nnz (larger than %1.1e): %d %d %d\n", threshold, nnz(prm.U[0],prm.dims[0]*prm.rank,threshold), nnz(prm.U[1],prm.dims[1]*prm.rank,threshold), nnz(prm.U[2],prm.dims[2]*prm.rank,threshold) );
				// round and return
				for (i = 0; i < 3; i++)
				{
					capping(prm.U[i],prm.dims[i]*prm.rank,prm.rnd_maxVal);
					rounding(prm.U[i],prm.dims[i]*prm.rank,prm.rnd_pwrOfTwo);
				}
				numIters = maxIters;

				// print stats after rounding
				printf("New residual: %1.2e\n",compute_residual(prm,2,true));
				printf("New nnz (larger than %1.1e): %d %d %d\n", threshold, nnz(prm.U[0],prm.dims[0]*prm.rank,threshold), nnz(prm.U[1],prm.dims[1]*prm.rank,threshold), nnz(prm.U[2],prm.dims[2]*prm.rank,threshold) );
			}
			else
				die("Invalid method\n");   

			// Compute change in relative residual norm
			errChange = fabs(err - errOld);          

			// Print info at current iteration
			if ((printItn > 0) && (((numIters + 1) % printItn) == 0))
			{                
				// print info                    
				printf ("Iter %d: residual = %1.5e change = %1.5e\n", numIters + 1, err, errChange);
			} 

			// Check for convergence 
			if ( numIters > 0 && errChange < tol )
				break;

		}

		// If rounding, round final solution and re-compute residual
		if(roundFinal)
		{
			// normalize columns in A and B factors, put arbitrary weights into C
			normalize_model( prm, 2 );

			// cap large values and round to nearest power of 2
			for (i = 0; i < 3; i++)
			{
				capping(prm.U[i],prm.dims[i]*prm.rank,prm.rnd_maxVal);
				rounding(prm.U[i],prm.dims[i]*prm.rank,prm.rnd_pwrOfTwo);
			}

			err = compute_residual(prm,0,true);
		}    

		// Print status if searching over many seeds
		statusCnt++;
		if (numSeeds > 1000 && statusCnt == numSeeds/10)
		{
			printf("...%d%% complete...\n",10*status);
			status++;
			statusCnt = 0;
		}

		// Print final info
		elapsed = wall_time() - start_als;
		if ((printItn > 0 || verbose) && !strcmp(prm.method,"als"))
		{
			if (infile)
				printf("\nInput %s ",infile);
			else
				printf("\nInitial seed %d ",mySeed);
			printf("achieved residual %1.3e in %d iterations and %1.3e seconds\n \t final residual change: %1.3e\n \t average time per iteration: %1.3e s\n", err, numIters, elapsed, errChange, elapsed/numIters);
		}

		if (verbose)
		{
			printf("\nSOLUTION...\n");
			for (i = 0; i < 3; i++)
			{
				printf("Factor matrix %d:\n",i);
				if (roundFinal || !strcmp(prm.method,"round"))
					print_int_matrix(prm.U[i], prm.dims[i], prm.rank, prm.dims[i], prm.rnd_pwrOfTwo);
				else
					print_matrix(prm.U[i],prm.dims[i],prm.rank,prm.dims[i]);
			}
			
			if (err < printTol)
				numGoodSeeds++;
		}
		else if (err < printTol)
		{
			numGoodSeeds++;

			printf("\n\n***************************************\n");
			if (infile)
				printf("Input %s: ",infile);
			else
				printf("Initial seed %d: ",mySeed);
			printf("after %d iterations, achieved residual %1.3e with final residual change of %1.3e\n", numIters, err, errChange);
			if (roundFinal)
			{

				for (i = 0; i < 3; i++)
				{
					printf("Factor matrix %d:\n",i);
					print_int_matrix(prm.U[i], prm.dims[i], prm.rank, prm.dims[i], prm.rnd_pwrOfTwo);
				}

				int count = 0;
				for (i = 0; i < 3; i++)
					count += nnz(prm.U[i],prm.dims[i]*prm.rank);
				printf("\ttotal nnz in solution: %d\n",count);
				printf("\tnaive adds/subs:       %d\n",count - prm.dims[2] - 2*prm.rank);
			}
			printf("***************************************\n\n\n");
		}

		// write to output
		if( outfile )
			write_output( outfile, prm ); 

		mySeed++;
	}      

	// Final report of processor statistics
	elapsed = wall_time()-start_search;

	// Print stats
	if (!strcmp(prm.method,"als"))
	{
		printf("\n\n------------------------------------------------------------\n");
		printf("Time elapsed:                \t%1.1e\tseconds\n",elapsed);
		printf("Total number of seeds tried: \t%d\n",numSeeds);
		printf("Total number of good seeds:  \t%d",numGoodSeeds);
		printf("\t(residual < %2.1e)\n",printTol);   
		printf("------------------------------------------------------------\n");
	}


	// free allocated memory
	for (i = 0; i < 3; i++)
	{
		free( prm.X[i] );
		free( prm.U[i] );
		free( U0[i] );
		free( prm.model[i] );
	} 
	free( prm.X );
	free( prm.U );
	free( U0 );
	free( prm.model );
	free( prm.lambda );
	free( prm.A );
	free( prm.NE_coeff );
	free( prm.NE_rhs );
	free( prm.residual );
	free( prm.tau );
	free( prm.work );
	free( prm.iwork );

	return 0;

}
Esempio n. 22
0
int main(int argc,char *argv[])
{ 

  Allinit();
  S_BOARD pos[1];
  S_SEARCHINFO info[1];
  info->quit = FALSE;
  info->depth = SETDEPTH;
  pos->hashtable->ptable=NULL;
  inithashtable(pos->hashtable,64);
  setbuf(stdin,NULL);
  setbuf(stdout,NULL);

  int argnum =0;

  for(argnum = 0; argnum < argc; argnum++)
  {
    if(strncmp(argv[argnum],"NoBook",6)==0)
    {
      engineoptions->usebook = FALSE;
      printf("Book Off\n");
    }
  }

  printf("Welcome to abhi_engine! type cons for console mode ...\n");
  char line[256];

  while(TRUE)
  {
    memset(line,0,sizeof(line));
    fflush(stdout);
    if(!fgets(line,256,stdin))
      continue;
    if(line[0]=='\n')
      continue;
    if(!strncmp(line,"uci",3))
    {
      uci_loop(pos,info);
      if(info->quit == TRUE)
        break;
      continue;
    }
    else if(!strncmp(line,"xboard",6))
    {
        xboard_loop(pos,info);
        if(info->quit == TRUE)
          break;
        continue;
    }
    else if(!strncmp(line,"cons",4))
    {
      console_loop(pos,info);
      if(info->quit == TRUE)
        break;
      continue;
    }
    else if(!strncmp(line,"quit",4))
      break;
  }
  free(pos->hashtable->ptable);
  cleanpolybook();
  
  return 0;
}
Esempio n. 23
0
int main(int argc, char **argv)
{
  setlocale(LC_NUMERIC, "C");
  program_name = argv[0];
  string env;
  static char stderr_buf[BUFSIZ];
  setbuf(stderr, stderr_buf);
  int c;
  static const struct option long_options[] = {
    { "help", no_argument, 0, CHAR_MAX + 1 },
    { "version", no_argument, 0, 'v' },
    { NULL, 0, 0, 0 }
  };
  while ((c = getopt_long(argc, argv, "b:c:F:gI:lmp:P:vw:", long_options, NULL))
	 != EOF)
    switch(c) {
    case 'b':
      // XXX check this
      broken_flags = atoi(optarg);
      bflag = 1;
      break;
    case 'c':
      if (sscanf(optarg, "%d", &ncopies) != 1 || ncopies <= 0) {
	error("bad number of copies `%s'", optarg);
	ncopies = 1;
      }
      break;
    case 'F':
      font::command_line_font_dir(optarg);
      break;
    case 'g':
      guess_flag = 1;
      break;
    case 'I':
      include_search_path.command_line_dir(optarg);
      break;
    case 'l':
      landscape_flag = 1;
      break;
    case 'm':
      manual_feed_flag = 1;
      break;
    case 'p':
      if (!font::scan_papersize(optarg, 0,
				&user_paper_length, &user_paper_width))
	error("invalid custom paper size `%1' ignored", optarg);
      break;
    case 'P':
      env = "GROPS_PROLOGUE";
      env += '=';
      env += optarg;
      env += '\0';
      if (putenv(strsave(env.contents())))
	fatal("putenv failed");
      break;
    case 'v':
      printf("GNU grops (groff) version %s\n", Version_string);
      exit(0);
      break;
    case 'w':
      if (sscanf(optarg, "%d", &linewidth) != 1 || linewidth < 0) {
	error("bad linewidth `%1'", optarg);
	linewidth = -1;
      }
      break;
    case CHAR_MAX + 1: // --help
      usage(stdout);
      exit(0);
      break;
    case '?':
      usage(stderr);
      exit(1);
      break;
    default:
      assert(0);
    }
  font::set_unknown_desc_command_handler(handle_unknown_desc_command);
  SET_BINARY(fileno(stdout));
  if (optind >= argc)
    do_file("-");
  else {
    for (int i = optind; i < argc; i++)
      do_file(argv[i]);
  }
  return 0;
}
Esempio n. 24
0
int main(int argc, char** argv)
{
#ifdef USE_DEBUGNET
    int ret = debugNetInit("255.255.255.255", 18194, DEBUG);
    printf("debugNetInit: %d", ret);
#endif

    printf("DOOM started\n");

    setbuf(stdout, NULL);

    int res = scePowerSetArmClockFrequency(50);
    if (res != 0x0)
    {
        printf("scePowerSetArmClockFrequency failed! (0x%08x) (Normal if not using PSM Unity 1.06. No clock speed change for you.)\n", res);
    }

    myargc = 0;
    myargv = 0;

    doomwaddir = PSP2_DIR("Documents/");
    strcpy_s(doomwaddir2, 256, doomwaddir);
    strcat(doomwaddir2, "WADS/");

    printf("WAD folder: %s\n", doomwaddir2);

	//pspAudioInit();
	//pspAudioSetChannelCallback(0, (void *)&sound_callback);

	//_DisableFPUExceptions();
//	pspDebugScreenInit();

	//sceCtrlSetSamplingCycle(0);

	//int result = sceCtrlSetSamplingMode(PSP2_CTRL_MODE_ANALOG);
 //   if (result < 0)
 //   {
 //       printf("sceCtrlSetSamplingMode : 0x%x", result);
 //   }

	//SetupCallbacks();
        pgInit();
        pgScreenFrame(2,0);
        pgFillvram(0);

    Get_DirList(doomwaddir2);
    dlist_start  = 0;
    dlist_curpos = 0;
    now_depth    = 0;

while(1) {
    Draw_All();
switch(Control()) {
		case 1:
			Get_DirList(doomwaddir2);
			break;
		case 2:
                        pgFillvram(0);
                        strcpy_s(target, 264, doomwaddir2);
                        strcat(target, dlist[dlist_curpos].name);

                        pgScreenFlipV();
                        //pspDebugScreenInit();

    D_DoomMain (); 
        }
    }    

    return 0;

}
Esempio n. 25
0
int
main(int argc, char **argv)
#endif
{
    int i;

#ifdef LINUXVGA
    LINUX_setup();		/* setup VGA before dropping privilege DBT 4/5/99 */
    drop_privilege();
#endif
/* make sure that we really have revoked root access, this might happen if
   gnuplot is compiled without vga support but is installed suid by mistake */
#ifdef __linux__
    setuid(getuid());
#endif

#if defined(MSDOS) && !defined(_Windows) && !defined(__GNUC__)
    PC_setup();
#endif /* MSDOS !Windows */

/* HBB: Seems this isn't needed any more for DJGPP V2? */
/* HBB: disable all floating point exceptions, just keep running... */
#if defined(DJGPP) && (DJGPP!=2)
    _control87(MCW_EM, MCW_EM);
#endif

#if defined(OS2)
    int rc;
#ifdef OS2_IPC
    char semInputReadyName[40];
    sprintf( semInputReadyName, "\\SEM32\\GP%i_Input_Ready", getpid() );
    rc = DosCreateEventSem(semInputReadyName,&semInputReady,0,0);
    if (rc != 0)
      fputs("DosCreateEventSem error\n",stderr);
#endif
    rc = RexxRegisterSubcomExe("GNUPLOT", (PFN) RexxInterface, NULL);
#endif

/* malloc large blocks, otherwise problems with fragmented mem */
#ifdef MALLOCDEBUG
    malloc_debug(7);
#endif

/* get helpfile from home directory */
#ifdef __DJGPP__
    {
	char *s;
	strcpy(HelpFile, argv[0]);
	for (s = HelpFile; *s; s++)
	    if (*s == DIRSEP1)
		*s = DIRSEP2;	/* '\\' to '/' */
	strcpy(strrchr(HelpFile, DIRSEP2), "/gnuplot.gih");
    }			/* Add also some "paranoid" tests for '\\':  AP */
#endif /* DJGPP */

#ifdef VMS
    unsigned int status[2] = { 1, 0 };
#endif

#if defined(HAVE_LIBEDITLINE)
    rl_getc_function = getc_wrapper;
#endif

#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
    /* T.Walter 1999-06-24: 'rl_readline_name' must be this fix name.
     * It is used to parse a 'gnuplot' specific section in '~/.inputrc'
     * or gnuplot specific commands in '.editrc' (when using editline
     * instead of readline) */
    rl_readline_name = "Gnuplot";
    rl_terminal_name = getenv("TERM");
#if defined(HAVE_LIBREADLINE)
    using_history();
#else
    history_init();
#endif
#endif
#if defined(HAVE_LIBREADLINE) && !defined(MISSING_RL_TILDE_EXPANSION)
    rl_complete_with_tilde_expansion = 1;
#endif

    for (i = 1; i < argc; i++) {
	if (!argv[i])
	    continue;

	if (!strcmp(argv[i], "-V") || !strcmp(argv[i], "--version")) {
	    printf("gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
	    return 0;

	} else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
	    printf( "Usage: gnuplot [OPTION]... [FILE]\n"
#ifdef X11
		    "for X11 options see 'help X11->command-line-options'\n"
#endif
		    "  -V, --version\n"
		    "  -h, --help\n"
		    "  -p  --persist\n"
		    "  -d  --default-settings\n"
		    "  -e  \"command1; command2; ...\"\n"
		    "gnuplot %s patchlevel %s\n",
		    gnuplot_version, gnuplot_patchlevel);
#ifdef DEVELOPMENT_VERSION
	    printf(
#ifdef DIST_CONTACT
		    "Report bugs to "DIST_CONTACT"\n"
		    "            or %s\n",
#else
		    "Report bugs to %s\n",
#endif
		    bug_email);
#endif
	    return 0;

	} else if (!strncmp(argv[i], "-persist", 2) || !strcmp(argv[i], "--persist")
#ifdef _Windows
		|| !stricmp(argv[i], "-noend") || !stricmp(argv[i], "/noend")
#endif
		) {
	    persist_cl = TRUE;
	} else if (!strncmp(argv[i], "-d", 2) || !strcmp(argv[i], "--default-settings")) {
	    /* Skip local customization read from ~/.gnuplot */
	    skip_gnuplotrc = TRUE;
	}
    }

#ifdef X11
    /* the X11 terminal removes tokens that it recognizes from argv. */
    {
	int n = X11_args(argc, argv);
	argv += n;
	argc -= n;
    }
#endif

    setbuf(stderr, (char *) NULL);

#ifdef HAVE_SETVBUF
    /* This was once setlinebuf(). Docs say this is
     * identical to setvbuf(,NULL,_IOLBF,0), but MS C
     * faults this (size out of range), so we try with
     * size of 1024 instead. [SAS/C does that, too. -lh]
     */
    if (setvbuf(stdout, (char *) NULL, _IOLBF, (size_t) 1024) != 0)
	(void) fputs("Could not linebuffer stdout\n", stderr);

    /* Switching to unbuffered mode causes all characters in the input
     * buffer to be lost. So the only safe time to do it is on program entry.
     * Do any non-X platforms suffer from this problem?
     * EAM - Jan 2013 YES.
     */
    setvbuf(stdin, (char *) NULL, _IONBF, 0);

#endif

    gpoutfile = stdout;

    /* Initialize pre-loaded user variables */
    (void) Gcomplex(&udv_pi.udv_value, M_PI, 0.0);
    udv_NaN = add_udv_by_name("NaN");
    (void) Gcomplex(&(udv_NaN->udv_value), not_a_number(), 0.0);
    udv_NaN->udv_undef = FALSE;

    init_memory();

    interactive = FALSE;
    init_terminal();		/* can set term type if it likes */
    push_terminal(0);		/* remember the default terminal */

    /* reset the terminal when exiting */
    /* this is done through gp_atexit so that other terminal functions
     * can be registered to be executed before the terminal is reset. */
    GP_ATEXIT(term_reset);

# if defined(_Windows) && ! defined(WGP_CONSOLE)
    interactive = TRUE;
# else
    interactive = isatty(fileno(stdin));
# endif

    /* Note: we want to know whether this is an interactive session so that we can
     * decide whether or not to write status information to stderr.  The old test
     * for this was to see if (argc > 1) but the addition of optional command line
     * switches broke this.  What we really wanted to know was whether any of the
     * command line arguments are file names or an explicit in-line "-e command".
     */
    for (i = 1; i < argc; i++) {
# ifdef _Windows
	if (!stricmp(argv[i], "/noend"))
	    continue;
# endif
	if ((argv[i][0] != '-') || (argv[i][1] == 'e')) {
	    interactive = FALSE;
	    break;
	}
    }

    /* Need this before show_version is called for the first time */

#ifdef HAVE_SYS_UTSNAME_H
    {
	struct utsname uts;

	/* something is fundamentally wrong if this fails ... */
	if (uname(&uts) > -1) {
# ifdef _AIX
	    strcpy(os_name, uts.sysname);
	    sprintf(os_name, "%s.%s", uts.version, uts.release);
# elif defined(SCO)
	    strcpy(os_name, "SCO");
	    strcpy(os_rel, uts.release);
# elif defined(DJGPP)
	    if (!strncmp(uts.sysname, "??Un", 4)) /* don't print ??Unknow" */
		strcpy(os_name, "Unknown");
	    else {
		strcpy(os_name, uts.sysname);
		strcpy(os_rel, uts.release);
	    }
# else
	    strcpy(os_name, uts.sysname);
	    strcpy(os_rel, uts.machine);
# ifdef OS2
	    if (!strchr(os_rel,'.'))
		/* write either "2.40" or "4.0", or empty -- don't print "OS/2 1" */
		strcpy(os_rel, "");
# endif

# endif
	}
    }
#else /* ! HAVE_SYS_UTSNAME_H */

    strcpy(os_name, OS);
    strcpy(os_rel, "");

#endif /* HAVE_SYS_UTSNAME_H */

    if (interactive)
	show_version(stderr);
    else
	show_version(NULL); /* Only load GPVAL_COMPILE_OPTIONS */

#ifdef WGP_CONSOLE
#ifdef CONSOLE_SWITCH_CP
    if (cp_changed && interactive) {
	fprintf(stderr,
	    "\ngnuplot changed the codepage of this console from %i to %i to\n" \
	    "match the graph window. Some characters might only display correctly\n" \
	    "if you change the font to a non-raster type.\n",
	    cp_input, GetConsoleCP());
    }
#else
    if ((GetConsoleCP() != GetACP()) && interactive) {
	fprintf(stderr,
	    "\nWarning: The codepage of the graph window (%i) and that of the\n" \
	    "console (%i) differ. Use `set encoding` or `!chcp` if extended\n" \
	    "characters don't display correctly.\n",
	    GetACP(), GetConsoleCP());
    }
#endif
#endif

    update_gpval_variables(3);  /* update GPVAL_ variables available to user */

#ifdef VMS
    /* initialise screen management routines for command recall */
    if (status[1] = smg$create_virtual_keyboard(&vms_vkid) != SS$_NORMAL)
	done(status[1]);
    if (status[1] = smg$create_key_table(&vms_ktid) != SS$_NORMAL)
	done(status[1]);
#endif /* VMS */

    if (!SETJMP(command_line_env, 1)) {
	/* first time */
	interrupt_setup();
	/* should move this stuff another initialisation routine,
	 * something like init_set() maybe */
	get_user_env();
	init_loadpath();
	init_locale();
	/* HBB: make sure all variables start in the same mode 'reset'
	 * would set them to. Since the axis variables aren't in
	 * initialized arrays any more, this is now necessary... */
	reset_command();
	init_color();		/* Initialization of color  */
	load_rcfile(0);		/* System-wide gnuplotrc if configured */
	load_rcfile(1);		/* ./.gnuplot if configured */
	init_fit();		/* Initialization of fitting module */

	/* After this point we allow pipes and system commands */
	successful_initialization = TRUE;

	load_rcfile(2);		/* ~/.gnuplot */

	if (interactive && term != 0) {		/* not unknown */
#ifdef GNUPLOT_HISTORY
	    FPRINTF((stderr, "Before read_history\n"));
#if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)
	    expanded_history_filename = tilde_expand(GNUPLOT_HISTORY_FILE);
#else
	    expanded_history_filename = gp_strdup(GNUPLOT_HISTORY_FILE);
	    gp_expand_tilde(&expanded_history_filename);
#endif
	    FPRINTF((stderr, "expanded_history_filename = %s\n", expanded_history_filename));
	    read_history(expanded_history_filename);
	    {
		/* BEGIN: Go local to get environment variable */
		const char *temp_env = getenv ("GNUPLOT_HISTORY_SIZE");
		if (temp_env)
		    gnuplot_history_size = strtol (temp_env, (char **) NULL, 10);
	    } /* END: Go local to get environment variable */

	    /*
	     * It is safe to ignore the return values of 'atexit()' and
	     * 'on_exit()'. In the worst case, there is no history of your
	     * currrent session and you have to type all again in your next
	     * session.
	     * This is the default behaviour (traditional reasons), too.
	     * In case you don't have one of these functions, or you don't
	     * want to use them, 'write_history()' is called directly.
	     */
	    GP_ATEXIT(wrapper_for_write_history);
#endif /* GNUPLOT_HISTORY */

	    fprintf(stderr, "\nTerminal type set to '%s'\n", term->name);
	}			/* if (interactive && term != 0) */
    } else {
	/* come back here from int_error() */
	if (!successful_initialization) {
	    /* Only print the warning once */
	    successful_initialization = TRUE;
	    fprintf(stderr,"WARNING: Error during initialization\n\n");
	}
	if (interactive == FALSE)
	    exit_status = EXIT_FAILURE;
#ifdef HAVE_READLINE_RESET
	else
	{
	    /* reset properly readline after a SIGINT+longjmp */
	    rl_reset_after_signal ();
	}
#endif

	load_file_error();	/* if we were in load_file(), cleanup */
	SET_CURSOR_ARROW;

#ifdef VMS
	/* after catching interrupt */
	/* VAX stuffs up stdout on SIGINT while writing to stdout,
	   so reopen stdout. */
	if (gpoutfile == stdout) {
	    if ((stdout = freopen("SYS$OUTPUT", "w", stdout)) == NULL) {
		/* couldn't reopen it so try opening it instead */
		if ((stdout = fopen("SYS$OUTPUT", "w")) == NULL) {
		    /* don't use int_error here - causes infinite loop! */
		    fputs("Error opening SYS$OUTPUT as stdout\n", stderr);
		}
	    }
	    gpoutfile = stdout;
	}
#endif /* VMS */
	if (!interactive && !noinputfiles) {
	    term_reset();
	    exit(EXIT_FAILURE);	/* exit on non-interactive error */
	}
    }

    /* load filenames given as arguments */
    while (--argc > 0) {
	    ++argv;
	    c_token = 0;
	    if (!strncmp(*argv, "-persist", 2) || !strcmp(*argv, "--persist")
#ifdef _Windows
		|| !stricmp(*argv, "-noend") || !stricmp(*argv, "/noend")
#endif
	    ) {
		FPRINTF((stderr,"'persist' command line option recognized\n"));
	    } else if (strcmp(*argv, "-") == 0) {
#if defined(_Windows) && !defined(WGP_CONSOLE)
		TextShow(&textwin);
#endif
		interactive = TRUE;
		while (!com_line());
		interactive = FALSE;

	    } else if (strcmp(*argv, "-e") == 0) {
		--argc; ++argv;
		if (argc <= 0) {
		    fprintf(stderr, "syntax:  gnuplot -e \"commands\"\n");
		    return 0;
		}
		interactive = FALSE;
		noinputfiles = FALSE;
		do_string(*argv);

	    } else if (!strncmp(*argv, "-d", 2) || !strcmp(*argv, "--default-settings")) {
		/* Ignore this; it already had its effect */
		FPRINTF((stderr, "ignoring -d\n"));
	    } else if (*argv[0] == '-') {
		fprintf(stderr, "unrecognized option %s\n", *argv);
	    } else {
		interactive = FALSE;
		noinputfiles = FALSE;
		load_file(loadpath_fopen(*argv, "r"), gp_strdup(*argv), FALSE);
	    }
    }

#ifdef _Windows
    /* On Windows 'persist' is handled by keeping the main input loop running. */
    if (persist_cl) {
	interactive = TRUE;
	while (!com_line());
	interactive = FALSE;
    } else
#endif
    {
	/* take commands from stdin */
	if (noinputfiles)
	    while (!com_line());
    }

#if (defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDITLINE)) && defined(GNUPLOT_HISTORY)
#if !defined(HAVE_ATEXIT) && !defined(HAVE_ON_EXIT)
    /* You should be here if you neither have 'atexit()' nor 'on_exit()' */
    wrapper_for_write_history();
#endif /* !HAVE_ATEXIT && !HAVE_ON_EXIT */
#endif /* (HAVE_LIBREADLINE || HAVE_LIBEDITLINE) && GNUPLOT_HISTORY */

#ifdef OS2
    RexxDeregisterSubcom("GNUPLOT", NULL);
#endif

    /* HBB 20040223: Not all compilers like exit() to end main() */
    /* exit(exit_status); */
    return exit_status;
}
Esempio n. 26
0
int main(int argc, char **argv) {
    signal(SIGPIPE, SIG_IGN);
    setbuf(stdout, nullptr);
    CDnsSeedOpts opts;
    opts.ParseCommandLine(argc, argv);
    printf("Supporting whitelisted filters: ");
    for (std::set<uint64_t>::const_iterator it = opts.filter_whitelist.begin();
         it != opts.filter_whitelist.end(); it++) {
        if (it != opts.filter_whitelist.begin()) {
            printf(",");
        }
        printf("0x%lx", (unsigned long)*it);
    }
    printf("\n");
    if (opts.tor) {
        CService service(LookupNumeric(opts.tor, 9050));
        if (service.IsValid()) {
            printf("Using Tor proxy at %s\n", service.ToStringIPPort().c_str());
            SetProxy(NET_TOR, service);
        }
    }
    if (opts.ipv4_proxy) {
        CService service(LookupNumeric(opts.ipv4_proxy, 9050));
        if (service.IsValid()) {
            printf("Using IPv4 proxy at %s\n",
                   service.ToStringIPPort().c_str());
            SetProxy(NET_IPV4, service);
        }
    }
    if (opts.ipv6_proxy) {
        CService service(LookupNumeric(opts.ipv6_proxy, 9050));
        if (service.IsValid()) {
            printf("Using IPv6 proxy at %s\n",
                   service.ToStringIPPort().c_str());
            SetProxy(NET_IPV6, service);
        }
    }
    bool fDNS = true;
    if (opts.fUseTestNet) {
        printf("Using testnet.\n");
        netMagic[0] = 0xf4;
        netMagic[1] = 0xe5;
        netMagic[2] = 0xf3;
        netMagic[3] = 0xf4;
        seeds = testnet_seeds;
        fTestNet = true;
    }
    if (!opts.ns) {
        printf("No nameserver set. Not starting DNS server.\n");
        fDNS = false;
    }
    if (fDNS && !opts.host) {
        fprintf(stderr, "No hostname set. Please use -h.\n");
        exit(1);
    }
    if (fDNS && !opts.mbox) {
        fprintf(stderr, "No e-mail address set. Please use -m.\n");
        exit(1);
    }
    FILE *f = fopen("dnsseed.dat", "r");
    if (f) {
        printf("Loading dnsseed.dat...");
        CAutoFile cf(f, SER_DISK, CLIENT_VERSION);
        cf >> db;
        if (opts.fWipeBan) db.banned.clear();
        if (opts.fWipeIgnore) db.ResetIgnores();
        printf("done\n");
    }
    pthread_t threadDns, threadSeed, threadDump, threadStats;
    if (fDNS) {
        printf("Starting %i DNS threads for %s on %s (port %i)...",
               opts.nDnsThreads, opts.host, opts.ns, opts.nPort);
        dnsThread.clear();
        for (int i = 0; i < opts.nDnsThreads; i++) {
            dnsThread.push_back(new CDnsThread(&opts, i));
            pthread_create(&threadDns, nullptr, ThreadDNS, dnsThread[i]);
            printf(".");
            Sleep(20);
        }
        printf("done\n");
    }
    printf("Starting seeder...");
    pthread_create(&threadSeed, nullptr, ThreadSeeder, nullptr);
    printf("done\n");
    printf("Starting %i crawler threads...", opts.nThreads);
    pthread_attr_t attr_crawler;
    pthread_attr_init(&attr_crawler);
    pthread_attr_setstacksize(&attr_crawler, 0x20000);
    for (int i = 0; i < opts.nThreads; i++) {
        pthread_t thread;
        pthread_create(&thread, &attr_crawler, ThreadCrawler, &opts.nThreads);
    }
    pthread_attr_destroy(&attr_crawler);
    printf("done\n");
    pthread_create(&threadStats, nullptr, ThreadStats, nullptr);
    pthread_create(&threadDump, nullptr, ThreadDumper, nullptr);
    void *res;
    pthread_join(threadDump, &res);
    return 0;
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
    char hostName[200] = DEFAULT_HOSTNAME;
    int port = DEFAULT_RESMGR_TPM_PORT;

    setbuf(stdout, NULL);
    setvbuf (stdout, NULL, _IONBF, BUFSIZ);

    int opt = -1;
    const char *optstring = "hvk:c:P:l:g:o:p:d:";
    static struct option long_options[] = {
        {"help",0,NULL,'h'},
        {"version",0,NULL,'v'},
        {"akHandle",1,NULL,'k'},
        {"akContext",1,NULL,'c'},
        {"akPassword",1,NULL,'P'},  //add ak auth
        {"idList",1,NULL,'l'},
        {"algorithm",1,NULL,'g'},
        {"outFile",1,NULL,'o'},
        {"port",1,NULL,'p'},
        {"debugLevel",1,NULL,'d'},
        {0,0,0,0}
    };

    char *contextFilePath = NULL;
    TPM_HANDLE akHandle;
    TPMI_ALG_HASH algorithmId;
    PCR_LIST pcrList;

    int returnVal = 0;
    int flagCnt = 0;
    int h_flag = 0,
        v_flag = 0,
        k_flag = 0,
        c_flag = 0,
        P_flag = 0,
        l_flag = 0,
        g_flag = 0,
        o_flag = 0;

    if(argc == 1)
    {
        showHelp(argv[0]);
        return 0;
    }
    while((opt = getopt_long(argc,argv,optstring,long_options,NULL)) != -1)
    {
        switch(opt)
        {
        case 'h':
            h_flag = 1;
            break;
        case 'v':
            v_flag = 1;
            break;
        case 'k':
            if(getSizeUint32Hex(optarg,&akHandle) != 0)
            {
                showArgError(optarg, argv[0]);
                returnVal = -1;
                break;
            }
            k_flag = 1;
            break;
        case 'c':
            contextFilePath = optarg;
            if(contextFilePath == NULL || contextFilePath[0] == '\0')
            {
                returnVal = -2;
                break;
            }
            printf("contextFile = %s\n", contextFilePath);
            c_flag = 1;
            break;

        case 'P':
            sessionData.hmac.t.size = sizeof(sessionData.hmac.t) - 2;
            if(str2ByteStructure(optarg,&sessionData.hmac.t.size,sessionData.hmac.t.buffer) != 0)
            {
                returnVal = -3;
                break;
            }
            P_flag = 1;
            break;
        case 'l':
            if(parseList(optarg, &pcrList) != 0)
            {
                returnVal = -4;
                break;
            }
            l_flag = 1;
            break;
        case 'g':
            if(getSizeUint16Hex(optarg,&algorithmId) != 0)
            {
                showArgError(optarg, argv[0]);
                returnVal = -5;
                break;
            }
            g_flag = 1;
            break;
        case 'o':
            safeStrNCpy(outFilePath, optarg, sizeof(outFilePath));
            if(checkOutFile(outFilePath) != 0)
            {
                returnVal = -6;
                break;
            }
            o_flag = 1;
            break;
        case 'p':
            if( getPort(optarg, &port) )
            {
                printf("Incorrect port number.\n");
                returnVal = -7;
            }
            break;
        case 'd':
            if( getDebugLevel(optarg, &debugLevel) )
            {
                printf("Incorrect debug level.\n");
                returnVal = -8;
            }
            break;
       case ':':
            //              printf("Argument %c needs a value!\n",optopt);
            returnVal = -9;
            break;
        case '?':
            //              printf("Unknown Argument: %c\n",optopt);
            returnVal = -10;
            break;
            //default:
            //  break;
        }
        if(returnVal)
            break;
    };

    if(returnVal != 0)
        return returnVal;

    flagCnt = h_flag + v_flag + k_flag + c_flag + l_flag + g_flag + o_flag;
    if(flagCnt == 1)
    {
        if(h_flag == 1)
            showHelp(argv[0]);
        else if(v_flag == 1)
            showVersion(argv[0]);
        else
        {
            showArgMismatch(argv[0]);
            return -11;
        }
    }
    else if(flagCnt == 4 && ((k_flag || c_flag) && l_flag && g_flag && o_flag))
    {
        if(P_flag == 0)
            sessionData.hmac.t.size = 0;

        prepareTest(hostName, port, debugLevel);

        if(c_flag)
            returnVal = loadTpmContextFromFile(sysContext, &akHandle, contextFilePath);
        if(returnVal == TPM_RC_SUCCESS)
            returnVal = quote(akHandle, pcrList, algorithmId);

        finishTest();

        if(returnVal)
            return -12;
    }
    else
    {
        showArgMismatch(argv[0]);
        return -13;
    }

    return 0;
}
Esempio n. 28
0
// 菜单
int Menu(char *cmd, LinkList head)
{
    
    // 进入到程序主循环
    while(1) {
        
        // 打印帮助信息
        PrintHelp();

        // 输入操作命令
        *cmd = getchar();
        printf("cmd = %c\n", *cmd);
        
        // 清空标准输入缓存
        setbuf(stdin, NULL);
        
        // 清空屏幕
        system("clear");
        
        // 列出所有联系人 
        List(head);
        
        // 根据输入操作
        switch (*cmd) {
            
            // 查询联系人
            case '1': 
                Search(head); 
                break;
            
            // 添加联系人并保存到文件
            case '2': 
                New(head); 
                Save(head); 
                break;
            
            // 更新联系人并保存到文件
            case '3': 
                Update(head); 
                Save(head);
                break;
            
            // 删除联系人并保存到文件
            case '4': 
                Remove(head);
                Save(head);
                break;
            
            // 退出系统
            case '5':
                exit(0);
            
            
            default : 
                printf("Input Error. Try Again\n");
                continue;
        }
        
        getchar();
    
    }

	return 0;
}
Esempio n. 29
0
void
setlinebuf(FILE * file)
{
    setbuf(file, NULL);
}
Esempio n. 30
0
int
main(int argc, char **argv) {
    time_t start = time(NULL);

    // If these fail, there's not really anywhere to complain...
    freopen(TEMPORARY_LOG_FILE, "a", stdout); setbuf(stdout, NULL);
    freopen(TEMPORARY_LOG_FILE, "a", stderr); setbuf(stderr, NULL);

    // If this binary is started with the single argument "--adbd",
    // instead of being the normal recovery binary, it turns into kind
    // of a stripped-down version of adbd that only supports the
    // 'sideload' command.  Note this must be a real argument, not
    // anything in the command file or bootloader control block; the
    // only way recovery should be run with this argument is when it
    // starts a copy of itself from the apply_from_adb() function.
    if (argc == 2 && strcmp(argv[1], "--adbd") == 0) {
        adb_main();
        return 0;
    }

    printf("Starting recovery on %s", ctime(&start));

    load_volume_table();
    get_args(&argc, &argv);

    int previous_runs = 0;
    const char *send_intent = NULL;
    const char *update_package = NULL;
    int wipe_data = 0, wipe_cache = 0, show_text = 0;
    bool just_exit = false;

    int arg;
    while ((arg = getopt_long(argc, argv, "", OPTIONS, NULL)) != -1) {
        switch (arg) {
        case 'p': previous_runs = atoi(optarg); break;
        case 's': send_intent = optarg; break;
        case 'u': update_package = optarg; break;
        case 'w': wipe_data = wipe_cache = 1; break;
        case 'c': wipe_cache = 1; break;
        case 't': show_text = 1; break;
        case 'x': just_exit = true; break;
        case 'l': locale = optarg; break;
        case '?':
            LOGE("Invalid command argument\n");
            continue;
        }
    }

    if (locale == NULL) {
        load_locale_from_cache();
    }
    printf("locale is [%s]\n", locale);

    Device* device = make_device();
    ui = device->GetUI();

    ui->Init();
    ui->SetLocale(locale);
    ui->SetBackground(RecoveryUI::NONE);
    if (show_text) ui->ShowText(true);

#ifdef HAVE_SELINUX
    struct selinux_opt seopts[] = {
      { SELABEL_OPT_PATH, "/file_contexts" }
    };

    sehandle = selabel_open(SELABEL_CTX_FILE, seopts, 1);

    if (!sehandle) {
        fprintf(stderr, "Warning: No file_contexts\n");
        ui->Print("Warning:  No file_contexts\n");
    }
#endif

    device->StartRecovery();

    printf("Command:");
    for (arg = 0; arg < argc; arg++) {
        printf(" \"%s\"", argv[arg]);
    }
    printf("\n");

    if (update_package) {
        // For backwards compatibility on the cache partition only, if
        // we're given an old 'root' path "CACHE:foo", change it to
        // "/cache/foo".
        if (strncmp(update_package, "CACHE:", 6) == 0) {
            int len = strlen(update_package) + 10;
            char* modified_path = (char*)malloc(len);
            strlcpy(modified_path, "/cache/", len);
            strlcat(modified_path, update_package+6, len);
            printf("(replacing path \"%s\" with \"%s\")\n",
                   update_package, modified_path);
            update_package = modified_path;
        }
    }
    printf("\n");

    property_list(print_property, NULL);
    printf("\n");

    int status = INSTALL_SUCCESS;

    if (update_package != NULL) {
        status = install_package(update_package, &wipe_cache, TEMPORARY_INSTALL_FILE);
        if (status == INSTALL_SUCCESS && wipe_cache) {
            if (erase_volume("/cache")) {
                LOGE("Cache wipe (requested by package) failed.");
            }
        }
        if (status != INSTALL_SUCCESS) ui->Print("Installation aborted.\n");
    } else if (wipe_data) {
        if (device->WipeData()) status = INSTALL_ERROR;
        if (erase_volume("/data")) status = INSTALL_ERROR;
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui->Print("Data wipe failed.\n");
    } else if (wipe_cache) {
        if (wipe_cache && erase_volume("/cache")) status = INSTALL_ERROR;
        if (status != INSTALL_SUCCESS) ui->Print("Cache wipe failed.\n");
    } else if (!just_exit) {
        status = INSTALL_NONE;  // No command specified
        ui->SetBackground(RecoveryUI::NO_COMMAND);
    }

    if (status == INSTALL_ERROR || status == INSTALL_CORRUPT) {
        ui->SetBackground(RecoveryUI::ERROR);
    }
    if (status != INSTALL_SUCCESS || ui->IsTextVisible()) {
        prompt_and_wait(device, status);
    }

    // Otherwise, get ready to boot the main system...
    finish_recovery(send_intent);
    ui->Print("Rebooting...\n");
    android_reboot(ANDROID_RB_RESTART, 0, 0);
    return EXIT_SUCCESS;
}