예제 #1
0
static void proc_data(struct wstate *ws, struct ieee80211_frame *wh, int len)
{
	int dlen;
	dlen = len - sizeof(*wh) - 4 -4;

	if (!(wh->i_fc[1] & IEEE80211_FC1_WEP)) {
		time_print("WARNING: Got NON wep packet from %s dlen %d\n",
			   mac2str(wh->i_addr2), dlen);
		return;
	}

	assert (wh->i_fc[1] & IEEE80211_FC1_WEP);

	if ((dlen == 36 || dlen == PADDED_ARPLEN)
	    && ws->ws_rtrmac == (unsigned char*) 1) {
		ws->ws_rtrmac = (unsigned char *) malloc(6);
		if (!ws->ws_rtrmac) {
			perror("malloc()");
			exit(1);
		}

		assert( ws->ws_rtrmac > (unsigned char*) 1);

		memcpy (ws->ws_rtrmac, wh->i_addr3, 6);
		time_print("Got arp reply from (%s)\n",
			   mac2str(ws->ws_rtrmac));

		return;
	}
}
예제 #2
0
파일: snore.c 프로젝트: clamiax/snore
int
main(int argc, char *argv[]) {
	double tm, endtm;
	int i;

	if(argc == 2 && !strcmp("-v", argv[1]))
		die("snore-"VERSION", © 2016 Claudio Alessi, see LICENSE for details\n");

	if(argc == 1) {
		endtm = symbols[LENGTH(symbols) - 1].mult;
	}
	else {
		endtm = 0;
		for(i = 1; i < argc; ++i) {
			tm = time_to_sec(argv[i]);
			if(tm < 0)
				die("%s: wrong time\n", argv[i]);
			endtm += time_to_sec(argv[i]);
		}
	}

	for(tm = 0; tm < endtm; tm += DELTA) {
		time_print(tm); /* ascending */
		printf(" | ");
		time_print(endtm - tm); /* descending */
		fflush(stdout);
		usleep(TICK);
		printf("%s", SCLEAR);
	}
	printf("\a%s elapsed\n", argv[1]);
	return 0;
}
예제 #3
0
static void got_wep(struct wstate *ws, struct ieee80211_frame* wh, int rd)
{
	int bodylen;
	int dlen;
	unsigned char clear[1024];
	int clearsize;
	unsigned char *body;

	bodylen = rd - sizeof(struct ieee80211_frame);

	dlen = bodylen - 4 - 4;
	body = (unsigned char*) wh + sizeof(*wh);


	// log it if its stuff not from us...
	if ( (wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS) ||
	     ( (wh->i_fc[1] & IEEE80211_FC1_DIR_TODS) &&
	        memcmp(wh->i_addr2, ws->ws_mymac, 6) != 0) ) {

		if (body[3] != 0) {
			time_print("Key index=%x!!\n", body[3]);
			exit(1);
		}
		log_wep(ws, wh, rd);
		add_keystream(ws, wh, rd);
	}

	// look for arp-request packets... so we can decrypt em
	if ((wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS) &&
	    (memcmp(wh->i_addr3, ws->ws_mymac, 6) != 0) &&
	    (memcmp(wh->i_addr1, "\xff\xff\xff\xff\xff\xff", 6) == 0) &&
	     (dlen == 36 || dlen == PADDED_ARPLEN) &&
	    !ws->ws_cipher &&
	    !ws->ws_netip) {
		decrypt_arpreq(ws, wh, rd);
	}

	// we have prga... check if its our stuff being relayed...
	if (ws->ws_pi.pi_len != 0) {
		check_relay(ws, wh, body, dlen);
		return;
	}

	known_clear(clear, &clearsize, NULL, (void*) wh, dlen);
	time_print("Datalen %d Known clear %d\n", dlen, clearsize);

	set_prga(ws, body, &body[4], clear, clearsize);
}
예제 #4
0
static void stuff_for_net(struct wstate *ws, struct ieee80211_frame* wh, int rd)
{
	int type, stype;

	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
	stype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;

	if (type == IEEE80211_FC0_TYPE_DATA &&
	    stype == IEEE80211_FC0_SUBTYPE_DATA) {
		int dlen = rd - sizeof(struct ieee80211_frame);

		if (ws->ws_state == SPOOF_MAC) {
			unsigned char mac[6];
			if (wh->i_fc[1] & IEEE80211_FC1_DIR_TODS) {
				memcpy(mac, wh->i_addr3, 6);
			} else if (wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS) {
				memcpy(mac, wh->i_addr1, 6);
			} else assert(0);

			if (mac[0] == 0xff || mac[0] == 0x1)
				return;

			memcpy(ws->ws_mymac, mac, 6);
			time_print("Trying to use MAC=(%s)\n",
				   mac2str(ws->ws_mymac));
			ws->ws_state = FOUND_VICTIM;
			return;
		}

		// wep data!
		if ( (wh->i_fc[1] & IEEE80211_FC1_WEP) && dlen > (4+8+4)) {
			got_wep(ws, wh, rd);
		}
	}
}
예제 #5
0
static void got_ip(struct wstate *ws)
{
	unsigned char ip[4];
	int i;
	struct in_addr *in = (struct in_addr*) ip;
	char *ptr;

	for (i = 0; i < 4; i++)
		ip[i] = ws->ws_cipher[8+8+6+i] ^ ws->ws_dpi.pi_prga[8+8+6+i];

	assert(!ws->ws_netip);
	ws->ws_netip = malloc(16);
	if(!ws->ws_netip) {
		perror("malloc()");
		exit(1);
	}

	memset(ws->ws_netip, 0, 16);
	strncpy(ws->ws_netip, inet_ntoa(*in), 16-1);

	time_print("Got IP=(%s)\n", ws->ws_netip);
	memset(ws->ws_myip, 0, sizeof(ws->ws_myip));
	strncpy(ws->ws_myip, ws->ws_netip, sizeof(ws->ws_myip)-1);

	ptr = strchr(ws->ws_myip, '.');
	assert(ptr);
	ptr = strchr(ptr+1, '.');
	assert(ptr);
	ptr = strchr(ptr+1, '.');
	assert(ptr);
	strncpy(ptr+1,"123", 3);

	time_print("My IP=(%s)\n", ws->ws_myip);

	/* clear decrypt state */
	free(ws->ws_dpi.pi_prga);
	free(ws->ws_cipher);
	ws->ws_cipher = 0;
	ws->ws_clen = 0;
	memset(&ws->ws_dpi, 0, sizeof(ws->ws_dpi));
	memset(&ws->ws_dfs, 0, sizeof(ws->ws_dfs));
}
예제 #6
0
static void decrypt_arpreq(struct wstate *ws, struct ieee80211_frame* wh,
			   int rd)
{
	unsigned char* body;
	int bodylen;
	unsigned char clear[36];
	unsigned char* ptr;
	struct arphdr* h;
	int i;

	body = (unsigned char*) wh+sizeof(*wh);
	ptr = clear;

	// calculate clear-text
	memcpy(ptr, S_LLC_SNAP_ARP, sizeof(S_LLC_SNAP_ARP)-1);
	ptr += sizeof(S_LLC_SNAP_ARP) -1;

	h = (struct arphdr*)ptr;
	h->ar_hrd = htons(ARPHRD_ETHER);
        h->ar_pro = htons(ETHERTYPE_IP);
        h->ar_hln = 6;
        h->ar_pln = 4;
        h->ar_op = htons(ARPOP_REQUEST);
	ptr += sizeof(*h);

	memcpy(ptr, wh->i_addr3, 6);

	bodylen = rd - sizeof(*wh) - 4 - 4;
	ws->ws_clen = bodylen;
	ws->ws_cipher = (unsigned char*) malloc(ws->ws_clen);
	if (!ws->ws_cipher) {
		perror("malloc()");
		exit(1);
	}
	ws->ws_dpi.pi_prga = (unsigned char*) malloc(ws->ws_clen);
	if (!ws->ws_dpi.pi_prga) {
		perror("malloc()");
		exit(1);
	}


	memcpy(ws->ws_cipher, &body[4], ws->ws_clen);
	memcpy(ws->ws_dpi.pi_iv, body, 3);

	memset(ws->ws_dpi.pi_prga, 0, ws->ws_clen);
	for(i = 0; i < (8+8+6); i++) {
		ws->ws_dpi.pi_prga[i] = ws->ws_cipher[i] ^
						clear[i];
	}

	ws->ws_dpi.pi_len = i;
	time_print("Got ARP request from (%s)\n", mac2str(wh->i_addr3));
}
예제 #7
0
void time_main_test(void)
{
    int i;

    time_start();

    for(i=0; i<FUNC_EXEC_TIME; i++)
    //timt_test();


    time_stop();
    time_print();
}
예제 #8
0
static void inject(struct wif *wi, void *buf, int len)
{
	int rc;

	rc = wi_write(wi, buf, len, NULL);

	if(rc == -1) {
		perror("writev()");
		exit(1);
	}
	if (rc != len) {
		time_print("ERROR: Packet length changed while transmitting (%d instead of %d).\n", rc, len);
		exit(1);
	}
}
예제 #9
0
static void proc_ctl(struct wstate *ws, int stype)
{
	if (stype == IEEE80211_FC0_SUBTYPE_ACK) {
		ws->ws_waiting_ack = 0;
		return;

	} else if (stype == IEEE80211_FC0_SUBTYPE_RTS) {
		return;

	} else if (stype == IEEE80211_FC0_SUBTYPE_CTS) {
		return;
	}

	time_print ("got CTL=%x\n", stype);
}
예제 #10
0
/* Expects host-endian arguments, but returns little-endian seq. */
static unsigned short fnseq(unsigned short fn, unsigned short seq)
{
        unsigned short r = 0;

        if(fn > 15) {
                time_print("too many fragments (%d)\n", fn);
                exit(1);
        }

        r = fn;

        r |=  ( (seq % 4096) << IEEE80211_SEQ_SEQ_SHIFT);

        return htole16(r);
}
예제 #11
0
static void alarm_thread(void) {
    msg_t m;

    struct tm time;

    time.tm_sec = 1;
    time.tm_min = 2;
    time.tm_hour = 3;

    int active = 0;

    while(1) {
        msg_receive(&m);
        switch (m.type) {
            case MSG_ACTIVATE:
                {
                    time_print(&time);
                    if (active) {
                    } else {
                    }
                    break;
                }
            case MSG_DEACTIVATE:
                  {
                      break;
                  }
            case MSG_BUTTON_HASH:
                  {
                      if (active) {
                          active = 0;
                          display_symbol(LCD_ICON_ALARM, SEG_OFF);
                      } else {
                          active = 1;
                          display_symbol(LCD_ICON_ALARM, SEG_ON);
                      }
                      break;
                  }
            default: 
                  {
                      printf("def alarm\n");
                  }
        }
    }
}
예제 #12
0
파일: amq.c 프로젝트: 2trill2spill/freebsd
static void
show_mapinfo(amq_map_info_list *ml, enum show_opt e, int *nwid, int *wwid)
{
  u_int i;

  switch (e) {

  case Calc:
    {
      for (i = 0; i < ml->amq_map_info_list_len; i++) {
	amq_map_info *mi = &ml->amq_map_info_list_val[i];
	int nw = strlen(mi->mi_name);
	int ww = strlen(mi->mi_wildcard ? mi->mi_wildcard : "(null");
	if (nw > *nwid)
	  *nwid = nw;
	if (ww > *wwid)
	  *wwid = ww;
      }
    }
  break;

  case Full:
    {
      printf("%-*.*s %-*.*s %-8.8s %-7.7s %-7.7s %-7.7s %-s Modified\n",
	*nwid, *nwid, "Name",
	*wwid, *wwid, "Wild",
	"Flags", "Refcnt", "Entries", "Reloads", "Stat");
      for (i = 0; i < ml->amq_map_info_list_len; i++) {
	amq_map_info *mi = &ml->amq_map_info_list_val[i];
        printf("%-*.*s %*.*s %-8x %-7d %-7d %-7d %s ",
	       *nwid, *nwid, mi->mi_name,
	       *wwid, *wwid, mi->mi_wildcard,
	       mi->mi_flags, mi->mi_refc, mi->mi_nentries, mi->mi_reloads,
	       mi->mi_up == -1 ? "root" : (mi->mi_up ? "  up" : "down"));
        time_print(mi->mi_modify);
	fputc('\n', stdout);
      }
    }
  break;

  default:
    break;
  }
}
예제 #13
0
static void kill_crack(struct wstate *ws)
{
	if (ws->ws_crack_pid == 0)
		return;

	printf("\n");
	time_print("Stopping crack PID=%d\n", ws->ws_crack_pid);

	// XXX doesn't return -1 for some reason! [maybe on my box... so it
	// might be buggy on other boxes...]
	if (kill(ws->ws_crack_pid, SIGINT) == -1) {
#if 0
		perror("kill()");
		exit(1);
#endif
	}

	ws->ws_crack_pid = 0;

	check_key(ws);
}
예제 #14
0
static void cleanup(int x)
{
	struct wstate *ws = get_ws();

	printf("\n");
	time_print("Dying...\n");

	if (x) {} /* XXX unused */

	if (ws->ws_fd)
		close(ws->ws_fd);

	kill_crack(ws);

	if (ws->ws_wi)
		wi_close(ws->ws_wi);

	if(ws->ws_ssid)
		free(ws->ws_ssid);

	exit(0);
}
예제 #15
0
static void check_relay(struct wstate *ws, struct ieee80211_frame *wh,
			unsigned char *body, int dlen)
{
	// looks like it...
	if ((wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS) &&
	    (memcmp(wh->i_addr3, ws->ws_mymac, 6) == 0) &&
	    (memcmp(wh->i_addr1, "\xff\xff\xff\xff\xff\xff", 6) == 0) &&
	    dlen == ws->ws_fs.fs_len) {

//		printf("I fink AP relayed it...\n");
		set_prga(ws, body, &body[4], ws->ws_fs.fs_data, dlen);
		free(ws->ws_fs.fs_data);
		ws->ws_fs.fs_data = 0;
		ws->ws_fs.fs_waiting_relay = 0;
	}

	// see if we get the multicast stuff of when decrypting
	if ((wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS) &&
	    (memcmp(wh->i_addr3, ws->ws_mymac, 6) == 0) &&
	    (memcmp(wh->i_addr1, MCAST_PREF, 5) == 0) &&
	    dlen == 36) {

		unsigned char pr = wh->i_addr1[5];

		printf("\n");
		time_print("Got clear-text byte: %d\n",
		ws->ws_cipher[ws->ws_dpi.pi_len-1] ^ pr);

		ws->ws_dpi.pi_prga[ws->ws_dpi.pi_len-1] = pr;
		ws->ws_dpi.pi_len++;
		ws->ws_dfs.fs_waiting_relay = 1;

		// ok we got the ip...
		if (ws->ws_dpi.pi_len == 26+1) {
			got_ip(ws);
		}
	}
}
예제 #16
0
static void check_key(struct wstate *ws)
{
	char buf[1024];
	int fd;
	int rd;
	struct timeval now;

	fd = open(KEY_FILE, O_RDONLY);

	if (fd == -1) {
		return;
	}

	rd = read(fd, buf, sizeof(buf) -1);
	if (rd == -1) {
		perror("read()");
		exit(1);
	}

	buf[rd] = 0;

	close(fd);

	printf ("\n\n");
	time_print("KEY=(%s)\n", buf);

	if (gettimeofday(&now, NULL) == -1) {
		perror("gettimeofday()");
		exit(1);
	}

	printf ("Owned in %.02f minutes\n",
		((double) now.tv_sec - ws->ws_real_start.tv_sec)/60.0);

	cleanup(0);
	exit(0);
}
예제 #17
0
static void log_wep(struct wstate *ws, struct ieee80211_frame* wh, int len)
{
	int rd;
	struct pcap_pkthdr pkh;
	struct timeval tv;
	unsigned char *body = (unsigned char*) (wh+1);

	memset(&pkh, 0, sizeof(pkh));
	pkh.caplen = pkh.len = len;
	if (gettimeofday(&tv, NULL) == -1)
		err(1, "gettimeofday()");
	pkh.tv_sec = tv.tv_sec;
	pkh.tv_usec = tv.tv_usec;
	if (write(ws->ws_fd, &pkh, sizeof(pkh)) != sizeof(pkh))
		err(1, "write()");

	rd = write(ws->ws_fd, wh, len);

	if (rd == -1) {
		perror("write()");
		exit(1);
	}
	if (rd != len) {
		time_print("short write %d out of %d\n", rd, len);
		exit(1);
	}

#if 0
	if (fsync(ws->ws_fd) == -1) {
		perror("fsync()");
		exit(1);
	}
#endif

	memcpy(ws->ws_iv, body, 3);
	ws->ws_packets++;
}
예제 #18
0
static void set_prga(struct wstate *ws, unsigned char* iv,
		     unsigned char* cipher, unsigned char* clear, int len)
{
	int i;
	int fd;

	if (ws->ws_pi.pi_len != 0)
		free(ws->ws_pi.pi_prga);

	ws->ws_pi.pi_prga = (unsigned char*) malloc(len);
	if (!ws->ws_pi.pi_prga) {
		perror("malloc()");
		exit(1);
	}

	ws->ws_pi.pi_len = len;
	memcpy(ws->ws_pi.pi_iv, iv, 3);

	for (i = 0; i < len; i++) {
		ws->ws_pi.pi_prga[i] =  ( cipher ? (clear[i] ^ cipher[i]) :
				 	        clear[i]);
	}

	time_print("Got %d bytes of prga IV=(%.02x:%.02x:%.02x) PRGA=",
	       ws->ws_pi.pi_len, ws->ws_pi.pi_iv[0], ws->ws_pi.pi_iv[1],
	       ws->ws_pi.pi_iv[2]);
	hexdump(ws->ws_pi.pi_prga, ws->ws_pi.pi_len);

	if (!cipher)
		return;

	fd = open(PRGA_FILE, O_WRONLY | O_CREAT,
		  S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

	if (fd == -1) {
		perror("open()");
		exit(1);
	}

	i = write(fd, ws->ws_pi.pi_iv, 3);
	if (i == -1) {
		perror("write()");
		exit(1);
	}
	if (i != 3) {
		printf("Wrote %d out of %d\n", i, 3);
		exit(1);
	}

	i = write(fd, ws->ws_pi.pi_prga, ws->ws_pi.pi_len);
	if (i == -1) {
		perror("write()");
		exit(1);
	}
	if (i != ws->ws_pi.pi_len) {
		printf("Wrote %d out of %d\n", i, ws->ws_pi.pi_len);
		exit(1);
	}

	close(fd);
}
예제 #19
0
파일: log.c 프로젝트: hajuuk/R7000
/* va_list version of zlog. */
void
vzlog (struct zlog *zl, int priority, const char *format, va_list *args)
{
  /* If zlog is not specified, use default one. */
  if (zl == NULL)
    zl = zlog_default;

  /* When zlog_default is also NULL, use stderr for logging. */
  if (zl == NULL)
    {
      time_print (stderr);
      fprintf (stderr, "%s: ", "unknown");
      vfprintf (stderr, format, args[ZLOG_NOLOG_INDEX]);
      fprintf (stderr, "\n");
      fflush (stderr);

      /* In this case we return at here. */
      return;
    }

  /* only log this information if it has not been masked out */
  if ( priority > zl->maskpri )
    return ;
		
  /* Syslog output */
  if (zl->flags & ZLOG_SYSLOG)
    vsyslog (priority, format, args[ZLOG_SYSLOG_INDEX]);

  /* File output. */
  if (zl->flags & ZLOG_FILE)
    {
      time_print (zl->fp);
      if (zl->record_priority) fprintf (zl->fp, "%s: ", zlog_priority[priority]);
      fprintf (zl->fp, "%s: ", zlog_proto_names[zl->protocol]);
      vfprintf (zl->fp, format, args[ZLOG_FILE_INDEX]);
      fprintf (zl->fp, "\n");
      fflush (zl->fp);
    }

  /* stdout output. */
  if (zl->flags & ZLOG_STDOUT)
    {
      time_print (stdout);
      if (zl->record_priority) fprintf (stdout, "%s: ", zlog_priority[priority]);
      fprintf (stdout, "%s: ", zlog_proto_names[zl->protocol]);
      vfprintf (stdout, format, args[ZLOG_STDOUT_INDEX]);
      fprintf (stdout, "\n");
      fflush (stdout);
    }

  /* stderr output. */
  if (zl->flags & ZLOG_STDERR)
    {
      time_print (stderr);
      if (zl->record_priority) fprintf (stderr, "%s: ", zlog_priority[priority]);
      fprintf (stderr, "%s: ", zlog_proto_names[zl->protocol]);
      vfprintf (stderr, format, args[ZLOG_STDERR_INDEX]);
      fprintf (stderr, "\n");
      fflush (stderr);
    }

  /* Terminal monitor. */
  vty_log (zlog_proto_names[zl->protocol], format, args[ZLOG_NOLOG_INDEX]);
}
예제 #20
0
파일: main.c 프로젝트: oohal/tp2
int main(int argc, char **argv)
{
	FILE *bin, *yaml;

	if(argc < 2) {
		fprintf(stderr, "Usage: %s <binfile>\n", argv[0]);
		return -1;
	}

	bin = fopen(argv[1], "rb");
	if(!bin) {
		fprintf(stderr, "Unable to open file: %s\n", argv[1]);
		return -1;
	}

    char *filename = strdup(argv[1]);
    int len = strlen(filename);
	strcpy(filename + len - 3, "yml");

	yaml = fopen(filename, "w");
    if(!yaml) {
		fprintf(stderr, "unable to open yaml file '%s' for writing, using \n", argv[2]);
		yaml = stdout;
		return -1;
	}


	/* print the YAML metadata header */

	fputs("metadata:\n", yaml);
	fputs(INDENT, yaml); fputs("team_number: 3\n", yaml);
	fputs("\n", yaml);
	fputs("samples:\n", yaml);

	do {
		uint32_t index, time, date;
		uint16_t accel[3], temp;
		float lat, lng;

		int count = 0;
		                                   // 0 0
		count += fread(&index, 4, 1, bin); // 1 1
		count += fread(&time,  4, 1, bin); // 1 2
		count += fread(&date,  4, 1, bin); // 1 3
		count += fread(&accel, 2, 3, bin); // 3 6
		count += fread(&lat,   4, 1, bin); // 1 7
		count += fread(&lng,   4, 1, bin); // 1 8
		count += fread(&temp,  2, 1, bin); // 1 9

		if(count == 9) { // all items read successfully
			// these are always generated
			fputs(INDENT, yaml); fprintf(yaml, "- temperature: %d\n", temp_convert(temp));
			fputs(INDENT, yaml); accel_print(yaml, accel);

			/* if the high bit is set then we had a fix, so lat
			 * and long coordinates should be generated
			 */

			if(index & (1 << 31)) { // fix flag set
				fputs(INDENT, yaml); time_print(yaml, time, date);

				fputs(INDENT, yaml); fprintf(yaml, "  latitude: %f\n",  gps_correct(lat));
				fputs(INDENT, yaml); fprintf(yaml, "  longitude: %f\n", gps_correct(lng));
			}

			fputs("\n", yaml);
		} else {

		    if(feof(bin)) {
                break;
		    }

			fprintf(stderr, "Error reading file: %s", argv[1]);
			return -1;
		}
	} while( !feof(bin) && !ferror(bin));

	fclose(yaml);
	fclose(bin);

    return 0;
}
예제 #21
0
int main(){
    int i, k;
    int nworkers, totalworkers;
    char cpuCount[20];
    double *a, *b, *c, *d;
    double sums[2000];
    cpu_set_t cpuset;
    TimeData timer;
    double triad_time, copy_time, total = 0;

    nprocessors = sysconf(_SC_NPROCESSORS_CONF);

    nworkers = cilk_spawn get_nworkers();
    totalworkers = cilk_spawn get_totalworkers();

    for (i=0;i<nworkers;i++)
    {
        sums[i] = 0;
    }

    LIKWID_MARKER_INIT;

    cilk_spawn allocate_vector(&a, SIZE);
    cilk_spawn allocate_vector(&b, SIZE);
    cilk_spawn allocate_vector(&c, SIZE);
    cilk_spawn allocate_vector(&d, SIZE);
    cilk_sync;

    for (i=0; i<SIZE; i++) {
        a[i] = 1.0;
        b[i] = 2.0;
        c[i] = 0.0;
        d[i] = 1.0;
    }

    time_start(&timer);
    for (k=0; k<ITER; k++)
    {
        for (i=0;i<nworkers;i++)
        {
            cilk_spawn LIKWID_MARKER_START("copy");
        }
        cilk_sync;
        cilk_for(i=0;i<SIZE;i++)
        {
            c[i] = a[i];
        }
        for (i=0;i<nworkers;i++)
        {
            cilk_spawn LIKWID_MARKER_STOP("copy");
        }
        cilk_sync;
    }
    time_stop(&timer);
    copy_time = time_print(&timer)/(double)ITER;

    time_start(&timer);
    for (k=0; k<ITER; k++)
    {
        for (i=0;i<nworkers;i++)
        {
            cilk_spawn LIKWID_MARKER_START("triad");
        }
        cilk_sync;
        cilk_for(i=0;i<SIZE;i++)
        {
            a[i] = b[i] +  c[i] * d[i];
        }
        for (i=0;i<nworkers;i++)
        {
            cilk_spawn LIKWID_MARKER_STOP("triad");
        }
        cilk_sync;
    }
    time_stop(&timer);
    triad_time = time_print(&timer)/(double)ITER;
    
    printf("Processed %.1f Mbyte at copy benchmark in %.4f seconds: %.2f MByte/s\n",
                        1E-6*(2*SIZE*sizeof(double)),
                        copy_time,
                        1E-6*((2*SIZE*sizeof(double))/copy_time));
    printf("Processed %.1f Mbyte at triad benchmark in %.4f seconds: %.2f MByte/s\n",
                        1E-6*(4*SIZE*sizeof(double)),
                        triad_time,
                        1E-6*((4*SIZE*sizeof(double))/triad_time));

    printf("Main PID %d\n",getpid());
    for (i=0;i<nworkers;i++)
    {
        cilk_spawn show_thread();
    }
    cilk_sync;

    LIKWID_MARKER_CLOSE;
}
예제 #22
0
int main(int argc,char *argv[]){
	//get_mtime("/bassapp/bass2/panzw2/.profile");
	time_print(get_mtime("c:\\boot.ini"));
        return 0;
}
예제 #23
0
static void anal(struct wstate *ws, unsigned char* buf, int rd) // yze
{
	struct ieee80211_frame* wh = (struct ieee80211_frame *) buf;
	int type,stype;
	static int lastseq = -1;
	int seq;
	unsigned short *seqptr;
	int for_us = 0;

	if (rd < 1) {
		time_print("rd=%d\n", rd);
		exit(1);
	}

	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
	stype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;

	// sort out acks
	if (ws->ws_state >= FOUND_VICTIM) {
		// stuff for us
		if (memcmp(wh->i_addr1, ws->ws_mymac, 6) == 0) {
			for_us = 1;
			if (type != IEEE80211_FC0_TYPE_CTL)
				send_ack(ws);
		}
	}

	// XXX i know it aint great...
	seqptr = (unsigned short*)  wh->i_seq;
	seq = (le16toh(*seqptr) & IEEE80211_SEQ_SEQ_MASK) >> IEEE80211_SEQ_SEQ_SHIFT;
	if (seq == lastseq && (wh->i_fc[1] & IEEE80211_FC1_RETRY) &&
	    type != IEEE80211_FC0_TYPE_CTL) {
//		printf("Ignoring dup packet... seq=%d\n", seq);
		return;
	}
	lastseq = seq;

	// management frame
	if (type == IEEE80211_FC0_TYPE_MGT) {
		if(ws->ws_state == FIND_VICTIM) {
			if (stype == IEEE80211_FC0_SUBTYPE_BEACON ||
			    stype == IEEE80211_FC0_SUBTYPE_PROBE_RESP) {

			    	if (get_victim_ssid(ws, wh, rd)) {
			    		return;
				}
			}

		}
	}

	if (ws->ws_state >= FOUND_VICTIM) {
		// stuff for us
		if (for_us) {
			stuff_for_us(ws, wh, rd);
		}

		// stuff in network [even for us]
		if ( ((wh->i_fc[1] & IEEE80211_FC1_DIR_TODS) &&
			  (memcmp(ws->ws_bss, wh->i_addr1, 6) == 0)) ||

			  ((wh->i_fc[1] & IEEE80211_FC1_DIR_FROMDS) &&
			  (memcmp(ws->ws_bss, wh->i_addr2, 6) == 0))
			   ) {
			stuff_for_net(ws, wh, rd);
		}
	}
}
예제 #24
0
static void proc_mgt(struct wstate *ws, int stype, unsigned char *body)
{
	unsigned short * rc;
	unsigned short * sc;
	unsigned int aid;

	if (stype == IEEE80211_FC0_SUBTYPE_DEAUTH) {
		rc = (unsigned short*) body;

		printf("\n");
		time_print("Got deauth=%u\n", le16toh(*rc));
		ws->ws_state = FOUND_VICTIM;
		return;

	} else if (stype == IEEE80211_FC0_SUBTYPE_AUTH) {
		sc = (unsigned short*) body;

		if (ws->ws_state != SENDING_AUTH) /* We didn't ask for it. */
			return;

		if (le16toh(*sc) != 0) {
			time_print("Warning got auth algo=%x\n", le16toh(*sc));
			exit(1);
			return;
		}
		sc++;

		if (le16toh(*sc) != 2) {
			time_print("Warning got auth seq=%x\n", le16toh(*sc));
			return;
		}

		sc++;

		if (le16toh(*sc) == 1) {
			time_print("Auth rejected.  Spoofin mac.\n");
			ws->ws_state = SPOOF_MAC;
			return;

		} else if (le16toh(*sc) == 0) {
			time_print("Authenticated\n");
			ws->ws_state = GOT_AUTH;
			return;

		} else {
			time_print("Got auth %x\n", *sc);
			exit(1);
		}
	}
	else if (stype == IEEE80211_FC0_SUBTYPE_ASSOC_RESP) {
		sc = (unsigned short*) body;
		sc++; // cap

		if (ws->ws_state != SENDING_ASSOC) /* We didn't ask for it. */
			return;

		if (le16toh(*sc) == 0) {
			sc++;
			aid = le16toh(*sc) & 0x3FFF;
			time_print("Associated (ID=%x)\n", aid);
			ws->ws_state = GOT_ASSOC;
			return;

		} else if (le16toh(*sc) == 12 || le16toh(*sc) == 1) {
			time_print("Assoc rejected..."
				   " trying to spoof mac.\n");
			ws->ws_state = SPOOF_MAC;
			return;
		} else {
			time_print("got assoc %d\n", le16toh(*sc));
			exit(1);
		}

	} else if (stype == IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
		return;
	}

	time_print("\nGOT MAN=%x\n", stype);
	exit(1);
}
예제 #25
0
int main(void)
{
  unsigned int sec_time;
  unsigned long prev_total_sys_time;
  unsigned long count_sys_time;

  TIME now;
  key_status key;

  char flag = 0;

  ROMEMU();

  sys_time = 0;
  total_sys_time = 0;
  prev_total_sys_time = 0;
  count_sys_time = 0;
  sec_time = 0;

  timer_init();
  timer_set(0,INT1MS);
  timer_start(0);

  lcd_init();

  time_init(&now);

  key_init(&key);

  lcd_cursor(0,0);
  time_print(now);

  ENINT();

  while (1) {

	if(sys_time>=1000)
	{
	  sec_time++;
	  sys_time = 0;
	}

	key_scan(&key);

	switch(key_press_check(&key))
	{
	case '0':
	  if(flag==1)
	  {
	    count_sys_time = time_to_msec(now);
		prev_total_sys_time = total_sys_time;
		flag = 0;
	  }
	  else
	  {
	    flag = 1;
	  }
	  break;
	case '6':
	  if(flag==1)
	  {
		if(now.second<60)
		  now.second += 1;
		count_sys_time=time_to_msec(now);
	  }
	  break;
	case '9':
	  if(flag==1)
	  {
		if(now.second>0)
		  now.second -= 1;
		count_sys_time=time_to_msec(now);
	  }
	  break;
	case '5':
	  if(flag==1)
	  {
		if(now.minute<60)
		  now.minute += 1;
		count_sys_time=time_to_msec(now);
	  }
	  break;
	case '8':
	  if(flag==1)
	  {
		if(now.minute>0)
		  now.minute -= 1;
		count_sys_time=time_to_msec(now);
	  }
	  break;
	case '4':
	  if(flag==1)
	  {
		if(now.hour<23)
		now.hour += 1;
		count_sys_time=time_to_msec(now);
	  }
	  break;
	case '7':
	  if(flag==1)
	  {
		if(now.hour>0)
		  now.hour -= 1;
		count_sys_time=time_to_msec(now);
	  }
	  break;
	}

	if(flag==0)
	{
	  count_sys_time += total_sys_time - prev_total_sys_time;
	  prev_total_sys_time = total_sys_time;
	}

	lcd_cursor(0,0);
	time_msec_to(&now,count_sys_time);
	time_print(now);
  }
  return 1;
}
예제 #26
0
static int get_victim_ssid(struct wstate *ws, struct ieee80211_frame* wh,
			   int len)
{
	unsigned char* ptr;
	int x;
	int gots = 0, gotc = 0;

	if (len <= (int) sizeof(*wh)) {
		time_print("Warning: short packet in get_victim_ssid()\n");
		return 0;
	}

	ptr = (unsigned char*)wh + sizeof(*wh);
	len -= sizeof(*wh);

	// only wep baby
	if ( !(IEEE80211_BEACON_CAPABILITY(ptr) & IEEE80211_CAPINFO_PRIVACY)) {
		return 0;
	}

	// we want a specific victim
	if (ws->ws_victim_mac) {
		if (memcmp(wh->i_addr3, ws->ws_victim_mac, 6) != 0)
			return 0;
	}

	// beacon header
	x = 8 + 2 + 2;
	if (len <= x) {
		time_print("Warning short.\n");
		return 0;
	}

	ptr += x;
	len -= x;

	// SSID
	while(len > 2) {
		int eid, elen;

		eid = *ptr;
		ptr++;
		elen = *ptr;
		ptr++;
		len -= 2;

		if (len < elen) {
			time_print("Warning short....\n");
			return 0;
		}

		// ssid
		if (eid == 0) {
			if (ws->ws_ssid)
				free(ws->ws_ssid);

			ws->ws_ssid = (char*) malloc(elen + 1);
			if (!ws->ws_ssid) {
				perror("malloc()");
				exit(1);
			}

			memcpy(ws->ws_ssid, ptr, elen);
			ws->ws_ssid[elen] = 0;
			gots = 1;

		}
		// chan
		else if(eid == 3) {
			if( elen != 1) {
				time_print("Warning len of chan not 1\n");
				return 0;
			}

			ws->ws_apchan = *ptr;
			gotc = 1;
		}

		ptr += elen;
		len -= elen;
	}

	if (gots && gotc) {
		memcpy(ws->ws_bss, wh->i_addr3, 6);
		set_chan(ws, ws->ws_apchan);
		ws->ws_state = FOUND_VICTIM;
		time_print("Found SSID(%s) BSS=(%s) chan=%d\n",
		       ws->ws_ssid, mac2str(ws->ws_bss), ws->ws_apchan);
		return 1;
	}
	return 0;
}
예제 #27
0
int main(int argn, char** argc)
{
    int err, i ,j;
    int numCPUs = 0;
    int gid;
    DATATYPE *a,*b,*c,*d;
    TimeData timer;
    double triad_time, copy_time, scale_time, stream_time;
    char estr[1024];
    double result, scalar = 3.0;
    char* ptr;

    if (argn != 3)
    {
        printf("Usage: %s <cpustr> <events>\n", argc[0]);
        return 1;
    }

    strcpy(estr, argc[2]);

    allocate_vector(&a, SIZE);
    allocate_vector(&b, SIZE);
    allocate_vector(&c, SIZE);
    allocate_vector(&d, SIZE);

    err = topology_init();
    if (err < 0)
    {
        printf("Failed to initialize LIKWID's topology module\n");
        return 1;
    }
    CpuTopology_t topo = get_cpuTopology();
    affinity_init();
    int* cpus = (int*)malloc(topo->numHWThreads * sizeof(int));
    if (!cpus)
        return 1;
    numCPUs = cpustr_to_cpulist(argc[1], cpus, topo->numHWThreads);
    omp_set_num_threads(numCPUs);
    err = perfmon_init(numCPUs, cpus);
    if (err < 0)
    {
        printf("Failed to initialize LIKWID's performance monitoring module\n");
        affinity_finalize();
        topology_finalize();
        return 1;
    }
    gid = perfmon_addEventSet(estr);
    if (gid < 0)
    {
        printf("Failed to add event string %s to LIKWID's performance monitoring module\n", estr);
        perfmon_finalize();
        affinity_finalize();
        topology_finalize();
        return 1;
    }

    err = perfmon_setupCounters(gid);
    if (err < 0)
    {
        printf("Failed to setup group %d in LIKWID's performance monitoring module\n", gid);
        perfmon_finalize();
        affinity_finalize();
        topology_finalize();
        return 1;
    }

#ifdef _OPENMP
    printf(HLINE);
#pragma omp parallel
    {
#pragma omp master
    {
        printf ("Number of Threads requested = %i\n",omp_get_num_threads());
    }
    likwid_pinThread(cpus[omp_get_thread_num()]);
    printf ("Thread %d running on processor %d ....\n",omp_get_thread_num(),sched_getcpu());
    }
#endif

#pragma omp parallel for
    for (int j=0; j<SIZE; j++) {
        a[j] = 1.0;
        b[j] = 2.0;
        c[j] = 0.0;
        d[j] = 1.0;
    }

    err = perfmon_startCounters();
    if (err < 0)
    {
        printf("Failed to start counters for group %d for thread %d\n",gid, (-1*err)-1);
        perfmon_finalize();
        topology_finalize();
        return 1;
    }
    time_start(&timer);
#pragma omp parallel
    {
        for (int k=0; k<ITER; k++)
        {
            LIKWID_MARKER_START("copy");
#pragma omp for
            for (int j=0; j<SIZE; j++)
            {
                c[j] = a[j];
            }
            LIKWID_MARKER_STOP("copy");
        }
    }
    time_stop(&timer);
    err = perfmon_stopCounters();
    copy_time = time_print(&timer)/(double)ITER;
    if (err < 0)
    {
        printf("Failed to stop counters for group %d for thread %d\n",gid, (-1*err)-1);
        perfmon_finalize();
        topology_finalize();
        return 1;
    }

    printf("Processed %.1f Mbyte at copy benchmark in %.4f seconds: %.2f MByte/s\n",
                        1E-6*(2*SIZE*sizeof(DATATYPE)),
                        copy_time,
                        1E-6*((2*SIZE*sizeof(DATATYPE))/copy_time));

    ptr = strtok(estr,",");
    j = 0;
    while (ptr != NULL)
    {
        for (i = 0;i < numCPUs; i++)
        {
            result = perfmon_getResult(gid, j, cpus[i]);
            printf("Measurement result for event set %s at CPU %d: %f\n", ptr, cpus[i], result);
        }
        ptr = strtok(NULL,",");
        j++;
    }
    strcpy(estr, argc[2]);
    perfmon_setupCounters(gid);

    err = perfmon_startCounters();
    if (err < 0)
    {
        printf("Failed to start counters for group %d for thread %d\n",gid, (-1*err)-1);
        perfmon_finalize();
        topology_finalize();
        return 1;
    }
    time_start(&timer);
#pragma omp parallel
    {
        for (int k=0; k<ITER; k++)
        {
            LIKWID_MARKER_START("scale");
#pragma omp for
            for (int j=0; j<SIZE; j++)
            {
                b[j] = scalar*c[j];
            }
            LIKWID_MARKER_STOP("scale");
        }
    }
    time_stop(&timer);
    err = perfmon_stopCounters();
    scale_time = time_print(&timer)/(double)ITER;
    if (err < 0)
    {
        printf("Failed to stop counters for group %d for thread %d\n",gid, (-1*err)-1);
        perfmon_finalize();
        topology_finalize();
        return 1;
    }

    printf("Processed %.1f Mbyte at scale benchmark in %.4f seconds: %.2f MByte/s\n",
                        1E-6*(2*SIZE*sizeof(DATATYPE)),
                        copy_time,
                        1E-6*((2*SIZE*sizeof(DATATYPE))/copy_time));

    ptr = strtok(estr,",");
    j = 0;
    while (ptr != NULL)
    {
        for (i = 0;i < numCPUs; i++)
        {
            result = perfmon_getResult(gid, j, cpus[i]);
            printf("Measurement result for event set %s at CPU %d: %f\n", ptr, cpus[i], result);
        }
        ptr = strtok(NULL,",");
        j++;
    }
    strcpy(estr, argc[2]);
    perfmon_setupCounters(gid);
    err = perfmon_startCounters();
    if (err < 0)
    {
        printf("Failed to start counters for group %d for thread %d\n",gid, (-1*err)-1);
        perfmon_finalize();
        topology_finalize();
        return 1;
    }
    time_start(&timer);
#pragma omp parallel
    {
        for (int k=0; k<ITER; k++)
        {
            LIKWID_MARKER_START("stream");
#pragma omp for
            for (int j=0; j<SIZE; j++)
            {
                c[j] = a[j] + b[j];
            }
            LIKWID_MARKER_STOP("stream");
        }
    }
    time_stop(&timer);
    err = perfmon_stopCounters();
    stream_time = time_print(&timer)/(double)ITER;
    if (err < 0)
    {
        printf("Failed to stop counters for group %d for thread %d\n",gid, (-1*err)-1);
        perfmon_finalize();
        topology_finalize();
        return 1;
    }

    printf("Processed %.1f Mbyte at stream benchmark in %.4f seconds: %.2f MByte/s\n",
                        1E-6*(2*SIZE*sizeof(DATATYPE)),
                        copy_time,
                        1E-6*((2*SIZE*sizeof(DATATYPE))/copy_time));

    ptr = strtok(estr,",");
    j = 0;
    while (ptr != NULL)
    {
        for (i = 0;i < numCPUs; i++)
        {
            result = perfmon_getResult(gid, j, cpus[i]);
            printf("Measurement result for event set %s at CPU %d: %f\n", ptr, cpus[i], result);
        }
        ptr = strtok(NULL,",");
        j++;
    }
    strcpy(estr, argc[2]);
    perfmon_setupCounters(gid);
    err = perfmon_startCounters();
    if (err < 0)
    {
        printf("Failed to start counters for group %d for thread %d\n",gid, (-1*err)-1);
        perfmon_finalize();
        topology_finalize();
        return 1;
    }
    time_start(&timer);
#pragma omp parallel
    {
        for (int k=0; k<ITER; k++)
        {

            LIKWID_MARKER_START("triad");
#pragma omp for
            for (int j=0; j<SIZE; j++)
            {
                a[j] = b[j] +  c[j] * scalar;
            }
            LIKWID_MARKER_STOP("triad");
        }
    }
    time_stop(&timer);
    err = perfmon_stopCounters();
    triad_time = time_print(&timer)/(double)ITER;
    if (err < 0)
    {
        printf("Failed to stop counters for group %d for thread %d\n",gid, (-1*err)-1);
        perfmon_finalize();
        topology_finalize();
        return 1;
    }



    printf("Processed %.1f Mbyte at triad benchmark in %.4f seconds: %.2f MByte/s\n",
                        1E-6*(4*SIZE*sizeof(DATATYPE)),
                        triad_time,
                        1E-6*((4*SIZE*sizeof(DATATYPE))/triad_time));
    ptr = strtok(estr,",");
    j = 0;
    while (ptr != NULL)
    {
        for (i = 0;i < numCPUs; i++)
        {
            result = perfmon_getResult(gid, j, cpus[i]);
            printf("Measurement result for event set %s at CPU %d: %f\n", ptr, cpus[i], result);
        }
        ptr = strtok(NULL,",");
        j++;
    }

    perfmon_finalize();
    affinity_finalize();
    topology_finalize();
    return 0;
}
예제 #28
0
파일: edax.c 프로젝트: markkings/reversi
/**
 * @brief Loop event.
 * @param ui user interface.
 */
void ui_loop_edax(UI *ui)
{
	char *cmd = NULL, *param = NULL;
	Play *play = ui->play;
	char book_file[FILENAME_MAX];
	unsigned long long histogram[129][65];
	int repeat = options.repeat;

	histogram_init(histogram);

	// loop forever
	for (;;) {
		errno = 0;

		if (options.verbosity) {
			putchar('\n');
			play_print(play, stdout);
			if (play_is_game_over(play)) printf("\n*** Game Over ***\n");
			putchar('\n');
		}

		if (log_is_open(edax_log)) {
			putc('\n', edax_log->f);
			play_print(play, edax_log->f);
			if (play_is_game_over(play)) fputs("\n*** Game Over ***\n", edax_log->f);
			putc('\n', edax_log->f);
		}

		// edax turn ? (automatic play mode)
		if (!ui_event_exist(ui) && !play_is_game_over(play) && (ui->mode == !play->player || ui->mode == 2)) {
			putchar('\n');
			play_go(play, true);
			printf("\nEdax plays "); move_print(play_get_last_move(play)->x, 0, stdout); putchar('\n');
			if (ui->mode != 2) play_ponder(play);

		// proceed by reading a command
		} else {

			/* automatic rules after a game over*/
			if (play_is_game_over(play)) {
				if (options.auto_store) play_store(play);
				if (options.auto_swap && ui->mode < 2) ui->mode = !ui->mode;
				if (options.repeat && repeat > 1) {
					--repeat;
					play_new(play);
					continue;
				}
				if (options.auto_quit) {
					return;
				}
				if (options.auto_start) {
					play_new(play);
					continue;
				}
			}

			putchar('>'); fflush(stdout);
			ui_event_wait(ui, &cmd, &param);
			log_print(edax_log, "cmd=\"%s\" ; param=\"%s\"\n", cmd, param);
			putchar('\n');

			if (cmd == NULL) {
				warn("unexpected null command?\n");
				continue;
			}

			// skip empty lines or commented lines
			if (*cmd == '\0' || *cmd == '#') {
			
			// help
			} else if (strcmp(cmd, "help") == 0 || strcmp(cmd, "?") == 0) {
				if (*param == '\0' || strcmp(param, "options") == 0) help_options();
				if (*param == '\0' || strcmp(param, "commands") == 0) help_commands();
				if (*param == '\0' || strcmp(param, "book") == 0) help_book();
				if (*param == '\0' || strcmp(param, "base") == 0) help_base();
				if (*param == '\0' || strcmp(param, "test") == 0) help_test(); 

			// new game from standard position
			} else if (strcmp(cmd, "i") == 0 || strcmp(cmd, "init") == 0) {
				board_init(play->initial_board);
				play_new(play);

			// new game from personnalized position
			} else if ((strcmp(cmd, "n") == 0 || strcmp(cmd, "new") == 0) && *param == '\0') {
				play_new(play);

			// open a saved game
			} else if (strcmp(cmd, "o") == 0 || strcmp(cmd, "open") == 0 || strcmp(cmd, "load") == 0) {
				play_load(play, param);

			// save a game
			} else if (strcmp(cmd, "s") == 0 || strcmp(cmd, "save") == 0) {
				play_save(play, param);

			// quit
			} else if (strcmp(cmd, "quit") == 0 || strcmp(cmd, "q") == 0 || strcmp(cmd, "exit") == 0) {
				free(cmd); free(param);
				return;

			} else if (!options.auto_quit && (strcmp(cmd, "eof") == 0 && (ui->mode != 2 || play_is_game_over(play)))){
				free(cmd); free(param);
				return;

			// undo last move
			} else if (strcmp(cmd, "u") == 0 || strcmp(cmd, "undo") == 0) {
				play_undo(play);
				if (ui->mode == 0 || ui->mode == 1) play_undo(play);

			// redo last move
			} else if (strcmp(cmd, "r") == 0 || strcmp(cmd, "redo") == 0) {
				play_redo(play);
				if (ui->mode == 0 || ui->mode == 1) play_undo(play);

			// mode
			} else if (strcmp(cmd, "m") == 0 || strcmp(cmd, "mode") == 0) {
				ui->mode = string_to_int(param, 3);

			// analyze a game
			} else if (strcmp(cmd, "a") == 0 || strcmp(cmd, "analyze") == 0 || strcmp(cmd, "analyse") == 0) {
				play_analyze(play, string_to_int(param, play->n_game));

			// set a new initial position
			} else if (strcmp(cmd, "setboard") == 0) {
				play_set_board(play, param);

			// vertical mirror
			} else if (strcmp(cmd, "vmirror") == 0) {
				play_symetry(play, 2);

			// horizontal mirror
			} else if (strcmp(cmd, "hmirror") == 0) {
				play_symetry(play, 1);

			// rotate
			} else if (strcmp(cmd, "rotate") == 0) {
				int angle = string_to_int(param, 90) % 360;
				if (angle < 0) angle += 360;
				switch (angle) {
				case 90: 
					play_symetry(play, 5);
					break; 
				case 180:
					play_symetry(play, 3);
					break; 
				case 270:
					play_symetry(play, 6);
					break; 
				default:
					warn("Rotate angle should be 90°, 180° or 270°");
					break;
				}

			// direct symetry...
			} else if (strcmp(cmd, "symetry") == 0) {
				int sym = string_to_int(param, 1);
				if (sym < 0 || sym >= 16) warn("symetry parameter should be a number between 0 and 15\n");
				else {
					if (sym & 8) play->player ^= 1;
					play_symetry(play, sym & 7);
				}

			// play a serie of moves
			} else if (strcmp(cmd, "play") == 0) {
				string_to_lowercase(param);
				play_game(play, param);

			// force edax to play an opening
			} else if (strcmp(cmd, "force") == 0) {
				string_to_lowercase(param);
				play_force_init(play, param);

			// solve a set of problems
			} else if (strcmp(cmd, "solve") == 0) {
				char problem_file[FILENAME_MAX + 1], *hard_file;
				hard_file = parse_word(param, problem_file, FILENAME_MAX);
				parse_word(hard_file, hard_file, FILENAME_MAX);
				obf_test(play->search, problem_file, hard_file);
				search_set_observer(play->search, edax_observer);

			// convert a set of problems in a .script file to a .obf file
			} else if (strcmp(cmd, "script-to-obf") == 0) {
				char script_file[FILENAME_MAX + 1], *obf_file;
				obf_file = parse_word(param, script_file, FILENAME_MAX);
				parse_word(obf_file, obf_file, FILENAME_MAX);
				script_to_obf(play->search, script_file, obf_file);
				search_set_observer(play->search, edax_observer);

			} else if (strcmp(cmd, "select-hard") == 0) {
				char full_file[FILENAME_MAX + 1], *hard_file;
				hard_file = parse_word(param, full_file, FILENAME_MAX);
				parse_word(hard_file, hard_file, FILENAME_MAX);
				obf_filter(full_file, hard_file);

			// game/position enumeration
			} else if (strcmp(cmd, "count") == 0) {
				char count_cmd[16], *count_param;
				int depth = 10, size = 8;

				count_param = parse_word(param, count_cmd, 15);
				count_param = parse_int(count_param, &depth); BOUND(depth, 1, 90, "max-ply");
				if (count_param) parse_int(count_param, &size); BOUND(size, 6, 8, "board-size");

				if (strcmp(count_cmd, "games") == 0) { // game enumeration
					quick_count_games(play->board, depth, size);
				} else if (strcmp(count_cmd, "positions") == 0) { // position enumeration
					count_positions(play->board, depth, size);
				} else if (strcmp(count_cmd, "shapes") == 0) { // shape enumeration
					count_shapes(play->board, depth, size);
				} else {
					warn("Unknown count command: \"%s %s\"\n", cmd, param);
				}

			} else if (strcmp(cmd, "perft") == 0) {
				int depth = 14;
				depth = string_to_int(param, 10); BOUND(depth, 1, 90, "max-ply");
				count_games(play->board, depth);
			
			// game/position enumeration
			} else if (strcmp(cmd, "estimate") == 0) {
				int n = 1000;
				n = string_to_int(param, 10); BOUND(n, 1, 2000000000, "max-trials");

				estimate_games(play->board, n);
	
			// seek highest mobility
			} else if (strcmp(cmd, "mobility") == 0) {
				int t = 3600; // 1 hour
				t = string_to_int(param, 10); BOUND(t, 1, 3600*24*365*10, "max time");

				seek_highest_mobility(play->board, t);

			// seek a position
			} else if (strcmp(cmd, "seek") == 0) {
				Board target;
				Line solution;
				
				board_set(&target, param);
				line_init(&solution, play->player);
				
				if (seek_position(&target, play->board, &solution)) {
					printf("Solution found:\n");
					line_print(&solution, 200, " ", stdout);
					putchar('\n');
				}
			
			// bench (a serie of low level tests).
			} else if (strcmp(cmd, "bench") == 0) {
				bench();

			// wtest test the engine against wthor theoretical scores
			} else if (strcmp(cmd, "wtest") == 0) {
				wthor_test(param, play->search);

			// make wthor games played by "Edax (Delorme)" as "Etudes" tournament.
			} else if (strcmp(cmd, "edaxify") == 0) {
				wthor_edaxify(param);

			// wtest test the engine against wthor theoretical scores
			} else if (strcmp(cmd, "weval") == 0) {
				wthor_eval(param, play->search, histogram);
				histogram_print(histogram);
				histogram_stats(histogram);
				histogram_to_ppm("weval.ppm", histogram);

			// go think!
			} else if (strcmp(cmd, "go") == 0) {
				if (play_is_game_over(play)) printf("\n*** Game Over ***\n");
				else {
					play_go(play, true);
					printf("\nEdax plays "); move_print(play_get_last_move(play)->x, 0, stdout); putchar('\n');
				}

			// hint for [n] moves
			} else if (strcmp(cmd, "hint") == 0) {
				int n = string_to_int(param, 1); BOUND(n, 1, 60, "n_moves");
				play_hint(play, n);

			// stop thinking
			} else if (strcmp(cmd, "stop") == 0) {
				ui->mode = 3;

			// user move
			} else if (play_user_move(play, cmd)) {
				printf("\nYou play "); move_print(play_get_last_move(play)->x, 0, stdout); putchar('\n');

			// debug pv
			} else if (strcmp(cmd, "debug-pv") == 0) {
				Move move[1];
				if (parse_move(param, play->board, move) != param) {
					search_set_board(play->search, play->board, play->player);
					pv_debug(play->search, move, stdout);
				}
			} else if (strcmp(cmd, "options") == 0) {
					options_dump(stdout);
#ifdef __unix__
			} else if (strcmp(cmd, "resources") == 0) {
				struct rusage u;
				long long t;
	 			getrusage(RUSAGE_SELF, &u);
				t = 1000 * u.ru_utime.tv_sec + u.ru_utime.tv_usec / 1000;
				printf("user cpu time: "); time_print(t, false, stdout); printf("\n");	
				t = 1000 * u.ru_stime.tv_sec + u.ru_stime.tv_usec / 1000;
				printf("system cpu time: "); time_print(t, false, stdout); printf("\n");	
				printf("max resident memory: %ld\n", u.ru_maxrss); 
				printf("page fault without I/O: %ld\n", u.ru_minflt); 
				printf("page fault with I/O: %ld\n", u.ru_majflt); 
				printf("number of input: %ld\n", u.ru_inblock); 
				printf("number of output: %ld\n", u.ru_oublock); 
				printf("number of voluntary context switch: %ld\n", u.ru_nvcsw); 
				printf("number of unvoluntary context switch: %ld\n\n", u.ru_nivcsw); 
#endif		
			// opening name
			} else if (strcmp(cmd, "opening") == 0) {
				const char *name;
				name = play_show_opening_name(play, opening_get_english_name);
				if (name == NULL) name = "?";
				puts(name);  

			// opening name in french
			} else if (strcmp(cmd, "ouverture") == 0) {
				const char *name;
				name = play_show_opening_name(play, opening_get_french_name);
				if (name == NULL) name = "?";
				puts(name); 

			// opening book commands
			} else if (strcmp(cmd, "book") == 0 || strcmp(cmd, "b") == 0) {
				char book_cmd[FILENAME_MAX + 1], *book_param;
				int val_1, val_2;
				Book *book = play->book;

				book->search = play->search;
				book->search->options.verbosity = book->options.verbosity;
				book_param = parse_word(param, book_cmd, FILENAME_MAX);
				// store the last played game
				if (strcmp(book_cmd, "store") == 0) {
					play_store(play);

				// turn book usage on
				} else if (strcmp(book_cmd, "on") == 0) { // learn
					options.book_allowed = true;

				// turn book usage off
				} else if (strcmp(book_cmd, "off") == 0) { // learn
					options.book_allowed = false;

				// set book randomness
				} else if (strcmp(book_cmd, "randomness") == 0) { // learn
					val_1 = 0; book_param = parse_int(book_param, &val_1);
					options.book_randomness = val_1;

				// set book depth (until which to learn)
				} else if (strcmp(book_cmd, "depth") == 0) { // learn
					val_1 = 36; book_param = parse_int(book_param, &val_1);
					book->options.n_empties = 61 - val_1;

				// create a new empty book
				} else if (strcmp(book_cmd, "new") == 0) {
					val_1 = 21; book_param = parse_int(book_param, &val_1);
					val_2 = 36;	book_param = parse_int(book_param, &val_2);
					book_free(book) ;
					book_new(book, val_1, 61 - val_2);

				// load an opening book (binary format) from the disc
				} else if (strcmp(book_cmd, "load") == 0 || strcmp(book_cmd, "open") == 0) {
					book_free(book) ;
					parse_word(book_param, book_file, FILENAME_MAX);
					book_load(book, book_file);

				// save an opening book (binary format) to the disc
				} else if (strcmp(book_cmd, "save") == 0) {
					parse_word(book_param, book_file, FILENAME_MAX);
					book_save(book, book_file);

				// import an opening book (text format)
				} else if (strcmp(book_cmd, "import") == 0) {
					book_free(book);
					parse_word(book_param, book_file, FILENAME_MAX);
					book_import(book, book_file);
					book_link(book);
					book_fix(book);
					book_negamax(book);
					book_sort(book);

				// export an opening book (text format)
				} else if (strcmp(book_cmd, "export") == 0) {
					parse_word(book_param, book_file, FILENAME_MAX);
					book_export(book, book_file);

				// merge an opening book to the current one
				} else if (strcmp(book_cmd, "merge") == 0) {
					Book src[1];
					parse_word(book_param, book_file, FILENAME_MAX);
					src->search = play->search;
					book_load(src, book_file);
					book_merge(book, src);
					book_free(src);
					warn("Book needs to be fixed before usage\n");

				// fix an opening book
				} else if (strcmp(book_cmd, "fix") == 0) {
					book_fix(book); // do nothing (or edax is buggy)
					book_link(book); // links nodes
					book_negamax(book); // negamax nodes
					book_sort(book); // sort moves

				// negamax an opening book
				} else if (strcmp(book_cmd, "negamax") == 0) {
					book_negamax(book); // negamax nodes
					book_sort(book); // sort moves

				// check and correct solved positions of the book
				} else if (strcmp(book_cmd, "correct") == 0) {
					book_correct_solved(book); // do nothing (or edax is buggy)
					book_fix(book); // do nothing (or edax is buggy)
					book_link(book); // links nodes
					book_negamax(book); // negamax nodes
					book_sort(book); // sort moves

				// prune an opening book
				} else if (strcmp(book_cmd, "prune") == 0) {
					book_prune(book); // remove unreachable lines.
					book_fix(book); // do nothing (or edax is buggy)
					book_link(book); // links nodes
					book_negamax(book); // negamax nodes
					book_sort(book); // sort moves

				// show the current position as stored in the book
				} else if (strcmp(book_cmd, "show") == 0) {
					book_show(book, play->board);

				// show book general information
				} else if (strcmp(book_cmd, "info") == 0) {
					book_info(book);

				// show book general information
				} else if (strcmp(book_cmd, "stats") == 0) {
					book_stats(book);


				// set book verbosity
				} else if (strcmp(book_cmd, "verbose") == 0) {
					parse_int(book_param, &book->options.verbosity);
					book->search->options.verbosity = book->options.verbosity;

				// analyze a game from the opening book point of view
				} else if (strcmp(book_cmd, "a") == 0 || strcmp(book_cmd, "analyze") == 0 || strcmp(book_cmd, "analyse") == 0) {
					val_1 = string_to_int(book_param, play->n_game); BOUND(val_1, 1, play->n_game, "depth");
					play_book_analyze(play, val_1);

				// add positions from a game database
				} else if (strcmp(book_cmd, "add") == 0) {
					Base base[1];
					parse_word(book_param, book_file, FILENAME_MAX);
					base_init(base);
					base_load(base, book_file);
					book_add_base(book, base);
					base_free(base);

				// check positions from a game database
				} else if (strcmp(book_cmd, "check") == 0) {
					Base base[1];
					parse_word(book_param, book_file, FILENAME_MAX);
					base_init(base);
					base_load(base, book_file);
					book_check_base(book, base);
					base_free(base);

				// extract positions
				} else if (strcmp(book_cmd, "problem") == 0) {
					val_1 = 24; book_param = parse_int(book_param, &val_1); BOUND(val_1, 0, 60, "number of empties");
					val_2 = 10; book_param = parse_int(book_param, &val_2); BOUND(val_2, 1, 1000000, "number of positions");
					book_extract_positions(book, val_1, val_2);
					
				// extract pv to a game database
				} else if (strcmp(book_cmd, "extract") == 0) {
					Base base[1];
					parse_word(book_param, book_file, FILENAME_MAX);
					base_init(base);
					book_extract_skeleton(book, base);
					base_save(base, book_file);
					base_free(base);

				// add position using the "deviate algorithm"
				} else if (strcmp(book_cmd, "deviate") == 0) {
					val_1 = 2; book_param = parse_int(book_param, &val_1); BOUND(val_1, -129, 129, "relative error");
					val_2 = 4; book_param = parse_int(book_param, &val_2); BOUND(val_2, 0, 65, "absolute error");
					book_deviate(book, play->board, val_1, val_2);

				// add position using the "enhance algorithm"
				} else if (strcmp(book_cmd, "enhance") == 0) {
					val_1 = 2; book_param = parse_int(book_param, &val_1); BOUND(val_1, 0, 129, "midgame error");
					val_2 = 4; book_param = parse_int(book_param, &val_2); BOUND(val_2, 0, 129, "endcut error");
					book_enhance(book, play->board, val_1, val_2);

				// add position by filling hole in the book
				} else if (strcmp(book_cmd, "fill") == 0) {
					val_1 = 1; book_param = parse_int(book_param, &val_1); BOUND(val_1, 1, 61, "fill depth");
					book_fill(book, val_1);

				// add positions by expanding positions with no-link
				} else if (strcmp(book_cmd, "play") == 0) {
					book_play(book);

				// add positions by expanding positions with no-link
				} else if (strcmp(book_cmd, "deepen") == 0) {
					book_deepen(book);

				// add book positions to the hash table
				} else if (strcmp(book_cmd, "feed-hash") == 0) {
					book_feed_hash(book, play->board, play->search);

				// wrong command ?
				} else {
					warn("Unknown book command: \"%s %s\"\n", cmd, param);
				}
				book->options.verbosity = book->search->options.verbosity;
				book->search->options.verbosity = options.verbosity;

			/* base TODO: add more actions... */
			} else if (strcmp(cmd, "base") == 0) {
				char base_file[FILENAME_MAX + 1];
				char base_cmd[512], *base_param;
				Base base[1];

				base_init(base);
				base_param = parse_word(param, base_cmd, 511);
				base_param = parse_word(base_param, base_file, FILENAME_MAX);

				// extract problem from a game base
				if (strcmp(base_cmd, "problem") == 0) {
					char problem_file[FILENAME_MAX + 1];
					int n_empties = 24;
					base_param = parse_int(base_param, &n_empties);
					base_param = parse_word(base_param, problem_file, FILENAME_MAX);

					base_load(base, base_file);
					base_to_problem(base, n_empties, problem_file);

				// extract FEN 
				} else if (strcmp(base_cmd, "tofen") == 0) {
					char problem_file[FILENAME_MAX + 1];
					int n_empties = 24;
					base_param = parse_int(base_param, &n_empties);
					base_param = parse_word(base_param, problem_file, FILENAME_MAX);

					base_load(base, base_file);
					base_to_FEN(base, n_empties, problem_file);
	
				// correct erroneous games
				} else if (strcmp(base_cmd, "correct") == 0) {
					int n_empties = 24;
					base_param = parse_int(base_param, &n_empties);

					base_load(base, base_file);
					base_analyze(base, play->search, n_empties, true);
					remove(base_file);
					base_save(base, base_file);

				// check erroneous games
				} else if (strcmp(base_cmd, "check") == 0) {
					int n_empties = 24;
					base_param = parse_int(base_param, &n_empties);

					base_load(base, base_file);
					base_analyze(base, play->search, n_empties, false);

				// terminate unfinished base
				} else if (strcmp(base_cmd, "complete") == 0) {
					base_load(base, base_file);
					base_complete(base, play->search);
					remove(base_file);
					base_save(base, base_file);

				// convert a base to another format
				} else if (strcmp(base_cmd, "convert") == 0) {
					base_load(base, base_file);
					base_param = parse_word(base_param, base_file, FILENAME_MAX);
					base_save(base, base_file);

				// make a base unique by removing identical games
				} else if (strcmp(base_cmd, "unique") == 0) {
					base_load(base, base_file);
					base_param = parse_word(base_param, base_file, FILENAME_MAX);
					base_unique(base);
					base_save(base, base_file);

				// compare two game bases
				} else if (strcmp(base_cmd, "compare") == 0) {
					char base_file_2[FILENAME_MAX + 1];
					base_param = parse_word(base_param, base_file_2, FILENAME_MAX);
					base_compare(base_file, base_file_2);

				} else {
					warn("Unknown base command: \"%s %s\"\n", cmd, param);
				}

				base_free(base);

			/* edax options */
			} else if (options_read(cmd, param)) {
				options_bound();
				// parallel search changes:
				if (search_count_tasks(play->search) != options.n_task) {
					play_stop_pondering(play);
					search_set_task_number(play->search, options.n_task);
				}

			/* switch to another protocol */
			} else if (strcmp(cmd, "nboard") == 0 && strcmp(param, "1") == 0) {
				free(cmd); free(param);
				play_stop_pondering(play);
				ui->free(ui);
				ui_switch(ui, "nboard");
				ui->init(ui);
				ui->loop(ui);
				return;

			} else if (strcmp(cmd, "xboard") == 0) {
				free(cmd); free(param);
				play_stop_pondering(play);
				ui->free(ui);
				ui_switch(ui, "xboard");
				ui->init(ui);
				ui->loop(ui);
				return;

			} else if (strcmp(cmd, "engine-protocol") == 0 && strcmp(param, "init") == 0) {
				free(cmd); free(param);
				play_stop_pondering(play);
				ui->free(ui);
				ui_switch(ui, "cassio");
				engine_loop();
				return;

			} else if (strcmp(cmd, "protocol_version") == 0) {
				free(cmd); free(param);
				play_stop_pondering(play);
				ui->free(ui);
				ui_switch(ui, "gtp");
				ui->init(ui);
				puts("= 2\n"); fflush(stdout);
				ui->loop(ui);
				return;

#ifdef TUNE_EDAX
			/* edax tuning */
			} else if (strcmp(cmd, "tune") == 0) {
				char problem[FILENAME_MAX];
				char *w_name;
				play_stop_pondering(play);
				w_name = parse_word(param, problem, FILENAME_MAX);
				tune_move_evaluate(play->search, problem, parse_skip_spaces(w_name));
				search_set_observer(play->search, edax_observer);
#endif
			/* illegal cmd/move */
			} else {
				warn("Unknown command/Illegal move: \"%s %s\"\n", cmd, param);
			}
		}
	}
}
예제 #29
0
int
render_html(const char *html_fn, render_cb r, void *arg)
{
	FILE *f;
	char s[8192];
	char fn[MAXPATHLEN];
	const char *s2;

	if ((f = fopen(html_fn, "r")) == NULL) {
		printf("ERROR: fopen: %s: %s<br>\n", html_fn, strerror(errno));
		return (1);
	}
	while (fgets(s, sizeof(s), f)) {
		char *a, *b;

		for (a = s; (b = strstr(a, "%%")) != NULL;) {
			*b = 0;
			printf("%s", a);
			a = b + 2;
			if ((b = strstr(a, "%%")) != NULL) {
				*b = 0;
				if (!strcmp(a, "ACTION")) {
					if ((s2 = get_query_param(q, "action")) == NULL)
						s2 = "front";
					printf("%s", s2);
				} else if (!strcmp(a, "BASEURL"))
					printf("%s", conf.baseurl);
				else if (!strcmp(a, "BASEDIR"))
					printf("%s", conf.htmldir);
				else if (!strcmp(a, "BASECSS")) {
					printf("%s?action=css%s", conf.baseurl,
							display_type == DISPLAY_PRINT ?
							"&amp;display=print" :
							display_type == DISPLAY_CSV ?
							"&amp;display=csv" : "");
				} else if (!strcmp(a, "TITLE"))
					printf("%s", conf.title);
				else if (!strcmp(a, "HEADER")) {
					snprintf(fn, sizeof(fn), "%s/header.html", conf.htmldir);
					render_html(fn, NULL, NULL);
				} else if (!strcmp(a, "FOOTER")) {
					snprintf(fn, sizeof(fn), "%s/footer.html", conf.htmldir);
					render_html(fn, NULL, NULL);
				} else if (!strcmp(a, "ROW")) {
					printf("row%d", rowselect);
					rowselect = !rowselect;
				} else if (!strcmp(a, "ROWRESET"))
					rowselect = 0;
				else if (!strcmp(a, "TIMESTART"))
					printf("%s", time_print(time_start));
				else if (!strcmp(a, "TIMESTOP"))
					printf("%s", time_print(time_stop));
				else if (!strcmp(a, "TIMENOW")) {
					char datetime[sizeof("9999-12-31T23:59:60+0000")];
					time_t now = time(NULL);
					strftime(datetime, sizeof(datetime), "%FT%T%z",
							localtime(&now));
					printf("%s", datetime);
				} else if (!strcmp(a, "TIMETODAY"))
					printf("%s", time_print(time_ext(TIME_TODAY)));
				else if (!strcmp(a, "TIMEYESTERDAY"))
					printf("%s", time_print(time_ext(TIME_YESTERDAY)));
				else if (!strcmp(a, "TIMETOMORROW"))
					printf("%s", time_print(time_ext(TIME_TOMORROW)));
				else if (!strcmp(a, "TIMETHISWEEK"))
					printf("%s", time_print(time_ext(TIME_THISWEEK)));
				else if (!strcmp(a, "TIMETHISMONTH"))
					printf("%s", time_print(time_ext(TIME_THISMONTH)));
				else if (!strcmp(a, "TIMETHISYEAR"))
					printf("%s", time_print(time_ext(TIME_THISYEAR)));
				else if (!strcmp(a, "TIMELASTWEEK"))
					printf("%s", time_print(time_ext(TIME_LASTWEEK)));
				else if (!strcmp(a, "TIMELASTMONTH"))
					printf("%s", time_print(time_ext(TIME_LASTMONTH)));
				else if (!strcmp(a, "TIMELASTYEAR"))
					printf("%s", time_print(time_ext(TIME_LASTYEAR)));
				else if (!strcmp(a, "QUERY"))
					printf("%s", q->query_string);
#if 0
				else if (!strcmp(a, "RCSID"))
					printf("%s", rcsid);
#endif
				else if (r != NULL)
					(*r)(a, arg);
				a = b + 2;
			}
		}
		printf("%s", a);
	}
	fclose(f);
	return 0;
}
예제 #30
0
static void send_frame(struct wstate *ws, unsigned char* buf, int len)
{
	static unsigned char* lame = 0;
	static int lamelen = 0;
	static int lastlen = 0;

	// retransmit!
	if (len == -1) {
		ws->ws_retries++;

		if (ws->ws_ignore_ack && ws->ws_retries >= ws->ws_ignore_ack) {
			ws->ws_waiting_ack = 0;
			return;
		}

		if (ws->ws_retries > 10) {
			time_print("ERROR Max retransmists for (%d bytes):\n",
			       lastlen);
			hexdump(&lame[0], lastlen);
#if 0
			txstate.waiting_ack = 0;
			return;
#endif
		}
		len = lastlen;
//		printf("Warning doing a retransmit...\n");
	}
	// normal tx
	else {
		assert(!ws->ws_waiting_ack);

		if (len > lamelen) {
			if (lame)
				free(lame);

			lame = (unsigned char*) malloc(len);
			if(!lame) {
				perror("malloc()");
				exit(1);
			}

			lamelen = len;
		}

		memcpy(lame, buf, len);
		ws->ws_retries = 0;
		lastlen = len;
	}

	inject(ws->ws_wi, lame, len);

	if (ws->ws_ignore_ack != 1)
		ws->ws_waiting_ack = 1;

	ws->ws_psent++;
	if (gettimeofday(&ws->ws_tsent, NULL) == -1) {
		perror("gettimeofday()");
		exit(1);
	}

#if 0
	printf("Wrote frame at %lu.%lu\n",
	       txstate.tsent.tv_sec, txstate.tsent.tv_usec);
#endif
}