Example #1
0
int sys_select_intr(int maxfd, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *tval)
{
	int ret;
	fd_set *readfds2, readfds_buf, *writefds2, writefds_buf, *errorfds2, errorfds_buf;
	struct timeval tval2, *ptval, end_time;

	readfds2 = (readfds ? &readfds_buf : NULL);
	writefds2 = (writefds ? &writefds_buf : NULL);
	errorfds2 = (errorfds ? &errorfds_buf : NULL);
	if (tval) {
		GetTimeOfDay(&end_time);
		end_time.tv_sec += tval->tv_sec;
		end_time.tv_usec += tval->tv_usec;
		end_time.tv_sec += end_time.tv_usec / 1000000;
		end_time.tv_usec %= 1000000;
		errno = 0;
		tval2 = *tval;
		ptval = &tval2;
	} else {
		ptval = NULL;
	}

	do {
		if (readfds)
			readfds_buf = *readfds;
		if (writefds)
			writefds_buf = *writefds;
		if (errorfds)
			errorfds_buf = *errorfds;
		if (ptval && (errno == EINTR)) {
			struct timeval now_time;
			SMB_BIG_INT tdif;

			GetTimeOfDay(&now_time);
			tdif = usec_time_diff(&end_time, &now_time);
			if (tdif <= 0) {
				ret = 0; /* time expired. */
				break;
			}
			ptval->tv_sec = tdif / 1000000;
			ptval->tv_usec = tdif % 1000000;
		}

		/* We must use select and not sys_select here. If we use
		   sys_select we'd lose the fact a signal occurred when sys_select
		   read a byte from the pipe. Fix from Mark Weaver
		   <*****@*****.**>
		*/
		ret = select(maxfd, readfds2, writefds2, errorfds2, ptval);
	} while (ret == -1 && errno == EINTR);

	if (readfds)
		*readfds = readfds_buf;
	if (writefds)
		*writefds = writefds_buf;
	if (errorfds)
		*errorfds = errorfds_buf;

	return ret;
}
Example #2
0
/* fake timestamps */
static void onefs_adjust_stat_time(struct connection_struct *conn,
				   const char *fname, SMB_STRUCT_STAT *sbuf)
{
	struct onefs_vfs_share_config cfg;
	struct timeval tv_now = {0, 0};
	bool static_mtime = False;
	bool static_atime = False;

	if (!onefs_get_config(SNUM(conn),
			      ONEFS_VFS_CONFIG_FAKETIMESTAMPS, &cfg)) {
		return;
	}

	if (IS_MTIME_STATIC_PATH(conn, &cfg, fname)) {
		sbuf->st_ex_mtime = sbuf->st_ex_btime;
		static_mtime = True;
	}
	if (IS_ATIME_STATIC_PATH(conn, &cfg, fname)) {
		sbuf->st_ex_atime = sbuf->st_ex_btime;
		static_atime = True;
	}

	if (IS_CTIME_NOW_PATH(conn, &cfg, fname)) {
		if (cfg.ctime_slop < 0) {
			sbuf->st_ex_btime.tv_sec = INT_MAX - 1;
		} else {
			GetTimeOfDay(&tv_now);
			sbuf->st_ex_btime.tv_sec = tv_now.tv_sec +
			    cfg.ctime_slop;
		}
	}

	if (!static_mtime && IS_MTIME_NOW_PATH(conn,&cfg,fname)) {
		if (cfg.mtime_slop < 0) {
			sbuf->st_ex_mtime.tv_sec = INT_MAX - 1;
		} else {
			if (tv_now.tv_sec == 0)
				GetTimeOfDay(&tv_now);
			sbuf->st_ex_mtime.tv_sec = tv_now.tv_sec +
			    cfg.mtime_slop;
		}
	}
	if (!static_atime && IS_ATIME_NOW_PATH(conn,&cfg,fname)) {
		if (cfg.atime_slop < 0) {
			sbuf->st_ex_atime.tv_sec = INT_MAX - 1;
		} else {
			if (tv_now.tv_sec == 0)
				GetTimeOfDay(&tv_now);
			sbuf->st_ex_atime.tv_sec = tv_now.tv_sec +
			    cfg.atime_slop;
		}
	}
}
Example #3
0
/* Format messages as per RFC5424
 *
 * <165>1 2003-08-24T05:14:15.000003-07:00 192.0.2.1
 *         myproc 8710 - - %% It's time to make the do-nuts.
 */
static int format_rfc5424(int dbglevel, struct ctdb_syslog_sock_state *state,
			  const char *str, char *buf, int bsize)
{
	int pri;
	struct timeval tv;
	struct timeval_buf tvbuf;
	int len, s;

	/* Header */
	pri = CTDB_SYSLOG_FACILITY | ctdb_debug_to_syslog_level(dbglevel);
	GetTimeOfDay(&tv);
	len = snprintf(buf, bsize,
		       "<%d>1 %s %s %s %u - - ",
		       pri, timeval_str_buf(&tv, true, true, &tvbuf),
		       state->hostname, state->app_name, getpid());
	/* A truncated header is not useful... */
	if (len >= bsize) {
		return -1;
	}

	/* Message */
	s = snprintf(&buf[len], bsize - len, "%s %s", debug_extra, str);
	len = MIN(len + s, bsize - 1);

	return len;
}
Example #4
0
NTSTATUS file_new(struct smb_request *req, connection_struct *conn,
		  files_struct **result)
{
	struct smbd_server_connection *sconn = conn->sconn;
	files_struct *fsp;
	NTSTATUS status;

	status = fsp_new(conn, conn, &fsp);
	if (!NT_STATUS_IS_OK(status)) {
		return status;
	}

	GetTimeOfDay(&fsp->open_time);

	if (sconn->conn) {
		struct smbXsrv_open *op = NULL;
		NTTIME now = timeval_to_nttime(&fsp->open_time);

		status = smbXsrv_open_create(sconn->conn,
					     conn->session_info,
					     now, &op);
		if (!NT_STATUS_IS_OK(status)) {
			file_free(NULL, fsp);
			return status;
		}
		fsp->op = op;
		op->compat = fsp;
		fsp->fnum = op->local_id;
		fsp->fh->gen_id = smbXsrv_open_hash(op);
	}

	/*
	 * Create an smb_filename with "" for the base_name.  There are very
	 * few NULL checks, so make sure it's initialized with something. to
	 * be safe until an audit can be done.
	 */
	fsp->fsp_name = synthetic_smb_fname(fsp, "", NULL, NULL);
	if (fsp->fsp_name == NULL) {
		file_free(NULL, fsp);
		return NT_STATUS_NO_MEMORY;
	}

	DEBUG(5,("allocated file structure %s (%u used)\n",
		 fsp_fnum_dbg(fsp), (unsigned int)sconn->num_files));

	if (req != NULL) {
		fsp->mid = req->mid;
		req->chain_fsp = fsp;
	}

	/* A new fsp invalidates the positive and
	  negative fsp_fi_cache as the new fsp is pushed
	  at the start of the list and we search from
	  a cache hit to the *end* of the list. */

	ZERO_STRUCT(sconn->fsp_fi_cache);

	*result = fsp;
	return NT_STATUS_OK;
}
double bootSeconds()
{
#ifdef SC_DARWIN
	return 1e-9 * (double)AudioConvertHostTimeToNanos(AudioGetCurrentHostTime());
#else
	return GetTimeOfDay();
#endif
}
double elapsedTime()
{
#ifdef SC_DARWIN
	return 1e-9 * (double)(AudioConvertHostTimeToNanos(AudioGetCurrentHostTime()) - gHostStartNanos);
#else
	return GetTimeOfDay();
#endif
}
Example #7
0
void* CopyDefaultAndReleaseInSingleThread(void* arg)
{
    OSStatus result;

    double endTime = GetTimeOfDay() + kTestLength;
    do
    {
        SecKeychainRef kc;
        result  = SecKeychainCopyDefault(&kc);
        CFRelease(kc);

        if (result != noErr)
        {
            return NULL;
        }

    } while (GetTimeOfDay() < endTime);

    return NULL;
}
Example #8
0
void GameView::UpdateMonsterSpawning()
{
    if (GetTimeOfDay() != TimeOfDay::Night) return;

    float spawnRate = GetMonsterSpawnRate();
    m_monsterSpawnTime -= ODT;
    if (m_monsterSpawnTime <= 0.f)
    {
        m_monsterSpawnTime = spawnRate;
        SpawnMonster();
    }
}
Example #9
0
void smbprofile_dump_schedule_timer(void)
{
	struct timeval tv;

	GetTimeOfDay(&tv);
	tv.tv_sec += 1;

	smbprofile_state.internal.te = tevent_add_timer(
				smbprofile_state.internal.ev,
				smbprofile_state.internal.ev,
				tv,
				smbprofile_dump_timer,
				NULL);
}
Example #10
0
/**
**	@brief	Get or add a time of day
**
**	@param	ident	The time of day's string identifier
**
**	@return	The time of day if found, or a newly-created one otherwise
*/
CTimeOfDay *CTimeOfDay::GetOrAddTimeOfDay(const std::string &ident)
{
	CTimeOfDay *time_of_day = GetTimeOfDay(ident, false);
	
	if (!time_of_day) {
		time_of_day = new CTimeOfDay;
		time_of_day->Ident = ident;
		time_of_day->ID = TimesOfDay.size();
		TimesOfDay.push_back(time_of_day);
		TimesOfDayByIdent[ident] = time_of_day;
	}
	
	return time_of_day;
}
Example #11
0
static int do_reseed(int fd)
{
	unsigned char seed_inbuf[40];
	uint32_t v1, v2; struct timeval tval; pid_t mypid;
	int reseed_data = 0;

	if (fd == -1) {
		fd = open( "/dev/urandom", O_RDONLY,0);
		if (fd != -1) {
			smb_set_close_on_exec(fd);
		}
	}
	if (fd != -1
	    && (read(fd, seed_inbuf, sizeof(seed_inbuf)) == sizeof(seed_inbuf))) {
		seed_random_stream(seed_inbuf, sizeof(seed_inbuf));
		return fd;
	}

	/* Add in some secret file contents */

	do_filehash("/etc/shadow", &seed_inbuf[0]);

	/*
	 * Add the counter, time of day, and pid.
	 */

	GetTimeOfDay(&tval);
	mypid = getpid();
	v1 = (counter++) + mypid + tval.tv_sec;
	v2 = (counter++) * mypid + tval.tv_usec;

	SIVAL(seed_inbuf, 32, v1 ^ IVAL(seed_inbuf, 32));
	SIVAL(seed_inbuf, 36, v2 ^ IVAL(seed_inbuf, 36));

	/*
	 * Add any user-given reseed data.
	 */

	get_rand_reseed_data(&reseed_data);
	if (reseed_data) {
		size_t i;
		for (i = 0; i < sizeof(seed_inbuf); i++)
			seed_inbuf[i] ^= ((char *)(&reseed_data))[i % sizeof(reseed_data)];
	}

	seed_random_stream(seed_inbuf, sizeof(seed_inbuf));

	return -1;
}
Example #12
0
static BOOL timeout_until(struct timeval *timeout, const struct timeval *endtime)
{
	struct timeval now;
	SMB_BIG_INT t_dif;

	GetTimeOfDay(&now);

	t_dif = usec_time_diff(endtime, &now);
	if (t_dif <= 0) {
		return False;
	}

	timeout->tv_sec = (t_dif / (SMB_BIG_INT)1000000);
	timeout->tv_usec = (t_dif % (SMB_BIG_INT)1000000);
	return True;
}
Example #13
0
void GameView::OnRender()
{
    if (m_gameover)
        return;

#if defined(_DEBUG)
    auto pFont = OGetBMFont("font.fnt");
    pFont->draw("Time: " + std::to_string(GetDayTimeHour()), Vector2::Zero);
    switch (GetTimeOfDay())
    {
        case TimeOfDay::Night:
            pFont->draw("Night", Vector2(0, 20));
            break;
        case TimeOfDay::Dawn:
            pFont->draw("Dawn", Vector2(0, 20));
            break;
        case TimeOfDay::Day:
            pFont->draw("Day", Vector2(0, 20));
            break;
        case TimeOfDay::Dusk:
            pFont->draw("Dusk", Vector2(0, 20));
            break;
    }
    pFont->draw("Monster spawn Rate: " + std::to_string(GetMonsterSpawnRate()), Vector2(0, 40));
    pFont->draw("Monster count: " + std::to_string(Monster::count), Vector2(0, 60));
    pFont->draw("Day: " + std::to_string(m_day), Vector2(0, 80));

#if 0 // Show path
    OSB->end();
    for (auto pEntity : m_entities)
    {
        auto pMonster = dynamic_cast<Monster*>(pEntity);
        if (pMonster)
        {
            OPB->begin(onut::ePrimitiveType::LINE_STRIP, nullptr, GetRootNode()->GetTransform());
            for (auto& p : pMonster->m_path)
            {
                OPB->draw(p);
            }
            OPB->end();
        }
    }
    OSB->begin();
#endif
#endif
}
Example #14
0
/*******************************************************************
Get the next challenge value - no repeats.
********************************************************************/
void generate_next_challenge(char *challenge)
{
	unsigned char buf[16];
	static int counter = 0;
	struct timeval tval;
	int v1,v2;

	/* get a sort-of random number */
	GetTimeOfDay(&tval);
	v1 = (counter++) + getpid() + tval.tv_sec;
	v2 = (counter++) * getpid() + tval.tv_usec;
	SIVAL(challenge,0,v1);
	SIVAL(challenge,4,v2);

	/* mash it up with md4 */
	mdfour(buf, (unsigned char *)challenge, 8);

	memcpy(saved_challenge, buf, 8);
	memcpy(challenge,buf,8);
	challenge_sent = True;
}
Example #15
0
void run_events(void)
{
    struct timeval now;

    if (timed_events == NULL) {
        /* No syscall if there are no events */
        DEBUG(11, ("run_events: No events\n"));
        return;
    }

    GetTimeOfDay(&now);

    if (timeval_compare(&now, &timed_events->when) < 0) {
        /* Nothing to do yet */
        DEBUG(11, ("run_events: Nothing to do\n"));
        return;
    }

    DEBUG(10, ("Running event \"%s\" %lx\n", timed_events->event_name,
               (unsigned long)timed_events));

    timed_events->handler(timed_events, &now, timed_events->private_data);
    return;
}
Example #16
0
long64 GetMillisecondCount() {
    int sec, usec;
    GetTimeOfDay(&sec, &usec);
    return ((long64)sec) * 1000 + usec / 1000;
}
Example #17
0
NTSTATUS file_new(struct smb_request *req, connection_struct *conn,
		  files_struct **result)
{
	int i;
	files_struct *fsp;
	NTSTATUS status;

	/* we want to give out file handles differently on each new
	   connection because of a common bug in MS clients where they try to
	   reuse a file descriptor from an earlier smb connection. This code
	   increases the chance that the errant client will get an error rather
	   than causing corruption */
	if (first_file == 0) {
		first_file = (sys_getpid() ^ (int)time(NULL)) % real_max_open_files;
	}

	/* TODO: Port the id-tree implementation from Samba4 */

	i = bitmap_find(file_bmap, first_file);
	if (i == -1) {
		DEBUG(0,("ERROR! Out of file structures\n"));
		/* TODO: We have to unconditionally return a DOS error here,
		 * W2k3 even returns ERRDOS/ERRnofids for ntcreate&x with
		 * NTSTATUS negotiated */
		return NT_STATUS_TOO_MANY_OPENED_FILES;
	}

	/*
	 * Make a child of the connection_struct as an fsp can't exist
	 * indepenedent of a connection.
	 */
	fsp = talloc_zero(conn, struct files_struct);
	if (!fsp) {
		return NT_STATUS_NO_MEMORY;
	}

	/*
	 * This can't be a child of fsp because the file_handle can be ref'd
	 * when doing a dos/fcb open, which will then share the file_handle
	 * across multiple fsps.
	 */
	fsp->fh = talloc_zero(conn, struct fd_handle);
	if (!fsp->fh) {
		TALLOC_FREE(fsp);
		return NT_STATUS_NO_MEMORY;
	}

	fsp->fh->ref_count = 1;
	fsp->fh->fd = -1;

	fsp->conn = conn;
	fsp->fh->gen_id = get_gen_count();
	GetTimeOfDay(&fsp->open_time);

	first_file = (i+1) % real_max_open_files;

	bitmap_set(file_bmap, i);
	files_used++;

	fsp->fnum = i + FILE_HANDLE_OFFSET;
	SMB_ASSERT(fsp->fnum < 65536);

	/*
	 * Create an smb_filename with "" for the base_name.  There are very
	 * few NULL checks, so make sure it's initialized with something. to
	 * be safe until an audit can be done.
	 */
	status = create_synthetic_smb_fname(fsp, "", NULL, NULL,
					    &fsp->fsp_name);
	if (!NT_STATUS_IS_OK(status)) {
		TALLOC_FREE(fsp);
		TALLOC_FREE(fsp->fh);
	}

	DLIST_ADD(Files, fsp);

	DEBUG(5,("allocated file structure %d, fnum = %d (%d used)\n",
		 i, fsp->fnum, files_used));

	if (req != NULL) {
		req->chain_fsp = fsp;
	}

	/* A new fsp invalidates the positive and
	  negative fsp_fi_cache as the new fsp is pushed
	  at the start of the list and we search from
	  a cache hit to the *end* of the list. */

	ZERO_STRUCT(fsp_fi_cache);

	conn->num_files_open++;

	*result = fsp;
	return NT_STATUS_OK;
}
void Reaction::React(NPC *who, Perception *pcpt)
{
    CS_ASSERT(who);

    // Check if the perception is a match for this reaction
    if (!pcpt->ShouldReact(this,who))
    {
        if (who->IsDebugging(20))
        {
            who->Printf(20, "Reaction '%s' skipping perception %s", GetEventType(), pcpt->ToString().GetDataSafe());
        }
        return;
    }

    // If dead we should not react unless reactWhenDead is set
    if (!(who->IsAlive() || reactWhenDead))
    {
        who->Printf(5, "Only react to '%s' when alive", GetEventType());
        return;
    }

    // Check if the active behavior should not be interrupted.
    if (who->GetCurrentBehavior() && DoNotInterrupt(who->GetCurrentBehavior()))
    {
        who->Printf(5,"Prevented from reacting to '%s' while not interrupt behavior '%s' is active",
                    GetEventType(),who->GetCurrentBehavior()->GetName());
        return; 
    } 

    // Check if this reaction is limited to only interrupt some given behaviors.
    if (who->GetCurrentBehavior() && OnlyInterrupt(who->GetCurrentBehavior()))
    {
        who->Printf(5,"Prevented from reacting to '%s' since behavior '%s' should not be interrupted",
                    GetEventType(),who->GetCurrentBehavior()->GetName());
        return; 
    } 



    // We should no react and triggerd all affected behaviors

    // For debug get the time this reaction was triggered
    GetTimeOfDay(lastTriggered);


    // Adjust the needs for the triggerd behaviors
    for (size_t i = 0; i < affected.GetSize(); i++)
    {

        // When activeOnly flag is set we should do nothing
        // if the affected behaviour is inactive.
        if (activeOnly && !affected[i]->IsActive() )
            break;
        
        // When inactiveOnly flag is set we should do nothing
        // if the affected behaviour is active.
        if (inactiveOnly && affected[i]->IsActive() )
            break;


        who->Printf(2, "Reaction '%s' reacting to perception %s", GetEventType(), pcpt->ToString().GetDataSafe());
        switch (desireType)
        {
        case DESIRE_NONE:
            who->Printf(10, "No change to need for behavior %s.", affected[i]->GetName());
            break;
        case DESIRE_ABSOLUTE:
            who->Printf(10, "Setting %1.1f need to behavior %s", desireValue, affected[i]->GetName());
            affected[i]->ApplyNeedAbsolute(who, desireValue);
            break;
        case DESIRE_DELTA:
            who->Printf(10, "Adding %1.1f need to behavior %s", desireValue, affected[i]->GetName());
            affected[i]->ApplyNeedDelta(who, desireValue);
            break;
        case DESIRE_GUARANTIED:
            who->Printf(10, "Guarantied need to behavior %s", affected[i]->GetName());
            
            float highest = 0;
            if (who->GetCurrentBehavior())
            {
                highest = who->GetCurrentBehavior()->CurrentNeed();
            }
            if (who->GetCurrentBehavior() != affected[i])
            {
                affected[i]->ApplyNeedAbsolute(who, highest + 25);
                affected[i]->SetCompletionDecay(-1);
            }
            break;
        }
    }
    
    // Execute the perception
    pcpt->ExecutePerception(who,weight);

    Perception *p = pcpt->MakeCopy();
    who->SetLastPerception(p);

}
Example #19
0
static void send_spoolss_notify2_msg(struct tevent_context *ev,
				     struct messaging_context *msg_ctx,
				     SPOOLSS_NOTIFY_MSG *msg)
{
	struct notify_queue *pnqueue, *tmp_ptr;

	/*
	 * Ensure we only have one job total_bytes and job total_pages for
	 * each job. There is no point in sending multiple messages that match
	 * as they will just cause flickering updates in the client.
	 */

	if ((num_messages < 100) && (msg->type == JOB_NOTIFY_TYPE) 
		&& (msg->field == JOB_NOTIFY_FIELD_TOTAL_BYTES
		    || msg->field == JOB_NOTIFY_FIELD_TOTAL_PAGES ))
	{

		for (tmp_ptr = notify_queue_head; tmp_ptr; tmp_ptr = tmp_ptr->next) 
		{
			if (tmp_ptr->msg->type == msg->type &&
					tmp_ptr->msg->field == msg->field &&
					tmp_ptr->msg->id == msg->id &&
					tmp_ptr->msg->flags == msg->flags &&
					strequal(tmp_ptr->msg->printer, msg->printer)) {

				DEBUG(5,("send_spoolss_notify2_msg: replacing message 0x%02x/0x%02x for "
					 "printer %s in notify_queue\n", msg->type, msg->field, msg->printer));

				tmp_ptr->msg = msg;
				return;
			}
		}
	}

	/* Store the message on the pending queue. */

	pnqueue = talloc(send_ctx, struct notify_queue);
	if (!pnqueue) {
		DEBUG(0,("send_spoolss_notify2_msg: Out of memory.\n"));
		return;
	}

	/* allocate a new msg structure and copy the fields */
	
	if ( !(pnqueue->msg = talloc(send_ctx, SPOOLSS_NOTIFY_MSG)) ) {
		DEBUG(0,("send_spoolss_notify2_msg: talloc() of size [%lu] failed!\n", 
			(unsigned long)sizeof(SPOOLSS_NOTIFY_MSG)));
		return;
	}
	copy_notify2_msg(pnqueue->msg, msg);
	GetTimeOfDay(&pnqueue->tv);
	pnqueue->buf = NULL;
	pnqueue->buflen = 0;

	DEBUG(5, ("send_spoolss_notify2_msg: appending message 0x%02x/0x%02x for printer %s \
to notify_queue_head\n", msg->type, msg->field, msg->printer));

	/*
	 * Note we add to the end of the list to ensure
	 * the messages are sent in the order they were received. JRA.
	 */

	DLIST_ADD_END(notify_queue_head, pnqueue, struct notify_queue *);
	num_messages++;

	if ((notify_event == NULL) && (ev != NULL)) {
		/* Add an event for 1 second's time to send this queue. */
		notify_event = tevent_add_timer(
			ev, NULL, timeval_current_ofs(1,0),
			print_notify_event_send_messages, msg_ctx);
	}

}
Example #20
0
NTSTATUS file_new(struct smb_request *req, connection_struct *conn,
		  files_struct **result)
{
	int i;
	files_struct *fsp;

	/* we want to give out file handles differently on each new
	   connection because of a common bug in MS clients where they try to
	   reuse a file descriptor from an earlier smb connection. This code
	   increases the chance that the errant client will get an error rather
	   than causing corruption */
	if (first_file == 0) {
		first_file = (sys_getpid() ^ (int)time(NULL)) % real_max_open_files;
	}

	/* TODO: Port the id-tree implementation from Samba4 */

	i = bitmap_find(file_bmap, first_file);
	if (i == -1) {
		DEBUG(0,("ERROR! Out of file structures\n"));
		/* TODO: We have to unconditionally return a DOS error here,
		 * W2k3 even returns ERRDOS/ERRnofids for ntcreate&x with
		 * NTSTATUS negotiated */
		return NT_STATUS_TOO_MANY_OPENED_FILES;
	}

	fsp = SMB_MALLOC_P(files_struct);
	if (!fsp) {
		return NT_STATUS_NO_MEMORY;
	}

	ZERO_STRUCTP(fsp);

	fsp->fh = SMB_MALLOC_P(struct fd_handle);
	if (!fsp->fh) {
		SAFE_FREE(fsp);
		return NT_STATUS_NO_MEMORY;
	}

	ZERO_STRUCTP(fsp->fh);

	fsp->fh->ref_count = 1;
	fsp->fh->fd = -1;

	fsp->conn = conn;
	fsp->fh->gen_id = get_gen_count();
	GetTimeOfDay(&fsp->open_time);

	first_file = (i+1) % real_max_open_files;

	bitmap_set(file_bmap, i);
	files_used++;

	fsp->fnum = i + FILE_HANDLE_OFFSET;
	SMB_ASSERT(fsp->fnum < 65536);

	string_set(&fsp->fsp_name,"");
	
	DLIST_ADD(Files, fsp);

	DEBUG(5,("allocated file structure %d, fnum = %d (%d used)\n",
		 i, fsp->fnum, files_used));

	if (req != NULL) {
		req->chain_fsp = fsp;
	}

	/* A new fsp invalidates the positive and
	  negative fsp_fi_cache as the new fsp is pushed
	  at the start of the list and we search from
	  a cache hit to the *end* of the list. */

	ZERO_STRUCT(fsp_fi_cache);

	conn->num_files_open++;

	*result = fsp;
	return NT_STATUS_OK;
}
Example #21
0
void GameView::UpdateTime()
{
    m_dayTime += ODT;
    if (m_dayTime >= DAY_TOTAL_DURATION)
    {
        m_dayTime -= DAY_TOTAL_DURATION;
    }

    static const Color dayAmbient(1, 1, 1, 1);
    static const Color nightAmbient = Color(.10f, .15f, .2f, 1);
    static const Color dawnAmbient(1, .75f, 0, 1);
    static const Color duskAmbient(.75f, .35f, .55f, 1);

    auto timeOfDay = GetTimeOfDay();
    switch (timeOfDay)
    {
        case TimeOfDay::Day:
            m_pGameLayer->SetAmbient(dayAmbient);
            break;
        case TimeOfDay::Night:
            m_pGameLayer->SetAmbient(nightAmbient);
            break;
        case TimeOfDay::Dawn:
        {
            const float fullStart = DAWN_START + (DAWN_END - DAWN_START) * .3f;
            const float fullEnd = DAWN_START + (DAWN_END - DAWN_START) * .6f;
            if (m_dayTime >= fullStart && m_dayTime <= fullEnd) m_pGameLayer->SetAmbient(dawnAmbient);
            else if (m_dayTime < fullStart)
            {
                float dawnPercent = (m_dayTime - DAWN_START) / (fullStart - DAWN_START);
                m_pGameLayer->SetAmbient(Color::Lerp(nightAmbient, dawnAmbient, dawnPercent));
            }
            else
            {
                float dawnPercent = (DAWN_END - m_dayTime) / (DAWN_END - fullEnd);
                m_pGameLayer->SetAmbient(Color::Lerp(dayAmbient, dawnAmbient, dawnPercent));
            }
            break;
        }
        case TimeOfDay::Dusk:
        {
            const float fullStart = DUSK_START + (DUSK_END - DUSK_START) * .3f;
            const float fullEnd = DUSK_START + (DUSK_END - DUSK_START) * .6f;
            if (m_dayTime >= fullStart && m_dayTime <= fullEnd) m_pGameLayer->SetAmbient(duskAmbient);
            else if (m_dayTime < fullStart)
            {
                float duskPercent = (m_dayTime - DUSK_START) / (fullStart - DUSK_START);
                m_pGameLayer->SetAmbient(Color::Lerp(dayAmbient, duskAmbient, duskPercent));
            }
            else
            {
                float duskPercent = (DUSK_END - m_dayTime) / (DUSK_END - fullEnd);
                m_pGameLayer->SetAmbient(Color::Lerp(nightAmbient, duskAmbient, duskPercent));
            }
            break;
        }
    }

    if (timeOfDay != m_previousTimeOfDay)
    {
        m_previousTimeOfDay = timeOfDay;
        OnTimeOfDayChanged(m_previousTimeOfDay);
    }
}
Example #22
0
int main(int argc, char **argv)
{
	TALLOC_CTX *ctx;
	struct samu *out = NULL;
	struct samu *in = NULL;
	NTSTATUS rv;
	int i;
	struct timeval tv;
	BOOL error = False;
	struct passwd *pwd;
	uint8 *buf;
	uint32 expire, min_age, history;
	struct pdb_methods *pdb;
	poptContext pc;
	static const char *backend = NULL;
	static const char *unix_user = "******";
	struct poptOption long_options[] = {
		{"username", 'u', POPT_ARG_STRING, &unix_user, 0, "Unix user to use for testing", "USERNAME" },
		{"backend", 'b', POPT_ARG_STRING, &backend, 0, "Backend to use if not default", "BACKEND[:SETTINGS]" },
		POPT_AUTOHELP
		POPT_COMMON_SAMBA
		POPT_TABLEEND
	};

	load_case_tables();

	pc = poptGetContext("vfstest", argc, (const char **) argv,
			    long_options, 0);

	poptSetOtherOptionHelp(pc, "backend[:settings] username");
	
	while(poptGetNextOpt(pc) != -1);

	poptFreeContext(pc);

	/* Load configuration */
	lp_load(dyn_CONFIGFILE, False, False, True, True);
	setup_logging("pdbtest", True);

	if (backend == NULL) {
		backend = lp_passdb_backend();
	}

	rv = make_pdb_method_name(&pdb, backend);
	if (NT_STATUS_IS_ERR(rv)) {
		fprintf(stderr, "Error initializing '%s': %s\n", backend, get_friendly_nt_error_msg(rv));
		exit(1);
	}
	
	ctx = talloc_init("PDBTEST");
	
	if (!(out = samu_new(ctx))) {
		fprintf(stderr, "Can't create samu structure.\n");
		exit(1);
	}
	
	if ((pwd = getpwnam_alloc(ctx, unix_user)) == NULL) {
		fprintf(stderr, "Error getting user information for %s\n", unix_user);
		exit(1);
	}
	
	samu_set_unix(out, pwd);

	pdb_set_profile_path(out, "\\\\torture\\profile", PDB_SET);
	pdb_set_homedir(out, "\\\\torture\\home", PDB_SET);
	pdb_set_logon_script(out, "torture_script.cmd", PDB_SET);

	pdb_get_account_policy(AP_PASSWORD_HISTORY, &history);
	if (history * PW_HISTORY_ENTRY_LEN < NT_HASH_LEN) {
		buf = (uint8 *)TALLOC(ctx, NT_HASH_LEN);
	} else {
		buf = (uint8 *)TALLOC(ctx, history * PW_HISTORY_ENTRY_LEN);
	}

	/* Generate some random hashes */
	GetTimeOfDay(&tv);
	srand(tv.tv_usec);
	for (i = 0; i < NT_HASH_LEN; i++) {
		buf[i] = (uint8) rand();
	}
	pdb_set_nt_passwd(out, buf, PDB_SET);
	for (i = 0; i < LM_HASH_LEN; i++) {
		buf[i] = (uint8) rand();
	}
	pdb_set_lanman_passwd(out, buf, PDB_SET);
	for (i = 0; i < history * PW_HISTORY_ENTRY_LEN; i++) {
		buf[i] = (uint8) rand();
	}
	pdb_set_pw_history(out, buf, history, PDB_SET);

	pdb_get_account_policy(AP_MAX_PASSWORD_AGE, &expire);
	pdb_get_account_policy(AP_MIN_PASSWORD_AGE, &min_age);
	pdb_set_pass_last_set_time(out, time(NULL), PDB_SET);
	
	if (expire == 0 || expire == (uint32)-1) {
		pdb_set_pass_must_change_time(out, get_time_t_max(), PDB_SET);
	} else {
		pdb_set_pass_must_change_time(out, time(NULL)+expire, PDB_SET);
	}

	if (min_age == (uint32)-1) {
		pdb_set_pass_can_change_time(out, 0, PDB_SET);
	} else {
		pdb_set_pass_can_change_time(out, time(NULL)+min_age, PDB_SET);
	}
	
	/* Create account */
	if (!NT_STATUS_IS_OK(rv = pdb->add_sam_account(pdb, out))) {
		fprintf(stderr, "Error in add_sam_account: %s\n", 
				get_friendly_nt_error_msg(rv));
		exit(1);
	}

	if (!(in = samu_new(ctx))) {
		fprintf(stderr, "Can't create samu structure.\n");
		exit(1);
	}
	
	/* Get account information through getsampwnam() */
	if (NT_STATUS_IS_ERR(pdb->getsampwnam(pdb, in, out->username))) {
		fprintf(stderr, "Error getting sampw of added user %s.\n",
				out->username);
		if (!NT_STATUS_IS_OK(rv = pdb->delete_sam_account(pdb, out))) {
			fprintf(stderr, "Error in delete_sam_account %s\n", 
					get_friendly_nt_error_msg(rv));
		}
		TALLOC_FREE(ctx);
	}
	
	/* Verify integrity */
	if (samu_correct(out, in)) {
		printf("User info written correctly\n");
	} else {
		printf("User info NOT written correctly\n");
		error = True;
	}
	
	/* Delete account */
	if (!NT_STATUS_IS_OK(rv = pdb->delete_sam_account(pdb, out))) {
		fprintf(stderr, "Error in delete_sam_account %s\n", 
					get_friendly_nt_error_msg(rv));
	}

	pdb->setsampwent(pdb, False, 0);
	while (NT_STATUS_IS_OK(pdb->getsampwent(pdb, out))) {
		if (pdb_get_username(out) == NULL) {
			fprintf(stderr, "Got bad username through getsampwent()\n");
			error = True;
			break;
		}
		if (NT_STATUS_IS_ERR(pdb->getsampwnam(pdb, in, pdb_get_username(out)))) {
			fprintf(stderr, "Error getting samu through getsampwnam() of an account we got through getsampwent!\n");
			error = True;
			continue;
		}
		if (!samu_correct(out, in)) {
			printf("Record gotten through getsampwnam() differs from same record through getsampwent()\n");
		}
	}
	pdb->endsampwent(pdb);
	
	TALLOC_FREE(ctx);

	if (error) {
		return 1;
	}
	return 0;
}
Example #23
0
/****************************************************************************
  do a netbios name query to find someones IP
  returns an array of IP addresses or NULL if none
  *count will be set to the number of addresses returned
  ****************************************************************************/
struct in_addr *
name_query (int fd, const char *name, int name_type, BOOL bcast, BOOL recurse,
            struct in_addr to_ip, int *count, void (*fn) (struct packet_struct *))
{
    BOOL found = False;
    int i, retries = 3;
    int retry_time = bcast ? 250 : 2000;
    struct timeval tval;
    struct packet_struct p;
    struct packet_struct *p2;
    struct nmb_packet *nmb = &p.packet.nmb;
    static int name_trn_id = 0;
    struct in_addr *ip_list = NULL;

    memset ((char *) &p, '\0', sizeof (p));
    (*count) = 0;

    if (!name_trn_id)
        name_trn_id = ((unsigned) time (NULL) % (unsigned) 0x7FFF) +
            ((unsigned) getpid () % (unsigned) 100);
    name_trn_id = (name_trn_id + 1) % (unsigned) 0x7FFF;

    nmb->header.name_trn_id = name_trn_id;
    nmb->header.opcode = 0;
    nmb->header.response = False;
    nmb->header.nm_flags.bcast = bcast;
    nmb->header.nm_flags.recursion_available = False;
    nmb->header.nm_flags.recursion_desired = recurse;
    nmb->header.nm_flags.trunc = False;
    nmb->header.nm_flags.authoritative = False;
    nmb->header.rcode = 0;
    nmb->header.qdcount = 1;
    nmb->header.ancount = 0;
    nmb->header.nscount = 0;
    nmb->header.arcount = 0;

    make_nmb_name (&nmb->question.question_name, name, name_type);

    nmb->question.question_type = 0x20;
    nmb->question.question_class = 0x1;

    p.ip = to_ip;
    p.port = NMB_PORT;
    p.fd = fd;
    p.timestamp = time (NULL);
    p.packet_type = NMB_PACKET;

    GetTimeOfDay (&tval);

    if (!send_packet (&p))
        return NULL;

    retries--;

    while (1)
    {
        struct timeval tval2;
        GetTimeOfDay (&tval2);
        if (TvalDiff (&tval, &tval2) > retry_time)
        {
            if (!retries)
                break;
            if (!found && !send_packet (&p))
                return NULL;
            GetTimeOfDay (&tval);
            retries--;
        }

        if ((p2 = receive_packet (fd, NMB_PACKET, 90)))
        {
            struct nmb_packet *nmb2 = &p2->packet.nmb;
            debug_nmb_packet (p2);

            if (nmb->header.name_trn_id != nmb2->header.name_trn_id || !nmb2->header.response)
            {
                /* 
                 * Its not for us - maybe deal with it later 
                 * (put it on the queue?).
                 */
                if (fn)
                    fn (p2);
                else
                    free_packet (p2);
                continue;
            }

            if (nmb2->header.opcode != 0 ||
                nmb2->header.nm_flags.bcast || nmb2->header.rcode || !nmb2->header.ancount)
            {
                /* 
                 * XXXX what do we do with this? Could be a redirect, but
                 * we'll discard it for the moment.
                 */
                free_packet (p2);
                continue;
            }

            ip_list = (struct in_addr *) Realloc (ip_list, sizeof (ip_list[0]) *
                                                  ((*count) + nmb2->answers->rdlength / 6));
            if (ip_list)
            {
                DEBUG (fn ? 3 : 2, ("Got a positive name query response from %s ( ",
                                    inet_ntoa (p2->ip)));
                for (i = 0; i < nmb2->answers->rdlength / 6; i++)
                {
                    putip ((char *) &ip_list[(*count)], &nmb2->answers->rdata[2 + i * 6]);
                    DEBUG (fn ? 3 : 2, ("%s ", inet_ntoa (ip_list[(*count)])));
                    (*count)++;
                }
                DEBUG (fn ? 3 : 2, (")\n"));
            }

            found = True;
            retries = 0;
            free_packet (p2);
            if (fn)
                break;

            /*
             * If we're doing a unicast lookup we only
             * expect one reply. Don't wait the full 2
             * seconds if we got one. JRA.
             */
            if (!bcast && found)
                break;
        }
    }

    return ip_list;
}
Example #24
0
static int do_reseed(bool use_fd, int fd)
{
	unsigned char seed_inbuf[40];
	uint32 v1, v2; struct timeval tval; pid_t mypid;
	struct passwd *pw;
	int reseed_data = 0;

	if (use_fd) {
		if (fd != -1)
			return fd;

		fd = sys_open( "/dev/urandom", O_RDONLY,0);
		if(fd >= 0)
			return fd;
	}

	/* Add in some secret file contents */

	do_filehash("/etc/shadow", &seed_inbuf[0]);
	do_filehash(lp_smb_passwd_file(), &seed_inbuf[16]);

	/*
	 * Add in the root encrypted password.
	 * On any system where security is taken
	 * seriously this will be secret.
	 */

	pw = getpwnam_alloc(talloc_autofree_context(), "root");
	if (pw && pw->pw_passwd) {
		size_t i;
		unsigned char md4_tmp[16];
		mdfour(md4_tmp, (unsigned char *)pw->pw_passwd, strlen(pw->pw_passwd));
		for (i=0;i<16;i++)
			seed_inbuf[8+i] ^= md4_tmp[i];
		TALLOC_FREE(pw);
	}

	/*
	 * Add the counter, time of day, and pid.
	 */

	GetTimeOfDay(&tval);
	mypid = sys_getpid();
	v1 = (counter++) + mypid + tval.tv_sec;
	v2 = (counter++) * mypid + tval.tv_usec;

	SIVAL(seed_inbuf, 32, v1 ^ IVAL(seed_inbuf, 32));
	SIVAL(seed_inbuf, 36, v2 ^ IVAL(seed_inbuf, 36));

	/*
	 * Add any user-given reseed data.
	 */

	get_rand_reseed_data(&reseed_data);
	if (reseed_data) {
		size_t i;
		for (i = 0; i < sizeof(seed_inbuf); i++)
			seed_inbuf[i] ^= ((char *)(&reseed_data))[i % sizeof(reseed_data)];
	}

	smb_arc4_init(smb_arc4_state, seed_inbuf, sizeof(seed_inbuf));

	return -1;
}
Example #25
0
static int do_reseed(BOOL use_fd, int fd)
{
	unsigned char seed_inbuf[40];
	uint32 v1, v2; struct timeval tval; pid_t mypid;
	struct passwd *pw;

	if (use_fd) {
		if (fd != -1)
			return fd;

		fd = sys_open( "/dev/urandom", O_RDONLY,0);
		if(fd >= 0)
			return fd;
	}

#ifdef __INSURE__
	memset(seed_inbuf, '\0', sizeof(seed_inbuf));
#endif

	/* Add in some secret file contents */

	do_filehash("/etc/shadow", &seed_inbuf[0]);
#ifdef WITH_TDB_SAM
	do_filehash(lp_tdb_passwd_file(), &seed_inbuf[16]);
#else
	do_filehash(lp_smb_passwd_file(), &seed_inbuf[16]);
#endif

	/*
	 * Add in the root encrypted password.
	 * On any system where security is taken
	 * seriously this will be secret.
	 */

	pw = sys_getpwnam("root");
	if (pw && pw->pw_passwd) {
		size_t i;
		unsigned char md4_tmp[16];
		mdfour(md4_tmp, (unsigned char *)pw->pw_passwd, strlen(pw->pw_passwd));
		for (i=0;i<16;i++)
			seed_inbuf[8+i] ^= md4_tmp[i];
	}

	/*
	 * Add the counter, time of day, and pid.
	 */

	GetTimeOfDay(&tval);
	mypid = sys_getpid();
	v1 = (counter++) + mypid + tval.tv_sec;
	v2 = (counter++) * mypid + tval.tv_usec;

	SIVAL(seed_inbuf, 32, v1 ^ IVAL(seed_inbuf, 32));
	SIVAL(seed_inbuf, 36, v2 ^ IVAL(seed_inbuf, 36));

	/*
	 * Add any user-given reseed data.
	 */

	if (reseed_data) {
		size_t i;
		for (i = 0; i < sizeof(seed_inbuf); i++)
			seed_inbuf[i] ^= reseed_data[i % reseed_data_size];
	}

	seed_random_stream(seed_inbuf, sizeof(seed_inbuf));

	return -1;
}
Example #26
0
main()
{
    FILE	*fptr, *FileListPtr, *PlistPtr;
    CHAR	mline[MAXSTRING], CdimageFileName[1024], dirname[MAXSTRING];
    CHAR	mline2[512], filename[MAXSTRING], newfile[2], *CharPtr;
    CHAR	CdimageName[MAXSTRING], BeginName[32], FilePath[1024];
    INT		i, j;
    LONG	numfiles = 0;
    BOOL	NotFirstTime = FALSE;
    CHAR	Version[64], Patch[8], CurrentTime[25], TmpBfr[512], *CharPtr2;
    CHAR	ReleaseDir[1024];
    DWORD	HeaderSum, CheckSum;
	CHAR	verrel[64];

    if (!getenv("IngVersion"))
    {
	printf("Error! IngVersion not defined!\n");
	exit(1);
    }

    if (!getenv("PATCHNO"))
    {
	printf("Error! PATCHNO not defined!\n");
	exit(1);
    }

    if (!getenv("II_PATCH_DIR"))
    {
	printf("Error! II_PATCH_DIR not defined!\n");
	exit(1);
    }

    strcpy(Version, getenv("IngVersion"));
    j = 0;
    for (i=0; i<strlen(Version); i++)
    {
	if (Version[i] == '"')
	    continue;
	mline2[j++] = Version[i];
    }
    mline2[j] = '\0';
    strcpy(Version, mline2);

	strcpy(verrel, Version);
    j = 0;
	/* miss out the first 3 chars e.g. 'OI ' */
    for (i=3; i<strlen(verrel); i++)
    {
	if (verrel[i] == '.' || verrel[i] == '(' || verrel[i] == ')' || verrel[i] == '/'
		|| verrel[i] == ' ')
	    continue;
	mline2[j++] = verrel[i];
    }
    mline2[j] = '\0';
    strcpy(verrel, mline2);

    strcpy(Patch, getenv("PATCHNO"));
    j = 0;
    for (i=0; i<strlen(Patch); i++)
    {
	if (Patch[i] == '"')
	    continue;
	mline2[j++] = Patch[i];
    }
    mline2[j] = '\0';
    strcpy(Patch, mline2);

    strcpy(ReleaseDir, getenv("II_PATCH_DIR"));
    j = 0;
    for (i=0; i<strlen(ReleaseDir); i++)
    {
	if (ReleaseDir[i] == '"')
	    continue;
	mline2[j++] = ReleaseDir[i];
    }
    mline2[j] = '\0';
    strcpy(ReleaseDir, mline2);

    if ((fptr = fopen("fsizes.roc", "w")) == NULL)
    {
	printf("Error! Unable to open fsizes.roc for write!\n");
	exit(1);
    }

    if ((FileListPtr = fopen("filelist", "r")) == NULL)
    {
	printf("Error! Unable to open filelist for read!\n");
	fclose(fptr);
	exit(1);
    }

    if ((PlistPtr = fopen("plist", "w")) == NULL)
    {
	printf("Error! Unable to open filelist for read!\n");
	fclose(fptr);
	fclose(FileListPtr);
	exit(1);
    }

	/*
    ** Define some essentials first.
    */
    fprintf(fptr, "#define IngVersion \"%s\"\n", Version);
    fprintf(fptr, "#define PATCHNO \"%s\"\n", Patch);
    fprintf(fptr, "#define PatchVersion \"%s\"\n", verrel);
    if (getenv("INGRESII"))
	fprintf(fptr, "#define IngresII\n");

    /*
    ** Set up the plist headers.
    */
    fprintf(PlistPtr, "## Version:	%s\n", Version);
    fprintf(PlistPtr, "## Patch:	%s\n", Patch);
    fprintf(PlistPtr, "## Task:	build_plist\n");
    GetTimeOfDay(CurrentTime);
    fprintf(PlistPtr, "## Performed:	%s\n", CurrentTime);
    fprintf(PlistPtr, "##\n##\n## Contents:\n");
    fprintf(PlistPtr, "##	Packing list for patch ID recorded above.\n");
    fprintf(PlistPtr, "##\n##\n");
    fprintf(PlistPtr, "##                  file                        size     checksum\n##\n");

    fprintf(fptr, "\nstruct FILEINF filesizes[] = {\n");

    /*
    ** Now, set up the filesizes array. As we do this, if we find a file
    ** which is not in 8.3 (cdimage) format, rename it as such. Also,
    ** if we are dealing with files which are located in dictfiles or
    ** collation, the directories on the cdimage will be dictfile
    ** or collatio.
    */
    while (fgets(mline, MAXSTRING -1, FileListPtr) != NULL)
    {
	numfiles++;

	if (NotFirstTime)
	    fprintf(fptr, ",\n");

	if (!NotFirstTime)
	    NotFirstTime = TRUE;

	mline[strlen(mline)-1] = '\0';
	CharPtr = mline;
	strcpy(dirname, mline);
	CharPtr2 = dirname;
	while (*CharPtr2 != ' ')
	{
	    CharPtr++;
	    CharPtr2++;
	}
	*CharPtr2 = '\0';
	strcpy(TmpBfr, dirname);
	if (dirname[strlen(dirname)-1] == '\\')
	    dirname[strlen(dirname)-1] = '\0';
	else 
	{
		TmpBfr[strlen(TmpBfr)+1] = '\0';
		TmpBfr[strlen(TmpBfr)] = '\\';
	}

	/*
	** Convert single slashes to double slashes.
	*/
	j = 0;
	for (i=0; i<strlen(dirname); i++)
	{
	    mline2[j] = dirname[i];
	    if (dirname[i] == '\\')
		mline2[++j] = '\\';

	    j++;
	}
	mline2[j] = '\0';
	strcpy(dirname, mline2);

	CharPtr++;
	strcpy(filename, CharPtr);
	CharPtr2 = filename;
	while (*CharPtr2 != ' ')
	{
	    CharPtr++;
	    CharPtr2++;
	}
	*CharPtr2 = '\0';
	strcat(TmpBfr, filename);

	CharPtr++;
	strcpy(newfile, CharPtr);
	newfile[1] = '\0';

	sprintf(CdimageFileName, "%s%s\\%s", ReleaseDir, dirname, filename);

	if (!FileExists(CdimageFileName))
	{
	    printf("Error! %s does not exist!\n", CdimageFileName);
	    fclose(PlistPtr);
	    fclose(FileListPtr);
	    fclose(fptr);
	}

	strcpy(CdimageName, filename);
/*	strcpy(mline2, filename);
	if ((CharPtr2 = strchr(mline2, '.')) != NULL)
	    *CharPtr2 = '\0';

	if (strlen(mline2) > 8)
	{
	    j = 1;
	    strncpy(BeginName, filename, 7);
	    BeginName[7] = '\0';
	    CharPtr2 = strchr(filename, '.');
	    if (CharPtr2)
		sprintf(CdimageName, "%s%i%s", BeginName, j, CharPtr2);
	    else
		sprintf(CdimageName, "%s%i", BeginName, j);
	    sprintf(mline2, "%s%s\\%s", ReleaseDir, dirname, CdimageName);
	    while (FileExists(mline2))
	    {
		j++;
	   	if (CharPtr2)
		    sprintf(CdimageName, "%s%i%s", BeginName, j, CharPtr2);
		else
		    sprintf(CdimageName, "%s%i", BeginName, j);
		sprintf(mline2, "%s%s\\%s", ReleaseDir, dirname, CdimageName);
	    }

	    CopyFile(CdimageFileName, mline2, FALSE);
	    DeleteFile(CdimageFileName);
	    strcpy(CdimageFileName, mline2);
	} */
	
	fprintf(fptr, "\"  \",	\"%s\",	\"%s\",	\"%s\",	%d,	%i,	0",
		filename, CdimageName, dirname,
		GetCurrentFileSize(CdimageFileName), atoi(newfile));

	CheckSum = GetCurrentFileChecksum(CdimageFileName);
	fprintf(PlistPtr, "%-58s  %9d  %10u\n", TmpBfr,
		GetCurrentFileSize(CdimageFileName), CheckSum);
    }

    fprintf(fptr, "\n};\n\n#define NUMFILES %d\n", numfiles);

    fprintf(PlistPtr, "##\n##\n## File format version:	1\n");
    fprintf(PlistPtr, "##\n##\n## State:	completed\n");

    fclose(PlistPtr);
    fclose(FileListPtr);
    fclose(fptr);
}
Example #27
0
static bool test_usermod(struct torture_context *tctx, struct dcerpc_pipe *p,
			 TALLOC_CTX *mem_ctx,
			 struct policy_handle *handle, int num_changes,
			 struct libnet_rpc_usermod *mod, char **username)
{
	const char* logon_scripts[] = { "start_login.cmd", "login.bat", "start.cmd" };
	const char* home_dirs[] = { "\\\\srv\\home", "\\\\homesrv\\home\\user", "\\\\pdcsrv\\domain" };
	const char* home_drives[] = { "H:", "z:", "I:", "J:", "n:" };
	const char *homedir, *homedrive, *logonscript;
	const uint32_t flags[] = { (ACB_DISABLED | ACB_NORMAL | ACB_PW_EXPIRED),
				   (ACB_NORMAL | ACB_PWNOEXP),
				   (ACB_NORMAL | ACB_PW_EXPIRED) };

	NTSTATUS status;
	struct timeval now;
	enum test_fields testfld;
	int i;

	ZERO_STRUCT(*mod);
	srandom((unsigned)time(NULL));

	mod->in.username = talloc_strdup(mem_ctx, *username);
	mod->in.domain_handle = *handle;

	torture_comment(tctx, "modifying user (%d simultaneous change(s))\n",
			num_changes);

	torture_comment(tctx, "fields to change: [");

	for (i = 0; i < num_changes && i <= USER_FIELD_LAST; i++) {
		const char *fldname;

		testfld = (random() % USER_FIELD_LAST) + 1;

		GetTimeOfDay(&now);

		switch (testfld) {
		case acct_name:
			continue_if_field_set(mod->in.change.account_name);
			mod->in.change.account_name = talloc_asprintf(mem_ctx, TEST_CHG_ACCOUNTNAME,
								      (int)(random() % 100));
			mod->in.change.fields |= USERMOD_FIELD_ACCOUNT_NAME;
			fldname = "account_name";
			*username = talloc_strdup(mem_ctx, mod->in.change.account_name);
			break;

		case acct_full_name:
			continue_if_field_set(mod->in.change.full_name);
			mod->in.change.full_name = talloc_asprintf(mem_ctx, TEST_CHG_FULLNAME,
								  (int)random(), (int)random());
			mod->in.change.fields |= USERMOD_FIELD_FULL_NAME;
			fldname = "full_name";
			break;

		case acct_description:
			continue_if_field_set(mod->in.change.description);
			mod->in.change.description = talloc_asprintf(mem_ctx, TEST_CHG_DESCRIPTION,
								    random());
			mod->in.change.fields |= USERMOD_FIELD_DESCRIPTION;
			fldname = "description";
			break;

		case acct_home_directory:
			continue_if_field_set(mod->in.change.home_directory);
			homedir = home_dirs[random() % (sizeof(home_dirs)/sizeof(char*))];
			mod->in.change.home_directory = talloc_strdup(mem_ctx, homedir);
			mod->in.change.fields |= USERMOD_FIELD_HOME_DIRECTORY;
			fldname = "home_directory";
			break;

		case acct_home_drive:
			continue_if_field_set(mod->in.change.home_drive);
			homedrive = home_drives[random() % (sizeof(home_drives)/sizeof(char*))];
			mod->in.change.home_drive = talloc_strdup(mem_ctx, homedrive);
			mod->in.change.fields |= USERMOD_FIELD_HOME_DRIVE;
			fldname = "home_drive";
			break;

		case acct_comment:
			continue_if_field_set(mod->in.change.comment);
			mod->in.change.comment = talloc_asprintf(mem_ctx, TEST_CHG_COMMENT,
								random(), random());
			mod->in.change.fields |= USERMOD_FIELD_COMMENT;
			fldname = "comment";
			break;

		case acct_logon_script:
			continue_if_field_set(mod->in.change.logon_script);
			logonscript = logon_scripts[random() % (sizeof(logon_scripts)/sizeof(char*))];
			mod->in.change.logon_script = talloc_strdup(mem_ctx, logonscript);
			mod->in.change.fields |= USERMOD_FIELD_LOGON_SCRIPT;
			fldname = "logon_script";
			break;

		case acct_profile_path:
			continue_if_field_set(mod->in.change.profile_path);
			mod->in.change.profile_path = talloc_asprintf(mem_ctx, TEST_CHG_PROFILEPATH,
								     (long int)random(), (unsigned int)random());
			mod->in.change.fields |= USERMOD_FIELD_PROFILE_PATH;
			fldname = "profile_path";
			break;

		case acct_expiry:
			continue_if_field_set(mod->in.change.acct_expiry);
			now = timeval_add(&now, (random() % (31*24*60*60)), 0);
			mod->in.change.acct_expiry = (struct timeval *)talloc_memdup(mem_ctx, &now, sizeof(now));
			mod->in.change.fields |= USERMOD_FIELD_ACCT_EXPIRY;
			fldname = "acct_expiry";
			break;

		case acct_flags:
			continue_if_field_set(mod->in.change.acct_flags);
			mod->in.change.acct_flags = flags[random() % ARRAY_SIZE(flags)];
			mod->in.change.fields |= USERMOD_FIELD_ACCT_FLAGS;
			fldname = "acct_flags";
			break;

		default:
			fldname = talloc_asprintf(mem_ctx, "unknown_field (%d)", testfld);
			break;
		}

		torture_comment(tctx, ((i < num_changes - 1) ? "%s," : "%s"), fldname);
	}
	torture_comment(tctx, "]\n");

	status = libnet_rpc_usermod(p, mem_ctx, mod);
	torture_assert_ntstatus_ok(tctx, status, "Failed to call sync libnet_rpc_usermod");

	return true;
}
Example #28
0
static void do_atar(char *rname,char *lname,file_info *finfo1)
{
	int fnum;
	SMB_BIG_UINT nread=0;
	char ftype;
	file_info2 finfo;
	BOOL close_done = False;
	BOOL shallitime=True;
	char data[65520];
	int read_size = 65520;
	int datalen=0;

	struct timeval tp_start;

	GetTimeOfDay(&tp_start);

	ftype = '0'; /* An ordinary file ... */

	if (finfo1) {
		finfo.size  = finfo1 -> size;
		finfo.mode  = finfo1 -> mode;
		finfo.uid   = finfo1 -> uid;
		finfo.gid   = finfo1 -> gid;
		finfo.mtime = finfo1 -> mtime;
		finfo.atime = finfo1 -> atime;
		finfo.ctime = finfo1 -> ctime;
		finfo.name  = finfo1 -> name;
	} else {
		finfo.size  = def_finfo.size;
		finfo.mode  = def_finfo.mode;
		finfo.uid   = def_finfo.uid;
		finfo.gid   = def_finfo.gid;
		finfo.mtime = def_finfo.mtime;
		finfo.atime = def_finfo.atime;
		finfo.ctime = def_finfo.ctime;
		finfo.name  = def_finfo.name;
	}

	if (dry_run) {
		DEBUG(3,("skipping file %s of size %12.0f bytes\n", finfo.name,
				(double)finfo.size));
		shallitime=0;
		ttarf+=finfo.size + TBLOCK - (finfo.size % TBLOCK);
		ntarf++;
		return;
	}

	fnum = cli_open(cli, rname, O_RDONLY, DENY_NONE);

	dos_clean_name(rname);

	if (fnum == -1) {
		DEBUG(0,("%s opening remote file %s (%s)\n",
				cli_errstr(cli),rname, cur_dir));
		return;
	}

	finfo.name = string_create_s(strlen(rname));
	if (finfo.name == NULL) {
		DEBUG(0, ("Unable to allocate space for finfo.name in do_atar\n"));
		return;
	}

	safe_strcpy(finfo.name,rname, strlen(rname));
	if (!finfo1) {
		if (!cli_getattrE(cli, fnum, &finfo.mode, &finfo.size, NULL, &finfo.atime, &finfo.mtime)) {
			DEBUG(0, ("getattrE: %s\n", cli_errstr(cli)));
			return;
		}
		finfo.ctime = finfo.mtime;
	}

	DEBUG(3,("file %s attrib 0x%X\n",finfo.name,finfo.mode));

	if (tar_inc && !(finfo.mode & aARCH)) {
		DEBUG(4, ("skipping %s - archive bit not set\n", finfo.name));
		shallitime=0;
	} else if (!tar_system && (finfo.mode & aSYSTEM)) {
		DEBUG(4, ("skipping %s - system bit is set\n", finfo.name));
		shallitime=0;
	} else if (!tar_hidden && (finfo.mode & aHIDDEN)) {
		DEBUG(4, ("skipping %s - hidden bit is set\n", finfo.name));
		shallitime=0;
	} else {
		DEBUG(3,("getting file %s of size %.0f bytes as a tar file %s",
			finfo.name, (double)finfo.size, lname));
      
		/* write a tar header, don't bother with mode - just set to 100644 */
		writetarheader(tarhandle, rname, finfo.size, finfo.mtime, "100644 \0", ftype);

		while (nread < finfo.size && !close_done) {
	      
			DEBUG(3,("nread=%.0f\n",(double)nread));
	      
			datalen = cli_read(cli, fnum, data, nread, read_size);
	      
			if (datalen == -1) {
				DEBUG(0,("Error reading file %s : %s\n", rname, cli_errstr(cli)));
				break;
			}
	      
			nread += datalen;

			/* if file size has increased since we made file size query, truncate
				read so tar header for this file will be correct.
			*/

			if (nread > finfo.size) {
				datalen -= nread - finfo.size;
				DEBUG(0,("File size change - truncating %s to %.0f bytes\n",
							finfo.name, (double)finfo.size));
			}

			/* add received bits of file to buffer - dotarbuf will
			* write out in 512 byte intervals */

			if (dotarbuf(tarhandle,data,datalen) != datalen) {
				DEBUG(0,("Error writing to tar file - %s\n", strerror(errno)));
				break;
			}
	      
			if (datalen == 0) {
				DEBUG(0,("Error reading file %s. Got 0 bytes\n", rname));
				break;
			}

			datalen=0;
		}

		/* pad tar file with zero's if we couldn't get entire file */
		if (nread < finfo.size) {
			DEBUG(0, ("Didn't get entire file. size=%.0f, nread=%d\n",
						(double)finfo.size, (int)nread));
			if (padit(data, sizeof(data), finfo.size - nread))
				DEBUG(0,("Error writing tar file - %s\n", strerror(errno)));
		}

		/* round tar file to nearest block */
		if (finfo.size % TBLOCK)
			dozerobuf(tarhandle, TBLOCK - (finfo.size % TBLOCK));
      
		ttarf+=finfo.size + TBLOCK - (finfo.size % TBLOCK);
		ntarf++;
	}
  
	cli_close(cli, fnum);

	if (shallitime) {
		struct timeval tp_end;
		int this_time;

		/* if shallitime is true then we didn't skip */
		if (tar_reset && !dry_run)
			(void) do_setrattr(finfo.name, aARCH, ATTRRESET);
      
		GetTimeOfDay(&tp_end);
		this_time = (tp_end.tv_sec - tp_start.tv_sec)*1000 + (tp_end.tv_usec - tp_start.tv_usec)/1000;
		get_total_time_ms += this_time;
		get_total_size += finfo.size;

		if (tar_noisy) {
			DEBUG(0, ("%12.0f (%7.1f kb/s) %s\n",
				(double)finfo.size, finfo.size / MAX(0.001, (1.024*this_time)),
				finfo.name));
		}

		/* Thanks to Carel-Jan Engel ([email protected]) for this one */
		DEBUG(3,("(%g kb/s) (average %g kb/s)\n",
				finfo.size / MAX(0.001, (1.024*this_time)),
				get_total_size / MAX(0.001, (1.024*get_total_time_ms))));
	}
}