Esempio n. 1
0
void
init_tracker_for_transfer (void)
{
	unsigned char data[100];
	int n;

	protocol_channel = 0;

	init_fitbit ();
	wait_for_beacon ();
	reset_tracker ();

	while (1) {
		device_number = getrandom () & 0xffff;
		if (device_number != 0 && device_number != 0xffff)
			break;
	}
	pairing_request = 0;
	device_type = 1;
	transmission_type = 1;

	dbg ("init_tracker_for_transfer: tell device to change dev num\n");
	n = 0;
	data[n++] = 0x78;
        data[n++] = 0x02;
	data[n++] = device_number;
	data[n++] = device_number >> 8;
	data[n++] = 0x00;
	data[n++] = 0x00;
	data[n++] = 0x00;
	data[n++] = 0x00;
	protocol_send_acknowledged_data (data, n);
	
	protocol_close_channel ();
	/* 
	 * we're supposed to wait for EVENT_CHANNEL_CLOSED but it never
	 * seems to come
	 */
	soak (.2);

	dbg ("hoping channel close has happened...\n");

	init_device_channel (device_number,
			     pairing_request, device_type,
			     transmission_type);

	wait_for_beacon ();
	ping_tracker ();
}
Esempio n. 2
0
int getrandom(int width,int height,int *x)
{
    int row,col;
    row = evenbetween(0,height);
    col = evenbetween(0,width);
    *x = width * row + col;
    /* here we prevent generation of number that would produce odd column value*/
    if((*x%width)%2 != 0)
    {
        //printf("\n\tratio = %2d",(*x%width)%2); //getch();
        getrandom(width,height,x);
    }
//  printf("\n\trow - %3d , col - %3d x = %3d width = %3d cycle = %4d", row,col,*x,width,cycle);
    return cycle--;
}
Esempio n. 3
0
static unsigned ffsb_createfile_core(ffsb_thread_t *ft, ffsb_fs_t *fs,
				     unsigned opnum, uint64_t *filesize_ret,
				     int fsync_file)
{
	struct benchfiles *bf = (struct benchfiles *)fs_get_opdata(fs, opnum);
	struct ffsb_file *newfile = NULL;

	int fd;
	uint64_t size;

	char *buf = ft_getbuf(ft);
	uint32_t write_blocksize = ft_get_write_blocksize(ft);
	struct randdata *rd = ft_get_randdata(ft);
	unsigned iterations = 0;

	if (fs->num_weights) {
		int num = 1 + getrandom(rd, fs->sum_weights);
		int curop = 0;

		while (fs->size_weights[curop].weight < num) {
			num -= fs->size_weights[curop].weight;
			curop++;
		}
		size = fs->size_weights[curop].size;
	}
	else {
		uint64_t range = fs_get_max_filesize(fs) - fs_get_min_filesize(fs);
		size = fs_get_min_filesize(fs);
		if (range != 0)
			size += getllrandom(rd, range);
	}

	newfile = add_file(bf, size, rd);
	fd = fhopencreate(newfile->name, ft, fs);
	iterations = writefile_helper(fd, size, write_blocksize, buf, ft, fs);

	if (fsync_file)
 		if (fsync(fd)) {
 			perror("fsync");
 			printf("aborting\n");
 			exit(1);
 		}

	fhclose(fd, ft, fs);
	unlock_file_writer(newfile);
 	*filesize_ret = size;
	return iterations;
}
Esempio n. 4
0
main(){
	int *p; //p stores random  number array(unsorted)
	int i,q,index;
	p=getrandom();
	printf("Enter the number to be searched ??\n");
	scanf("%d",&q);
	index=find(p,q);
	printf("Array is :\n");
	printf("-------------------------------------------------\n");
	for(i=0;i<10;i++)
		printf(" %2d |",*(p+i) );
	printf("\n");
	printf("--------------------------------------------------\n");
	if(index!=-1){
		printf("The number  '%d' found and index is %d\n",q,index );
	}
	else
		printf("Number Not found\n");
} 
int hcreate_r(size_t count, struct hsearch_data* htab) {
  htab->size=count;
  htab->filled=0;
  htab->table=calloc(count,sizeof(htab->table[0]));
  if (htab->table) {
    char* rnd=(char*)getauxval(AT_RANDOM);
    if (rnd)
      memcpy(htab->key,rnd,16);
    else {
      struct timeval tv;
      struct timeval* x=(struct timeval*)htab->key;
      if (getrandom(&htab->key,sizeof(htab->key),0) != sizeof(htab->key)) {
	gettimeofday(&tv,NULL);
	x->tv_sec += tv.tv_sec;
	x->tv_usec += tv.tv_usec;
      }
    }
  }
  return htab->table ? 1 : 0;
}
Esempio n. 6
0
/*
 * generate:
 *	generate initial key and write it on keyfile and key0file
 *	in the last file data is written as ascii string
 */
void
generate(void)
{
	int	 kfd;
	int	 k0fd;
	unsigned char	 key[20];
	unsigned char	 keyasc[41];
	int	 keylen;
	unsigned char	 randvalue[20];

	if (getrandom(randvalue, 20) < 0) {
		release();
		perror("getrandom");
		exit(-1);
	}
	if ( (keylen = mac(method, NULL, 0, randvalue, 20, key)) == -1) {
		release();
		perror("fatal");
		exit(-1);
	}
	if ( (kfd = open(keyfile, O_WRONLY|O_CREAT|O_EXCL,
	    S_IRUSR|S_IWUSR)) == -1) {
		release();
		perror(keyfile);
		exit(-1);
	}
	if ( (k0fd = open(key0file, O_WRONLY|O_CREAT|O_EXCL,
	    S_IRUSR|S_IWUSR)) == -1) {
		unlink(keyfile);
		close(kfd);
		release();
		perror(key0file);
		exit(-1);
	}

	/* write key 0 */
	write(kfd, key, keylen);
	write(k0fd, bin2asc(keyasc, key, keylen), keylen << 1);
	close(kfd);
	close(k0fd);
}
Esempio n. 7
0
static struct ffsb_file *choose_file(struct benchfiles *b, randdata_t *rd)
{
	rb_node *cur = NULL;
	int chosen = 0;
	struct ffsb_file temp;
	temp.num = chosen;

	if (b->listsize == 0) {
		fprintf(stderr, "No more files to operate on,"
			  " try making more initial files "
			  "or fewer delete operations\n");
		exit(0);
	}

	while (cur == NULL) {
		chosen = getrandom(rd, b->listsize);
		temp.num = chosen;
		cur = rbtree_find(b->files, &temp);
	}
	return cur->object;
}
Esempio n. 8
0
/*
 * bundle - bundle e and n into an RFC2537-format chunk_t
 */
static char *base64_bundle(int e, chunk_t modulus)
{
	/*
	 * Pack the single-byte exponent into a byte array.
	 */
	assert(e <= 255);
	u_char exponent_byte = 1;
	chunk_t exponent = {
		.ptr = &exponent_byte,
		.len = 1,
	};

	/*
	 * Create the resource record.
	 */
	char *bundle;
	err_t err = rsa_pubkey_to_base64(exponent, modulus, &bundle);
	if (err) {
		fprintf(stderr, "%s: can't-happen bundle convert error `%s'\n",
			progname, err);
		exit(1);
	}

	return bundle;
}

/* UpdateRNG - Updates NSS's PRNG with user generated entropy. */
static void UpdateNSS_RNG(int seedbits)
{
	SECStatus rv;
	int seedbytes = BYTES_FOR_BITS(seedbits);
	unsigned char *buf = alloc_bytes(seedbytes,"TLA seedmix");

	getrandom(seedbytes, buf);
	rv = PK11_RandomUpdate(buf, seedbytes);
	assert(rv == SECSuccess);
	messupn(buf, seedbytes);
	pfree(buf);
}
Esempio n. 9
0
File: udp.dns.c Progetto: ifbe/42
int dns_write_query(u8* buf, int len, u8* domain, int count)
{
	int j;
	int aa,bb;
	struct dnshead* h;

	//check domain
	aa = -1;
	for(j=0;j<100;j++)
	{
		if(domain[j] <= 0x20){bb = j;break;}
		if('/' == domain[j])aa = j+1;
	}
	if(aa < 0)return 0;

	//head
	h = (void*)buf;
	h->tran = getrandom()&0xffff;
	h->flag = 1;
	h->q = 0x100;
	h->a = 0;
	h->auth = 0;
	h->addi = 0;

	//copy
	j = 12;
	j += dns_query_fixurl(buf+j, 0, domain+aa, bb-aa);

	//tail
	buf[j+0] = 0;
	buf[j+1] = 1;
	buf[j+2] = 0;
	buf[j+3] = 1;

	return j+4;
}
// Attacks a target object.
void CHSLaser::AttackObject(CHSObject *cSource,
							CHSObject *cTarget,
							CHSConsole *cConsole,
							int iSysType)
{
	dbref dbUser;
	int   iAttackRoll;
	int   iDefendRoll;
	int i;
	CHSObject *cCTarget;
	double sX, sY, sZ; // Source object coords
	double tX, tY, tZ; // Target object coords;

	// Grab the user of the console.
	dbUser = hsInterface.ConsoleUser(cConsole->m_objnum);

	// Can we attack that object?
	if (cSource->GetType() == HST_SHIP)
	{
		CHSSysCloak *cCloak;
		CHSShip *ptr;
		float rval;

		ptr = (CHSShip *)cSource;

		// Look for the cloaking device.
		cCloak = (CHSSysCloak *)ptr->GetEngSystem(HSS_CLOAK);
		if (cCloak)
			if (cCloak->GetEngaged())
			{
				if (dbUser != NOTHING)
					hsStdError(dbUser, "You cannot fire while cloaked.");
				return;
			}
	}

	if (!CanAttackObject(cTarget))
	{
		if (dbUser != NOTHING)
			hsStdError(dbUser,
			"You cannot attack that target with that weapon.");
	}

 	// Calculate distance to object
	sX = cSource->GetX();
	sY = cSource->GetY();
	sZ = cSource->GetZ();
	tX = cTarget->GetX();
	tY = cTarget->GetY();
	tZ = cTarget->GetZ();

	double dDistance;
	dDistance = Dist3D(sX, sY, sZ, tX, tY, tZ) + .00001;

	// Size of a target ship matters relative to distance.
	// The closer a target gets to the ship, the larger
	// it effectively is.  That is to say it takes up more
	// of the view angle.  When the target is right next
	// to the ship, in front of the gun, it is essentially
	// the broad side of a barn, which everyone can hit.
	// Thus, to handle this we'll calculate the size of
	// the target and the viewing angle it takes up.

	double dSize; // Size of the side of the target
	double dAngle; // Amount of viewing angle taken up by size

	dSize = cTarget->GetSize();
	dSize = (.7 * dSize) * (.7 * dSize);

	// Halve the size, and divide by distance.  This
	// gives us the tangent of the angle taken up by
	// the target.
	dSize = (dSize * .5) / dDistance;

	// Take the inverse tangent to get angle.
	dAngle = atan(dSize);

	// Double the angle because we used half of the size
	// to get the angle of a right triangle.
	dAngle *= 2;

	// We now have the viewing angle consumed by the 
	// target.  There's a maximum possible value of 180,
	// so divide by that to determine how much of the viewing
	// angle is taken up by the target.
	dSize = dAngle * .005555;

	// Subtract from 1 to get maximum values of 1 when the
	// angle is small.
	dSize = 1 - dSize;

	// Now multiply by 6 to get relative difficulty of hitting
	// target.
	iDefendRoll = (int) (6 * dSize) + getrandom(6);
    iAttackRoll = GetAccuracy() + getrandom(6);

	// Simulate difficulty when a target is moving.
	// If the target is moving toward or away from the
	// attacker, it's not very difficult.  Thus, we
	// calculate the change in angle for the target
	// during one cycle.  The maximum change is 180
	// degrees.
	CHSVector tVec;
	CHSVector aVec;
	tVec = cTarget->GetMotionVector();
	aVec = cSource->GetMotionVector();

	// Calculate vector to target now.
	double dx, dy, dz;
	dx = tX - sX;
	dy = tY - sY;
	dz = tZ - sZ;

	// Make a unit vector
	dx /= dDistance;
	dy /= dDistance;
	dz /= dDistance;

	CHSVector nowVec(dx, dy, dz);

	// Now calculate coordinate for source and target
	// in one cycle.
	double sX2, sY2, sZ2;
	double tX2, tY2, tZ2;
	double aSpeed, tSpeed;

	// Grab both object speeds, and bring them down
	// to per-second levels.
	aSpeed = cSource->GetSpeed() * .0002778;
	tSpeed = cTarget->GetSpeed() * .0002778;

	// Calculate coordinates for next cycle.
	sX2 = sX + (aVec.i() * aSpeed);
	sY2 = sY + (aVec.j() * aSpeed);
	sZ2 = sZ + (aVec.k() * aSpeed);
	tX2 = tX + (tVec.i() * tSpeed);
	tY2 = tY + (tVec.j() * tSpeed);
	tZ2 = tZ + (tVec.k() * tSpeed);

	// Calculate vector to target after next cycle
	dx = tX2 - sX2;
	dy = tY2 - sY2;
	dz = tZ2 - sZ2;

	// Divide by distance to make a unit vector
	double dDistance2;
	dDistance2 = Dist3D(sX2, sY2, sZ2, tX2, tY2, tZ2);
	dx /= dDistance2;
	dy /= dDistance2;
	dz /= dDistance2;

	CHSVector nextVec(dx, dy, dz);

	// Calculate the dot product between the previous
	// and the next cycle vectors.
	double dp;
	dp = nowVec.DotProduct(nextVec);

	// Calculate the angle change.  This is in radians.
	dAngle = acos(dp);

	// Now divide angle change by 2pi to get change in angle
	// from 0 to 1, where 1 is a huge change in angle and,
	// therefore, high difficulty.
	dAngle *= .15915;

	// Add up to 6 points of defense for "evasion" by angle
	// change.
	iDefendRoll += (int) (6 * dAngle);


	// If distance is farther than our range, the shot always
	// misses.

	double range;
	range = GetRange();
				
	CHSUniverse *uDest;
	char tbuf[256];
	char fstat1[128];
	char fstat2[128];

	if (dDistance >= range || iDefendRoll > iAttackRoll) {
		sprintf(fstat1, "%s%smisses%s",ANSI_HILITE,ANSI_GREEN,ANSI_NORMAL);
		sprintf(fstat2, "%s%smissed%s",ANSI_HILITE,ANSI_GREEN,ANSI_NORMAL);
	} else {
		sprintf(fstat1, "%s%shits%s",ANSI_HILITE,ANSI_RED,ANSI_NORMAL);
		sprintf(fstat2, "%s%shit%s",ANSI_HILITE,ANSI_RED,ANSI_NORMAL);
	}
		
	uDest = uaUniverses.FindUniverse(cSource->GetUID());

	CHSSysSensors *cSensors;
	SENSOR_CONTACT *cContactS;
	SENSOR_CONTACT *cContactD;
	for (i = 0; i < HS_MAX_ACTIVE_OBJECTS; i++)
	{
		cCTarget = uDest->GetActiveUnivObject(i);
		if (!cCTarget)
			continue;
		if (cCTarget == cSource || cCTarget == cTarget)
			continue;

		cSensors = (CHSSysSensors *)cCTarget->GetEngSystem(HSS_SENSORS);
		if (!cSensors)
			continue;

		cContactS = cSensors->GetContact(cSource);
		cContactD = cSensors->GetContact(cTarget);


		if (!cContactS && !cContactD)
			continue;

		if (!cContactS && cContactD) {
			if (cContactD->status == DETECTED) {
				sprintf(tbuf, "%s[%s%s%d%s%s]%s - Unknown contact is being fired upon and %s",cTarget->GetObjectColor(),ANSI_NORMAL,ANSI_HILITE,cContactD->m_id,ANSI_NORMAL,cTarget->GetObjectColor(),ANSI_NORMAL, fstat2);
				cCTarget->HandleMessage(tbuf, MSG_SENSOR, (long *)cCTarget);
			} else if (cContactD->status == IDENTIFIED) {
				sprintf(tbuf, "%s[%s%s%d%s%s]%s - The %s is being fired upon and %s",cTarget->GetObjectColor(),ANSI_NORMAL,ANSI_HILITE,cContactD->m_id,ANSI_NORMAL,cTarget->GetObjectColor(),ANSI_NORMAL, cSource->GetName(), fstat2);
				cCTarget->HandleMessage(tbuf, MSG_SENSOR, (long *)cCTarget);
			}
			continue;
		}
						
											
		if (cContactS && !cContactD) {
			if (cContactS->status == DETECTED) {
				sprintf(tbuf, "%s[%s%s%d%s%s]%s - Unknown contact is firing upon something",cSource->GetObjectColor(),ANSI_NORMAL,ANSI_HILITE,cContactS->m_id,ANSI_NORMAL,cSource->GetObjectColor(),ANSI_NORMAL);
				cCTarget->HandleMessage(tbuf, MSG_SENSOR, (long *)cCTarget);
			} else if (cContactS->status == IDENTIFIED) {
				sprintf(tbuf, "%s[%s%s%d%s%s]%s - The %s is firing upon something",cSource->GetObjectColor(),ANSI_NORMAL,ANSI_HILITE,cContactS->m_id,ANSI_NORMAL,cSource->GetObjectColor(),ANSI_NORMAL, cSource->GetName());
				cCTarget->HandleMessage(tbuf, MSG_SENSOR, (long *)cCTarget);
			}
			continue;
		}

		if (cContactS && cContactD)
			if (cContactS->status == DETECTED && cContactD->status == DETECTED) {
				sprintf(tbuf, "%s[%s%s%d%s%s]%s - Unknown contact fires and %s unknown contact %s[%s%s%d%s%s]%s",cSource->GetObjectColor(),ANSI_NORMAL,ANSI_HILITE,cContactS->m_id,ANSI_NORMAL,cSource->GetObjectColor(),ANSI_NORMAL, fstat1,cTarget->GetObjectColor(),ANSI_NORMAL,ANSI_HILITE,cContactD->m_id,ANSI_NORMAL,cTarget->GetObjectColor(),ANSI_NORMAL);
				cCTarget->HandleMessage(tbuf,MSG_SENSOR, (long *)cCTarget);
			} else if (cContactS->status == IDENTIFIED && cContactD->status == IDENTIFIED) {
				sprintf(tbuf, "%s[%s%s%d%s%s]%s - The %s fires and %s the %s",cSource->GetObjectColor(),ANSI_NORMAL,ANSI_HILITE,cContactS->m_id,ANSI_NORMAL,cSource->GetObjectColor(),ANSI_NORMAL, cSource->GetName(), fstat1, cTarget->GetName());
				cCTarget->HandleMessage(tbuf, MSG_SENSOR, (long *)cCTarget);
			} else if (cContactS->status == IDENTIFIED && cContactD->status == DETECTED) {
				sprintf(tbuf, "%s[%s%s%d%s%s]%s - The %s fires and %s unknown contact %s[%s%s%d%s%s]%s",cSource->GetObjectColor(),ANSI_NORMAL,ANSI_HILITE,cContactS->m_id,ANSI_NORMAL,cSource->GetObjectColor(),ANSI_NORMAL, cSource->GetName(), fstat1,cTarget->GetObjectColor(),ANSI_NORMAL,ANSI_HILITE,cContactD->m_id,ANSI_NORMAL,cTarget->GetObjectColor(),ANSI_NORMAL);
				cCTarget->HandleMessage(tbuf, MSG_SENSOR, (long *)cCTarget);
			} else if (cContactS->status == DETECTED && cContactD->status == IDENTIFIED) {
				sprintf(tbuf, "%s[%s%s%d%s%s]%s - Unknown contact fires and %s the %s",cSource->GetObjectColor(),ANSI_NORMAL,ANSI_HILITE,cContactS->m_id,ANSI_NORMAL,cSource->GetObjectColor(),ANSI_NORMAL, fstat1, cTarget->GetName());
				cCTarget->HandleMessage(tbuf, MSG_SENSOR, (long *)cCTarget);
			}

	}
	
	
	
	
	
	if (dDistance >= range)
    {
		if (dbUser != NOTHING)
			hsStdError(
			dbUser,
			"Your shot dissipates short of its target.");

		strcpy(tbuf,
			"An incoming energy shot has missed us.");
		cTarget->HandleMessage(tbuf, MSG_COMBAT, (long *)cSource);
	}
    else if (iAttackRoll > iDefendRoll)
	{
		// The weapon hits!
		// Determine strength based on base weapon
		// strength and range to target.
		int strength;

		strength = GetStrength();
		if (dDistance > (range * .333))
		{
			strength = (int)(strength * 
				(.333 + (1 - (dDistance / (range + .0001)))));
		}

		// If iSysType is not HSS_NOTYPE, then do a roll
		// against the accuracy of the weapon to see if
		// the system gets hit.
		if (iSysType != HSS_NOTYPE)
		{
			UINT ARoll, SRoll;
		
			ARoll = getrandom(GetAccuracy());
			SRoll = getrandom(10);

			if (SRoll > ARoll)
				iSysType = HSS_NOTYPE; // Didn't succeed
		}

		// Tell the target to take damage
		cTarget->HandleDamage(cSource, this, strength,
			cConsole, iSysType);
	
	}
	else
	{
		// The weapon misses. :(
		if (dbUser != NOTHING)
			hsStdError(dbUser,
			"Your shot skims past your target and out into space.");

		strcpy(tbuf,
			"An incoming energy shot has missed us.");
		cTarget->HandleMessage(tbuf, MSG_COMBAT, (long *)cSource);
	}

	Regenerate();
}
Esempio n. 11
0
void cpu() {
	int box;
	srand((unsigned int)time(NULL));
	for (int i = 0; i < 1;) {
		if (display_field[2][2] == 1 && display_field[0][0] == 4 && display_field[1][1] == 4) {
			display_field[2][2] = 4;
			break;
		}
		else if (display_field[1][1] == 1 && display_field[0][0] == 4 && display_field[2][2] == 4) {
			display_field[1][1] = 4;
			break;
		}
		else if (display_field[0][0] == 1 && display_field[1][1] == 4 && display_field[2][2] == 4) {
			display_field[0][0] = 4;
			break;
		}
		else if (display_field[0][2] == 1 && display_field[1][1] == 4 && display_field[2][0] == 4) {
			display_field[0][2] = 4;
			break;
		}
		else if (display_field[1][1] == 1 && display_field[0][2] == 4 && display_field[2][0] == 4) {
			display_field[1][1] = 4;
			break;
		}
		else if (display_field[2][0] == 1 && display_field[1][1] == 4 && display_field[0][2] == 4) {
			display_field[2][0] = 4;
			break;
		}
		for (int j = 0; j < 3; j++) {
			if (display_field[j][0] == 1 && display_field[j][1] == 4 && display_field[j][2] == 4) {
				display_field[j][0] = 4;
				i = 1;
				break;
			}
			else if (display_field[j][1] == 1 && display_field[j][0] == 4 && display_field[j][2] == 4) {
				display_field[j][1] = 4;
				i = 1;
				break;
			}
			else if (display_field[j][2] == 1 && display_field[j][0] == 4 && display_field[j][1] == 4) {
				display_field[j][2] = 4;
				i = 1;
				break;
			}
			else if (display_field[0][j] == 1 && display_field[1][j] == 4 && display_field[2][j] == 4) {
				display_field[0][j] = 4;
				i = 1;
				break;
			}
			else if (display_field[1][j] == 1 && display_field[0][j] == 4 && display_field[2][j] == 4) {
				display_field[1][j] = 4;
				i = 1;
				break;
			}
			else if (display_field[2][j] == 1 && display_field[0][j] == 4 && display_field[1][j] == 4) {
				display_field[2][j] = 4;
				i = 1;
				break;
			}
		}
		if (i == 1)break;

		if (display_field[2][2] == 1 && display_field[0][0] == 3 && display_field[1][1] == 3) {
			display_field[2][2] = 4;
			break;
		}
		else if (display_field[1][1] == 1 && display_field[0][0] == 3 && display_field[2][2] == 3) {
			display_field[1][1] = 4;
			break;
		}
		else if (display_field[0][0] == 1 && display_field[1][1] == 3 && display_field[2][2] == 3) {
			display_field[0][0] = 4;
			break;
		}
		else if (display_field[0][2] == 1 && display_field[1][1] == 3 && display_field[2][0] == 3) {
			display_field[0][2] = 4;
			break;
		}
		else if (display_field[1][1] == 1 && display_field[0][2] == 3 && display_field[2][0] == 3) {
			display_field[1][1] = 4;
			break;
		}
		else if (display_field[2][0] == 1 && display_field[1][1] == 3 && display_field[0][2] == 3) {
			display_field[2][0] = 4;
			break;
		}
		for (int j = 0; j < 3; j++) {
			if (display_field[j][0] == 1 && display_field[j][1] == 3 && display_field[j][2] == 3) {
				display_field[j][0] = 4;
				i = 1;
				break;
			}
			else if (display_field[j][1] == 1 && display_field[j][0] == 3 && display_field[j][2] == 3) {
				display_field[j][1] = 4;
				i = 1;
				break;
			}
			else if (display_field[j][2] == 1 && display_field[j][0] == 3 && display_field[j][1] == 3) {
				display_field[j][2] = 4;
				i = 1;
				break;
			}
			else if (display_field[0][j] == 1 && display_field[1][j] == 3 && display_field[2][j] == 3) {
				display_field[0][j] = 4;
				i = 1;
				break;
			}
			else if (display_field[1][j] == 1 && display_field[0][j] == 3 && display_field[2][j] == 3) {
				display_field[1][j] = 4;
				i = 1;
				break;
			}
			else if (display_field[2][j] == 1 && display_field[0][j] == 3 && display_field[1][j] == 3) {
				display_field[2][j] = 4;
				i = 1;
				break;
			}
		}
		if (i == 1)break;
		if (display_field[1][1] == 1) {
			display_field[1][1] = 4;
			break;
		}
		else if (display_field[1][1] != 1) {
			box = getrandom(0, 7);
			if (box == 0 && display_field[0][0] == 1) {
				display_field[0][0] = 4;
				break;
			}
			else if (box == 1 && display_field[0][1] == 1) {
				display_field[0][1] = 4;
				break;
			}
			else if (box == 2 && display_field[0][2] == 1) {
				display_field[0][2] = 4;
				break;
			}
			else if (box == 3 && display_field[1][0] == 1) {
				display_field[1][0] = 4;
				break;
			}
			else if (box == 4 && display_field[1][2] == 1) {
				display_field[1][2] = 4;
				break;
			}
			else if (box == 5 && display_field[2][0] == 1) {
				display_field[2][0] = 4;
				break;
			}
			else if (box == 6 && display_field[2][1] == 1) {
				display_field[2][1] = 4;
				break;
			}
			else if (box == 7 && display_field[2][2] == 1) {
				display_field[2][2] = 4;
				break;
			}
		}
	}
}
Esempio n. 12
0
int Game::SetupFaction( Faction *pFac )
{
	pFac->unclaimed = Globals->START_MONEY + TurnNumber() * 50;

	if (pFac->noStartLeader)
		return 1;

	//
	// Set up first unit.
	//
	Unit *temp2 = GetNewUnit( pFac );
	temp2->SetMen(I_LEADERS, 1);
	pFac->DiscoverItem(I_LEADERS, 0, 1);
	temp2->reveal = REVEAL_FACTION;

	temp2->type = U_MAGE;
	temp2->Study(S_PATTERN, 30);
	temp2->Study(S_SPIRIT, 30);
	temp2->Study(S_GATE_LORE, 30);

	if (TurnNumber() >= 25) {
		temp2->Study(S_PATTERN, 60);
		temp2->Study(S_SPIRIT, 60);
		temp2->Study(S_FORCE, 90);
		temp2->Study(S_COMBAT, 30);
	}

	if (Globals->UPKEEP_MINIMUM_FOOD > 0)
	{
		if (!(ItemDefs[I_FOOD].flags & ItemType::DISABLED)) {
			temp2->items.SetNum(I_FOOD, 6);
			pFac->DiscoverItem(I_FOOD, 0, 1);
		} else if (!(ItemDefs[I_FISH].flags & ItemType::DISABLED)) {
			temp2->items.SetNum(I_FISH, 6);
			pFac->DiscoverItem(I_FISH, 0, 1);
		} else if (!(ItemDefs[I_LIVESTOCK].flags & ItemType::DISABLED)) {
			temp2->items.SetNum(I_LIVESTOCK, 6);
			pFac->DiscoverItem(I_LIVESTOCK, 0, 1);
		} else if (!(ItemDefs[I_GRAIN].flags & ItemType::DISABLED)) {
			temp2->items.SetNum(I_GRAIN, 2);
			pFac->DiscoverItem(I_GRAIN, 0, 1);
		}
		temp2->items.SetNum(I_SILVER, 10);
	}

	ARegion *reg = NULL;
	if (pFac->pStartLoc) {
		reg = pFac->pStartLoc;
	} else if (!Globals->MULTI_HEX_NEXUS) {
		reg = (ARegion *)(regions.First());
	} else {
		ARegionArray *pArr = regions.GetRegionArray(ARegionArray::LEVEL_NEXUS);
		while(!reg) {
			reg = pArr->GetRegion(getrandom(pArr->x), getrandom(pArr->y));
		}
	}
	temp2->MoveUnit( reg->GetDummy() );

	if (Globals->LAIR_MONSTERS_EXIST || Globals->WANDERING_MONSTERS_EXIST) {
		// Try to auto-declare all player factions unfriendly
		// to Creatures, since all they do is attack you.
		pFac->SetAttitude(monfaction, A_UNFRIENDLY);
	}

	return( 1 );
}
Esempio n. 13
0
ARegion *ARegionList::GetStartingCity( ARegion *AC,
                                       int i,
                                       int level,
                                       int maxX,
                                       int maxY )
{
    ARegionArray *pArr = pRegionArrays[ level ];
    ARegion * reg = 0;

    if( pArr->x < maxX ) maxX = pArr->x;
    if( pArr->y < maxY ) maxY = pArr->y;

	int tries = 0;
    while (!reg && tries < 10000) {
        //
        // We'll just let AC exits be all over the map.
        //
        int x = getrandom( maxX );
        int y = 2 * getrandom( maxY / 2 ) + x % 2;

        reg = pArr->GetRegion( x, y);

        if(!reg || !reg->CanBeStartingCity( pArr )) {
            reg = 0;
			tries++;
            continue;
        }

        for (int j=0; j<i; j++) {
			if(!AC->neighbors[j]) continue;
			if (GetDistance(reg,AC->neighbors[j]) < maxY / 10 + 2 ) {
				reg = 0;
				tries++;
				break;
            }
        }
    }

	// Okay, we failed to find something that normally would work
	// we'll just take anything that's of the right distance
	tries = 0;
	while (!reg && tries < 10000) {
		//
		// We couldn't find a normal starting city, let's just go for ANY
		// city
		//
		int x = getrandom( maxX );
		int y = 2 * getrandom( maxY / 2 ) + x % 2;
		reg = pArr->GetRegion( x, y);
		if(!reg || reg->type == R_OCEAN) {
			tries++;
			reg = 0;
			continue;
		}

        for (int j=0; j<i; j++) {
			if(!AC->neighbors[j]) continue;
			if (GetDistance(reg,AC->neighbors[j]) < maxY / 10 + 2 ) {
				reg = 0;
				tries++;
				break;
            }
        }
    }

	// Okay, if we still don't have anything, we're done.
    return reg;
}
Esempio n. 14
0
int ARegionList::GetRegType( ARegion *pReg )
{
    //
    // Figure out the distance from the equator, from 0 to 3.
    //
    int lat = ( pReg->yloc * 8 ) / ( pRegionArrays[ pReg->zloc ]->y );
    if (lat > 3)
    {
        lat = (7 - lat);
    }

	// Underworld region
    if((pReg->zloc > 1) && (pReg->zloc < Globals->UNDERWORLD_LEVELS+2)) {
        int r = getrandom(4);
        switch (r) {
			case 0:
				return R_OCEAN;
			case 1:
				return R_CAVERN;
			case 2:
				return R_UFOREST;
			case 3:
				return R_TUNNELS;
			default:
				return( 0 );
        }
    }

	// Underdeep region
	if((pReg->zloc > Globals->UNDERWORLD_LEVELS+1) &&
			(pReg->zloc < Globals->UNDERWORLD_LEVELS+
			 			  Globals->UNDERDEEP_LEVELS+2)) {
		int r = getrandom(4);
		switch(r) {
			case 0:
				return R_OCEAN;
			case 1:
				return R_CHASM;
			case 2:
				return R_DFOREST;
			case 3:
				return R_GROTTO;
			default:
				return (0);
		}
	}

	// surface region
    if( pReg->zloc == 1 ) {
        int r = getrandom(64);
        switch (lat)
        {
        case 0: /* Arctic regions */
            //if (r < 24) return R_TUNDRA;
            if (r < 32) return R_CERAN_HILL;
            if (r < 50) return R_MOUNTAIN;
            if (r < 58) return R_FOREST;
            return R_PLAIN;
        case 1: /* Colder regions */
            if (r < 16) return R_PLAIN;
            if (r < 32) return R_FOREST;
            if (r < 42) return R_CERAN_HILL;
            if (r < 48) return R_MOUNTAIN;
            return R_SWAMP;
        case 2: /* Warmer regions */
            if (r < 20) return R_PLAIN;
            if (r < 28) return R_FOREST;
            if (r < 36) return R_CERAN_HILL;
            if (r < 42) return R_MOUNTAIN;
            if (r < 48) return R_SWAMP;
            if (r < 52) return R_JUNGLE;
            return R_DESERT;
        case 3: /* tropical */
            if (r < 16) return R_PLAIN;
            if (r < 22) return R_CERAN_HILL;
            if (r < 28) return R_MOUNTAIN;
            if (r < 36) return R_SWAMP;
            if (r < 48) return R_JUNGLE;
            return R_DESERT;
        }
        return R_OCEAN;
    }

    if( pReg->zloc == 0 )
    {
        //
        // This really shouldn't ever get called.
        //
        return( R_NEXUS );
    }

    //
    // This really shouldn't get called either
    //
    return( R_OCEAN );
}
Esempio n. 15
0
/*!
 \brief

 \fn DoRandom
 \param arg
 \return double
*/
double DoRandom (double arg)
{
    return getrandom (static_cast <int> (arg));  // random number in range 0 to arg
}
Esempio n. 16
0
File: os.c Progetto: amagura/common
{
     char *tmp, *XXXX;
     uint64_t val;
     int fd, xcnt, cnt, pos,
         tries = pow(62, 3);
     pid_t pid;
     char *wp = strdup(template);
     size_t len = strlen(wp);
     /* characters used to fill in the X's in template names */
     const char filler[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

     tmp = XXXX = NULL;
     xcnt = cnt = pos = 0;
     pid = getpid();
     srand(time(NULL));
     val = getrandom() * rand() * randm(RAND_MAX) ^ pid;

/* The number of times to attempt to generate a temporary file.
 * POSIX demands that this must be no smaller than TMP_MAX.
 */
# if ((62*62*62) < TMP_MAX)
     tries = TMP_MAX;
# endif

     COINT_DBG("tries: '%d'\n", tries);

     /* find the last X in wp */
     char *sp = strrchr(wp, 'X');
     /* make sure that we at least have one template X */
     if (sp == NULL) {
          /* no period was found in template string */
Esempio n. 17
0
void arc4random_buf(void* Buf, size_t N) {
  if ((size_t)getrandom(Buf,N,GRND_NONBLOCK) != N)
    abort();
}
Esempio n. 18
0
int ARegionList::GetRegType( ARegion *pReg )
{
	//
	// Figure out the distance from the equator, from 0 to 3.
	//
	// Note that the -3 applied to y here is because I'm assuming we're using
	// icosahedral levels, which don't quite fill their y-space
	int lat = ( pReg->yloc * 8 ) / ( pRegionArrays[ pReg->zloc ]->y);
	if (lat > 3)
	{
		lat = (7 - lat);
	}
	if (lat < 0) lat = 0;

	// Underworld region
	if ((pReg->zloc > 1) && (pReg->zloc < Globals->UNDERWORLD_LEVELS+2)) {
		int r = getrandom(4);
		switch (r) {
			case 0:
				return R_OCEAN;
			case 1:
				return R_CAVERN;
			case 2:
				return R_UFOREST;
			case 3:
				return R_TUNNELS;
			default:
				return( 0 );
		}
	}

	// Underdeep region
	if ((pReg->zloc > Globals->UNDERWORLD_LEVELS+1) &&
			(pReg->zloc < Globals->UNDERWORLD_LEVELS+
			 			  Globals->UNDERDEEP_LEVELS+2)) {
		int r = getrandom(4);
		switch(r) {
			case 0:
				return R_OCEAN;
			case 1:
				return R_CHASM;
			case 2:
				return R_DFOREST;
			case 3:
				return R_GROTTO;
			default:
				return (0);
		}
	}

	// surface region
	if ( pReg->zloc == 1 ) {
		int r = getrandom(64);
		switch (lat)
		{
		case 0: /* Arctic regions */
			if (r < 32) return R_TUNDRA;
			if (r < 40) return R_MOUNTAIN;
			if (r < 48) return R_FOREST;
			return R_PLAIN;
		case 1: /* Colder regions */
			if (r < 8) return R_TUNDRA;
			if (r < 24) return R_PLAIN;
			if (r < 40) return R_FOREST;
			if (r < 48) return R_MOUNTAIN;
			return R_SWAMP;
		case 2: /* Warmer regions */
			if (r < 16) return R_PLAIN;
			if (r < 28) return R_FOREST;
			if (r < 36) return R_MOUNTAIN;
			if (r < 44) return R_SWAMP;
			if (r < 52) return R_JUNGLE;
			return R_DESERT;
		case 3: /* tropical */
			if (r < 16) return R_PLAIN;
			if (r < 24) return R_MOUNTAIN;
			if (r < 36) return R_SWAMP;
			if (r < 48) return R_JUNGLE;
			return R_DESERT;
		}
		return R_OCEAN;
	}

	if ( pReg->zloc == 0 )
	{
		//
		// This really shouldn't ever get called.
		//
		return( R_NEXUS );
	}

	//
	// This really shouldn't get called either
	//
	return( R_OCEAN );
}
Esempio n. 19
0
int AGetName(int town, ARegion *reg)
{
	int unique, rnd, syllables, i, trail, port, similar;
	unsigned int u;
	char temp[80];
	AString *name;

	port = 0;
	if (town) {
		for (i = 0; i < NDIRS; i++)
			if (reg->neighbors[i] &&
					TerrainDefs[reg->neighbors[i]->type].similar_type == R_OCEAN)
				port = 1;
	}

	unique = 0;
	while (!unique) {
		rnd = getrandom(tSyll);
		for (syllables = 0; rnd >= syllprob[syllables]; syllables++)
			rnd -= syllprob[syllables];
		syllables++;
		temp[0] = 0;
		trail = 0;
		while (syllables-- > 0) {
			if (!syllables) {
				// Might replace the last syllable with a
				// terrain specific suffix
				rnd = getrandom(400);
				similar = TerrainDefs[reg->type].similar_type;
				// Use forest names for underforest
				if (similar == R_UFOREST)
					similar = R_FOREST;
				// ocean (water) names for lakes
				if (similar == R_LAKE)
					similar = R_OCEAN;
				// and plains names for cavern
				if (similar == R_CAVERN)
					similar = R_PLAIN;
				for (u = 0; u < sizeof(ts) / sizeof(ts[0]); u++) {
					if (ts[u].terrain == similar ||
							ts[u].terrain == -1 ||
							(ts[u].town && town) ||
							(ts[u].port && port)) {
						if (rnd >= ts[u].prob)
							rnd -= ts[u].prob;
						else {
							if (trail) {
								switch(ts[u].word[0]) {
									case 'a':
									case 'e':
									case 'i':
									case 'o':
									case 'u':
										strcat(temp, "'");
										break;
									default:
										break;
								}
							}
							strcat(temp, ts[u].word);
							break;
						}
					}
				}
				if (u < sizeof(ts) / sizeof(ts[0]))
					break;
			}
			if (getrandom(5) > 0) {
				// 4 out of 5 syllables start with a consonant sequence
				rnd = getrandom(tIC);
				for (i = 0; rnd >= ic[i].prob; i++)
					rnd -= ic[i].prob;
				strcat(temp, ic[i].word);
			} else if (trail) {
				// separate adjacent vowels
				strcat(temp, "'");
			}
			// All syllables have a vowel sequence
			rnd = getrandom(tV);
			for (i = 0; rnd >= v[i].prob; i++)
				rnd -= v[i].prob;
			strcat(temp, v[i].word);
			if (getrandom(5) > 1) {
				// 3 out of 5 syllables end with a consonant sequence
				rnd = getrandom(tFC);
				for (i = 0; rnd >= fc[i].prob; i++)
					rnd -= fc[i].prob;
				strcat(temp, fc[i].word);
				trail = 0;
			} else {
				trail = 1;
			}
		}
		temp[0] = toupper(temp[0]);
		unique = 1;
		forlist(&regionnames) {
			name = (AString *) elem;
			if (*name == temp) {
				unique = 0;
				break;
			}
		}
		if (strlen(temp) > 12)
			unique = 0;
	}

	nnames++;
	if (town)
		ntowns++;
	else
		nregions++;

	name = new AString(temp);
	regionnames.Add(name);

	return regionnames.Num();
}
Esempio n. 20
0
int snake_newfood(struct snake* buf, int w, int h)
{
	buf[0].x = getrandom() % w;
	buf[0].y = getrandom() % h;
	return 0;
}
Esempio n. 21
0
void arc4random_stir(void) {
  n=0;
  if ((size_t)getrandom(buf,sizeof(buf),GRND_NONBLOCK) != sizeof(buf))
    abort();
}
Esempio n. 22
0
/*
 * When we are "the server", this starts SET/ACK mode
 * When we are "the client", this starts REQ/REPLY mode
 */
static int
cfg_initiator_send_ATTR(struct message *msg)
{
	struct sa      *isakmp_sa = msg->isakmp_sa;
	struct ipsec_exch *ie = msg->exchange->data;
	u_int8_t       *hashp = 0, *attrp, *attr;
	size_t          attrlen, off;
	char           *id_string, *cfg_mode, *field;
	struct sockaddr *sa;
#define CFG_ATTR_BIT_MAX ISAKMP_CFG_ATTR_FUTURE_MIN	/* XXX */
	bitstr_t        bit_decl(attrbits, CFG_ATTR_BIT_MAX);
	u_int16_t       bit, length;
	u_int32_t       life;

	if (msg->exchange->phase == 2) {
		hashp = cfg_add_hash(msg);
		if (!hashp)
			return -1;
	}
	/* We initiated this exchange, check isakmp_sa for other side.  */
	if (isakmp_sa->initiator)
		id_string = ipsec_id_string(isakmp_sa->id_r,
		    isakmp_sa->id_r_len);
	else
		id_string = ipsec_id_string(isakmp_sa->id_i,
		    isakmp_sa->id_i_len);
	if (!id_string) {
		log_print("cfg_initiator_send_ATTR: cannot parse ID");
		goto fail;
	}
	/* Check for attribute list to send to the other side */
	attrlen = 0;
	bit_nclear(attrbits, 0, CFG_ATTR_BIT_MAX - 1);

	cfg_mode = conf_get_str(id_string, "Mode");
	if (!cfg_mode || strcmp(cfg_mode, "SET") == 0) {
		/* SET/ACK mode */
		ie->cfg_type = ISAKMP_CFG_SET;

		LOG_DBG((LOG_NEGOTIATION, 10,
		    "cfg_initiator_send_ATTR: SET/ACK mode"));

#define ATTRFIND(STR,ATTR4,LEN4,ATTR6,LEN6) do				\
	{								\
		if ((sa = conf_get_address (id_string, STR)) != NULL)	\
			switch (sa->sa_family) {			\
			case AF_INET:					\
				bit_set (attrbits, ATTR4);		\
				attrlen += ISAKMP_ATTR_SZ + LEN4;	\
				break;					\
			case AF_INET6:					\
				bit_set (attrbits, ATTR6);		\
				attrlen += ISAKMP_ATTR_SZ + LEN6;	\
				break;					\
			default:					\
				break;					\
			}						\
		free (sa);						\
	} while (0)

		/*
		 * XXX We don't simultaneously support IPv4 and IPv6
		 * addresses.
		 */
		ATTRFIND("Address", ISAKMP_CFG_ATTR_INTERNAL_IP4_ADDRESS, 4,
		    ISAKMP_CFG_ATTR_INTERNAL_IP6_ADDRESS, 16);
		ATTRFIND("Netmask", ISAKMP_CFG_ATTR_INTERNAL_IP4_NETMASK, 4,
		    ISAKMP_CFG_ATTR_INTERNAL_IP6_NETMASK, 16);
		ATTRFIND("Nameserver", ISAKMP_CFG_ATTR_INTERNAL_IP4_DNS, 4,
		    ISAKMP_CFG_ATTR_INTERNAL_IP6_DNS, 16);
		ATTRFIND("WINS-server", ISAKMP_CFG_ATTR_INTERNAL_IP4_NBNS, 4,
		    ISAKMP_CFG_ATTR_INTERNAL_IP6_NBNS, 16);
		ATTRFIND("DHCP-server", ISAKMP_CFG_ATTR_INTERNAL_IP4_DHCP, 4,
		    ISAKMP_CFG_ATTR_INTERNAL_IP6_DHCP, 16);
#ifdef notyet
		ATTRFIND("Network", ISAKMP_CFG_ATTR_INTERNAL_IP4_SUBNET, 8,
		    ISAKMP_CFG_ATTR_INTERNAL_IP6_SUBNET, 17);
#endif
#undef ATTRFIND

		if (conf_get_str(id_string, "Lifetime")) {
			bit_set(attrbits,
			    ISAKMP_CFG_ATTR_INTERNAL_ADDRESS_EXPIRY);
			attrlen += ISAKMP_ATTR_SZ + 4;
		}
	} else {
		struct conf_list *alist;
		struct conf_list_node *anode;

		ie->cfg_type = ISAKMP_CFG_REQUEST;

		LOG_DBG((LOG_NEGOTIATION, 10,
		    "cfg_initiator_send_ATTR: REQ/REPLY mode"));

		alist = conf_get_list(id_string, "Attributes");
		if (alist) {
			for (anode = TAILQ_FIRST(&alist->fields); anode;
			    anode = TAILQ_NEXT(anode, link)) {
				if (strcasecmp(anode->field, "Address") == 0) {
					bit_set(attrbits, ISAKMP_CFG_ATTR_INTERNAL_IP4_ADDRESS);
					bit_set(attrbits, ISAKMP_CFG_ATTR_INTERNAL_IP6_ADDRESS);
					attrlen += ISAKMP_ATTR_SZ * 2;
				} else if (strcasecmp(anode->field, "Netmask")
				    == 0) {
					bit_set(attrbits, ISAKMP_CFG_ATTR_INTERNAL_IP4_NETMASK);
					bit_set(attrbits, ISAKMP_CFG_ATTR_INTERNAL_IP6_NETMASK);
					attrlen += ISAKMP_ATTR_SZ * 2;
				} else if (strcasecmp(anode->field,
				    "Nameserver") == 0) {
					bit_set(attrbits, ISAKMP_CFG_ATTR_INTERNAL_IP4_DNS);
					bit_set(attrbits, ISAKMP_CFG_ATTR_INTERNAL_IP6_DNS);
					attrlen += ISAKMP_ATTR_SZ * 2;
				} else if (strcasecmp(anode->field,
				    "WINS-server") == 0) {
					bit_set(attrbits, ISAKMP_CFG_ATTR_INTERNAL_IP4_NBNS);
					bit_set(attrbits, ISAKMP_CFG_ATTR_INTERNAL_IP6_NBNS);
					attrlen += ISAKMP_ATTR_SZ * 2;
				} else if (strcasecmp(anode->field,
				    "DHCP-server") == 0) {
					bit_set(attrbits, ISAKMP_CFG_ATTR_INTERNAL_IP4_DHCP);
					bit_set(attrbits, ISAKMP_CFG_ATTR_INTERNAL_IP6_DHCP);
					attrlen += ISAKMP_ATTR_SZ * 2;
				} else if (strcasecmp(anode->field,
				    "Lifetime") == 0) {
					bit_set(attrbits, ISAKMP_CFG_ATTR_INTERNAL_ADDRESS_EXPIRY);
					attrlen += ISAKMP_ATTR_SZ;
				} else {
					log_print("cfg_initiator_send_ATTR: "
					    "unknown attribute %.20s in "
					    "section [%s]", anode->field,
					    id_string);
				}
			}

			conf_free_list(alist);
		}
	}

	if (attrlen == 0) {
		/* No data found.  */
		log_print("cfg_initiator_send_ATTR: no IKECFG attributes "
		    "found for [%s]", id_string);

		/*
		 * We can continue, but this indicates a configuration error
		 * that the user probably will want to correct.
		 */
		free(id_string);
		return 0;
	}
	attrlen += ISAKMP_ATTRIBUTE_SZ;
	attrp = calloc(1, attrlen);
	if (!attrp) {
		log_error("cfg_initiator_send_ATTR: calloc (1, %lu) failed",
		    (unsigned long)attrlen);
		goto fail;
	}
	if (message_add_payload(msg, ISAKMP_PAYLOAD_ATTRIBUTE, attrp, attrlen,
	    1)) {
		free(attrp);
		goto fail;
	}
	SET_ISAKMP_ATTRIBUTE_TYPE(attrp, ie->cfg_type);
	getrandom((u_int8_t *) & ie->cfg_id, sizeof ie->cfg_id);
	SET_ISAKMP_ATTRIBUTE_ID(attrp, ie->cfg_id);

	off = ISAKMP_ATTRIBUTE_SZ;

	/*
	 * Use the bitstring built previously to collect the right
	 * parameters for attrp.
         */
	for (bit = 0; bit < CFG_ATTR_BIT_MAX; bit++)
		if (bit_test(attrbits, bit)) {
			attr = attrp + off;
			SET_ISAKMP_ATTR_TYPE(attr, bit);

			if (ie->cfg_type == ISAKMP_CFG_REQUEST) {
				off += ISAKMP_ATTR_SZ;
				continue;
			}
			/* All the other are similar, this is the odd one.  */
			if (bit == ISAKMP_CFG_ATTR_INTERNAL_ADDRESS_EXPIRY) {
				life = conf_get_num(id_string, "Lifetime",
				    1200);
				SET_ISAKMP_ATTR_LENGTH_VALUE(attr, 4);
				encode_32(attr + ISAKMP_ATTR_VALUE_OFF, life);
				off += ISAKMP_ATTR_SZ + 4;
				continue;
			}
			switch (bit) {
			case ISAKMP_CFG_ATTR_INTERNAL_IP4_ADDRESS:
			case ISAKMP_CFG_ATTR_INTERNAL_IP4_NETMASK:
			case ISAKMP_CFG_ATTR_INTERNAL_IP4_DNS:
			case ISAKMP_CFG_ATTR_INTERNAL_IP4_DHCP:
			case ISAKMP_CFG_ATTR_INTERNAL_IP4_NBNS:
				length = 4;
				break;

			case ISAKMP_CFG_ATTR_INTERNAL_IP6_ADDRESS:
			case ISAKMP_CFG_ATTR_INTERNAL_IP6_NETMASK:
			case ISAKMP_CFG_ATTR_INTERNAL_IP6_DNS:
			case ISAKMP_CFG_ATTR_INTERNAL_IP6_DHCP:
			case ISAKMP_CFG_ATTR_INTERNAL_IP6_NBNS:
				length = 16;
				break;

			default:
				length = 0;	/* Silence gcc.  */
			}

			switch (bit) {
			case ISAKMP_CFG_ATTR_INTERNAL_IP4_ADDRESS:
			case ISAKMP_CFG_ATTR_INTERNAL_IP6_ADDRESS:
				field = "Address";
				break;
			case ISAKMP_CFG_ATTR_INTERNAL_IP4_NETMASK:
			case ISAKMP_CFG_ATTR_INTERNAL_IP6_NETMASK:
				field = "Netmask";
				break;
			case ISAKMP_CFG_ATTR_INTERNAL_IP4_DNS:
			case ISAKMP_CFG_ATTR_INTERNAL_IP6_DNS:
				field = "Nameserver";
				break;
			case ISAKMP_CFG_ATTR_INTERNAL_IP4_DHCP:
			case ISAKMP_CFG_ATTR_INTERNAL_IP6_DHCP:
				field = "DHCP-server";
				break;
			case ISAKMP_CFG_ATTR_INTERNAL_IP4_NBNS:
			case ISAKMP_CFG_ATTR_INTERNAL_IP6_NBNS:
				field = "WINS-server";
				break;
			default:
				field = 0;	/* Silence gcc.  */
			}

			sa = conf_get_address(id_string, field);

			SET_ISAKMP_ATTR_LENGTH_VALUE(attr, length);
			memcpy(attr + ISAKMP_ATTR_VALUE_OFF,
			    sockaddr_addrdata(sa), length);

			free(sa);

			off += ISAKMP_ATTR_SZ + length;
		}
	if (msg->exchange->phase == 2)
		if (cfg_finalize_hash(msg, hashp, attrp, attrlen))
			goto fail;

	return 0;

fail:
	free(id_string);
	return -1;
}