예제 #1
0
/** pass time */
static void
time_passes(struct replay_runtime* runtime, struct replay_moment* mom)
{
	struct fake_timer *t;
	struct timeval tv = mom->elapse;
	if(mom->string) {
		char* xp = macro_process(runtime->vars, runtime, mom->string);
		double sec;
		if(!xp) fatal_exit("could not macro expand %s", mom->string);
		verbose(VERB_ALGO, "EVAL %s", mom->string);
		sec = atof(xp);
		free(xp);
#ifndef S_SPLINT_S
		tv.tv_sec = sec;
		tv.tv_usec = (int)((sec - (double)tv.tv_sec) *1000000. + 0.5);
#endif
	}
	timeval_add(&runtime->now_tv, &tv);
	runtime->now_secs = (time_t)runtime->now_tv.tv_sec;
#ifndef S_SPLINT_S
	log_info("elapsed %d.%6.6d  now %d.%6.6d", 
		(int)tv.tv_sec, (int)tv.tv_usec,
		(int)runtime->now_tv.tv_sec, (int)runtime->now_tv.tv_usec);
#endif
	/* see if any timers have fired; and run them */
	while( (t=replay_get_oldest_timer(runtime)) ) {
		t->enabled = 0;
		log_info("fake_timer callback");
		fptr_ok(fptr_whitelist_comm_timer(t->cb));
		(*t->cb)(t->cb_arg);
	}
}
예제 #2
0
파일: clock.c 프로젝트: coodie/mimiker
static void clock(timer_event_t *tev) {
  systime_t st = tv2st(tev->tev_when);
  tev->tev_when = timeval_add(&tev->tev_when, &tick);
  cpu_timer_add_event(tev);
  callout_process(st);
  sched_clock();
}
예제 #3
0
/*
 * get_timeout
 * returns the amount of time that select should block for before returning
 * whether some packets have arrived or not
 */
static int get_timeout(struct timeval *tv)
{
  struct timeval  temp;
  int64_t         min_diff = 1000, temp_diff;

  if(tv == NULL)
    {
      return 0;
    }

  bzero(&temp, sizeof(temp));
  bzero(&tz,   sizeof(tz));
  if(gettimeofday(&temp, &tz) != 0)
    {
      printerror(errno, strerror, "could not gettimeofday");
      return 0;
    }

  if(wait_between > 0)
    {
      temp_diff = timeval_diff_msec(&wait_between_tv, &temp);
      if(temp_diff >= 0 && temp_diff < min_diff) min_diff = temp_diff;
    }

  tv->tv_sec  = 0;
  tv->tv_usec = 0;
  timeval_add(tv, min_diff);

  return 1;
}
예제 #4
0
	void BroadcastReceiver::operator() (timeval *pTimeout) throw (FatalError)
	{
		// only one thread allowed per instance
		if(0 == std::atomic_fetch_add(&mNumInstances, 1))
			try {
				size_t numRemotes = mIpTable.size();
				timeval endTime, now;
				gettimeofday(&endTime, NULL);
				timeval_add(&endTime, pTimeout);
				do
				{
					const Endpoint remote = GetNextRemote(pTimeout);
					if(remote.IsValid()) {
						numRemotes++;
					}
					gettimeofday(&now, NULL);
				}
				while(mIsRunning && timeval_sub(&endTime, &now, pTimeout));
			} catch(FatalError& e) {
				std::atomic_fetch_sub(&mNumInstances, 1);
				throw(e);
			}



		std::atomic_fetch_sub(&mNumInstances, 1);
	}
예제 #5
0
int main(void)
{
  int *values = malloc(NUMVALUES * sizeof (*values));
  unsigned long idx, sortnum;
  struct timeval start, end, diff, tmp, runtime = {0,0};

  assert(values != NULL);
  for (sortnum = 0; sortnum < NUMSORTS; ++sortnum) {
    for (idx = 0; idx < NUMVALUES; ++idx) {
      values[idx] = rand();
    }
    (void) gettimeofday(&start, NULL);
    //qsort(values, sizeof(*values), NUMVALUES, compare);
    qsort(values, NUMVALUES, sizeof(*values), compare);
    (void) gettimeofday(&end, NULL);
    (void) timeval_subtract(&diff, &end, &start);
    tmp = runtime;
    (void) timeval_add(&runtime, &tmp, &diff);
    /* printf("Runtime (hh:mm:ss:us)\t%02lu:%02lu:%02lu:%06lu\n",
           runtime.tv_sec / 60LU / 60LU,
           (runtime.tv_sec / 60LU) % 60LU,
           runtime.tv_sec % 60LU,
           runtime.tv_usec); */
  }

  printf("Runtime (hh:mm:ss:us)\t%02lu:%02lu:%02lu:%06lu\n",
         runtime.tv_sec / 60LU / 60LU,
         (runtime.tv_sec / 60LU) % 60LU,
         runtime.tv_sec % 60LU,
         runtime.tv_usec);

  free(values);
  return 0;
}
예제 #6
0
void comm_timer_set(struct comm_timer* timer, struct timeval* tv)
{
	struct fake_timer* t = (struct fake_timer*)timer;
	t->enabled = 1;
	t->tv = *tv;
	log_info("fake timer set %d.%6.6d", 
		(int)t->tv.tv_sec, (int)t->tv.tv_usec);
	timeval_add(&t->tv, &t->runtime->now_tv);
}
예제 #7
0
struct timeval *elapse_time(struct timeval *tv, unsigned msec) {
    assert(tv);

    gettimeofday(tv, NULL);

    if (msec)
        timeval_add(tv, (Usec) msec*1000);
        
    return tv;
}
예제 #8
0
파일: stats.c 프로젝트: ChaosJohn/freebsd
void server_stats_add(struct stats_info* total, struct stats_info* a)
{
	total->svr.num_queries += a->svr.num_queries;
	total->svr.num_queries_missed_cache += a->svr.num_queries_missed_cache;
	total->svr.num_queries_prefetch += a->svr.num_queries_prefetch;
	total->svr.sum_query_list_size += a->svr.sum_query_list_size;
	/* the max size reached is upped to higher of both */
	if(a->svr.max_query_list_size > total->svr.max_query_list_size)
		total->svr.max_query_list_size = a->svr.max_query_list_size;

	if(a->svr.extended) {
		int i;
		total->svr.qtype_big += a->svr.qtype_big;
		total->svr.qclass_big += a->svr.qclass_big;
		total->svr.qtcp += a->svr.qtcp;
		total->svr.qipv6 += a->svr.qipv6;
		total->svr.qbit_QR += a->svr.qbit_QR;
		total->svr.qbit_AA += a->svr.qbit_AA;
		total->svr.qbit_TC += a->svr.qbit_TC;
		total->svr.qbit_RD += a->svr.qbit_RD;
		total->svr.qbit_RA += a->svr.qbit_RA;
		total->svr.qbit_Z += a->svr.qbit_Z;
		total->svr.qbit_AD += a->svr.qbit_AD;
		total->svr.qbit_CD += a->svr.qbit_CD;
		total->svr.qEDNS += a->svr.qEDNS;
		total->svr.qEDNS_DO += a->svr.qEDNS_DO;
		total->svr.ans_rcode_nodata += a->svr.ans_rcode_nodata;
		total->svr.ans_secure += a->svr.ans_secure;
		total->svr.ans_bogus += a->svr.ans_bogus;
		total->svr.rrset_bogus += a->svr.rrset_bogus;
		total->svr.unwanted_replies += a->svr.unwanted_replies;
		total->svr.unwanted_queries += a->svr.unwanted_queries;
		for(i=0; i<STATS_QTYPE_NUM; i++)
			total->svr.qtype[i] += a->svr.qtype[i];
		for(i=0; i<STATS_QCLASS_NUM; i++)
			total->svr.qclass[i] += a->svr.qclass[i];
		for(i=0; i<STATS_OPCODE_NUM; i++)
			total->svr.qopcode[i] += a->svr.qopcode[i];
		for(i=0; i<STATS_RCODE_NUM; i++)
			total->svr.ans_rcode[i] += a->svr.ans_rcode[i];
		for(i=0; i<NUM_BUCKETS_HIST; i++)
			total->svr.hist[i] += a->svr.hist[i];
	}

	total->mesh_num_states += a->mesh_num_states;
	total->mesh_num_reply_states += a->mesh_num_reply_states;
	total->mesh_jostled += a->mesh_jostled;
	total->mesh_dropped += a->mesh_dropped;
	total->mesh_replies_sent += a->mesh_replies_sent;
	timeval_add(&total->mesh_replies_sum_wait, &a->mesh_replies_sum_wait);
	/* the medians are averaged together, this is not as accurate as
	 * taking the median over all of the data, but is good and fast
	 * added up here, division later*/
	total->mesh_time_median += a->mesh_time_median;
}
예제 #9
0
/*
  start a timer to refresh this name
*/
static void nbtd_wins_start_refresh_timer(struct nbtd_iface_name *iname)
{
	uint32_t refresh_time;
	uint32_t max_refresh_time = lp_parm_int(iname->iface->nbtsrv->task->lp_ctx, NULL, "nbtd", "max_refresh_time", 7200);

	refresh_time = MIN(max_refresh_time, iname->ttl/2);
	
	event_add_timed(iname->iface->nbtsrv->task->event_ctx, 
			iname, 
			timeval_add(&iname->registration_time, refresh_time, 0),
			nbtd_wins_refresh, iname);
}
예제 #10
0
static void idle_handler(struct tevent_context *ev, 
			 struct tevent_timer *te, struct timeval t, void *private_data)
{
	struct smbcli_transport *transport = talloc_get_type(private_data,
							     struct smbcli_transport);
	struct timeval next = timeval_add(&t, 0, transport->idle.period);
	transport->socket->event.te = event_add_timed(transport->socket->event.ctx, 
						      transport,
						      next,
						      idle_handler, transport);
	transport->idle.func(transport, transport->idle.private_data);
}
예제 #11
0
파일: scavenger.c 프로젝트: 285858315/samba
void scavenger_schedule_disconnected(struct files_struct *fsp)
{
	NTSTATUS status;
	struct server_id self = messaging_server_id(fsp->conn->sconn->msg_ctx);
	struct timeval disconnect_time, until;
	uint64_t timeout_usec;
	struct scavenger_message msg;
	DATA_BLOB msg_blob;
	struct server_id_buf tmp;

	if (fsp->op == NULL) {
		return;
	}
	nttime_to_timeval(&disconnect_time, fsp->op->global->disconnect_time);
	timeout_usec = 1000 * fsp->op->global->durable_timeout_msec;
	until = timeval_add(&disconnect_time,
			    timeout_usec / 1000000,
			    timeout_usec % 1000000);

	ZERO_STRUCT(msg);
	msg.file_id = fsp->file_id;
	msg.open_persistent_id = fsp->op->global->open_persistent_id;
	msg.until = timeval_to_nttime(&until);

	DEBUG(10, ("smbd: %s mark file %s as disconnected at %s with timeout "
		   "at %s in %fs\n",
		   server_id_str_buf(self, &tmp),
		   file_id_string_tos(&fsp->file_id),
		   timeval_string(talloc_tos(), &disconnect_time, true),
		   timeval_string(talloc_tos(), &until, true),
		   fsp->op->global->durable_timeout_msec/1000.0));

	SMB_ASSERT(server_id_is_disconnected(&fsp->op->global->server_id));
	SMB_ASSERT(!server_id_equal(&self, &smbd_scavenger_state->parent_id));
	SMB_ASSERT(!smbd_scavenger_state->am_scavenger);

	msg_blob = data_blob_const(&msg, sizeof(msg));
	DEBUG(10, ("send message to scavenger\n"));

	status = messaging_send(smbd_scavenger_state->msg,
				smbd_scavenger_state->parent_id,
				MSG_SMB_SCAVENGER,
				&msg_blob);
	if (!NT_STATUS_IS_OK(status)) {
		struct server_id_buf tmp1, tmp2;
		DEBUG(2, ("Failed to send message to parent smbd %s "
			  "from %s: %s\n",
			  server_id_str_buf(smbd_scavenger_state->parent_id,
					    &tmp1),
			  server_id_str_buf(self, &tmp2),
			  nt_errstr(status)));
	}
}
예제 #12
0
  void test_timeval_add() {
    const struct timeval
      a_plus_b = { 3, 1000000 },
      a_plus_c = { 5, 900000 },
      b_plus_c = { 6, 100000 };

    TS_ASSERT_EQUALS(zero, timeval_add(zero, zero));
    TS_ASSERT_EQUALS(a, timeval_add(zero, a));
    TS_ASSERT_EQUALS(a, timeval_add(a, zero));
    TS_ASSERT_EQUALS(b, timeval_add(zero, b));
    TS_ASSERT_EQUALS(c, timeval_add(zero, c));
    TS_ASSERT_EQUALS(a_plus_b, timeval_add(a, b));
    TS_ASSERT_EQUALS(a_plus_c, timeval_add(a, c));
    TS_ASSERT_EQUALS(b_plus_c, timeval_add(b, c));
  }
예제 #13
0
파일: devtimer.c 프로젝트: JackieXie168/xnu
__private_extern__ void
devtimer_set_relative(devtimer_ref timer,
                      struct timeval rel_time,
                      devtimer_timeout_func timeout_func,
                      void * arg1, void * arg2)
{
    struct timeval		abs_time;
    struct timeval		current_time;

    current_time = devtimer_current_time();
    timeval_add(current_time, rel_time, &abs_time);
    devtimer_set_absolute(timer, abs_time, timeout_func, arg1, arg2);
    return;
}
예제 #14
0
/*
  setup for a unlink retry after a sharing violation
  or a non granted oplock
*/
static NTSTATUS pvfs_unlink_setup_retry(struct ntvfs_module_context *ntvfs,
					struct ntvfs_request *req,
					union smb_unlink *io,
					struct odb_lock *lck,
					NTSTATUS status)
{
	struct pvfs_state *pvfs = talloc_get_type(ntvfs->private_data,
				  struct pvfs_state);
	struct timeval end_time;

	if (NT_STATUS_EQUAL(status, NT_STATUS_SHARING_VIOLATION)) {
		end_time = timeval_add(&req->statistics.request_time,
				       0, pvfs->sharing_violation_delay);
	} else if (NT_STATUS_EQUAL(status, NT_STATUS_OPLOCK_NOT_GRANTED)) {
		end_time = timeval_add(&req->statistics.request_time,
				       pvfs->oplock_break_timeout, 0);
	} else {
		return NT_STATUS_INTERNAL_ERROR;
	}

	return pvfs_odb_retry_setup(ntvfs, req, lck, end_time, io, NULL,
				    pvfs_retry_unlink);
}
예제 #15
0
static void aio_child_cleanup(struct event_context *event_ctx,
			      struct timed_event *te,
			      struct timeval now,
			      void *private_data)
{
	struct aio_child_list *list = talloc_get_type_abort(
		private_data, struct aio_child_list);
	struct aio_child *child, *next;

	TALLOC_FREE(list->cleanup_event);

	for (child = list->children; child != NULL; child = next) {
		next = child->next;

		if (child->aiocb != NULL) {
			DEBUG(10, ("child %d currently active\n",
				   (int)child->pid));
			continue;
		}

		if (child->dont_delete) {
			DEBUG(10, ("Child %d was active since last cleanup\n",
				   (int)child->pid));
			child->dont_delete = false;
			continue;
		}

		DEBUG(10, ("Child %d idle for more than 30 seconds, "
			   "deleting\n", (int)child->pid));

		TALLOC_FREE(child);
		child = next;
	}

	if (list->children != NULL) {
		/*
		 * Re-schedule the next cleanup round
		 */
		list->cleanup_event = event_add_timed(server_event_context(), list,
						      timeval_add(&now, 30, 0),
						      aio_child_cleanup, list);

	}
}
예제 #16
0
coord timeval_round_up(coord c1, coord c2)
{
  coord r;
  struct tm *tmp;

  tmp = localtime((time_t *) &(c1.t.tv_sec));

#ifdef HAVE_TM_GMTOFF
  c1.t.tv_sec += tmp->tm_gmtoff;
#endif
  
  if (c2.t.tv_sec == 0) {
    r.t.tv_sec  = c1.t.tv_sec;
    if (c1.t.tv_usec % c2.t.tv_usec == 0)
      r.t.tv_usec = c1.t.tv_usec;
    else {
      r.t.tv_usec = c1.t.tv_usec + (c2.t.tv_usec -
				    (c1.t.tv_usec % c2.t.tv_usec));
      if (r.t.tv_usec >= 1000000) {
	r.t.tv_usec -= 1000000;
	r.t.tv_sec  += 1;
      }
    }
  } else {
    r.t.tv_usec = 0;
    if (c1.t.tv_sec % c2.t.tv_sec == 0)
      r.t.tv_sec = c1.t.tv_sec;
    else
      r.t.tv_sec = c1.t.tv_sec + (c2.t.tv_sec - (c1.t.tv_sec % c2.t.tv_sec));
  }

#ifdef HAVE_TM_GMTOFF
  r.t.tv_sec -= tmp->tm_gmtoff;
#endif

  timeval_fix(&r);
  return r;
  
#if 0
  return timeval_round_down(timeval_add(c1,c2), c2);
#endif

}
예제 #17
0
static int
add_timer(int ms, int oneshot, server_timer_callback callback, void* arg)
{
    struct timeval interval;
    timer_callback* cb;

    ASSERT (ms || oneshot);
    ASSERT(callback != NULL);

    interval.tv_sec = ms / 1000;
    interval.tv_usec = (ms % 1000) * 1000; /* into micro seconds */

    cb = (timer_callback*)calloc(1, sizeof(*cb));
    if(!cb)
    {
        errno = ENOMEM;
        return -1;
    }

    if(gettimeofday(&(cb->at), NULL) == -1)
    {
        free(cb);
        return -1;
    }

    timeval_add(&(cb->at), &interval);

    if (oneshot)
        memset(&(cb->interval), 0, sizeof(cb->interval));
    else
        memcpy(&(cb->interval), &interval, sizeof(cb->interval));

    cb->callback = callback;
    cb->arg = arg;

    cb->next = ctx.timers;
    ctx.timers = cb;

    return 0;
}
예제 #18
0
파일: util.c 프로젝트: acml/cvsnt
int wait_for_read(sock_t fd, struct timeval *end) {
    struct timeval now;

    if (end)
        gettimeofday(&now, NULL);

    for (;;) {
        struct timeval tv;
        fd_set fds;
        int r;
        
        FD_ZERO(&fds);
        FD_SET(fd, &fds);

        if (end) {
            if (timeval_cmp(&now, end) >= 0)
                return 1;
            
            tv.tv_sec = tv.tv_usec = 0;
            timeval_add(&tv, timeval_diff(end, &now));
        }
        
        if ((r = select((int)fd+1, &fds, NULL, NULL, end ? &tv : NULL)) < 0) {
            if (errno != EINTR) {
                fprintf(stderr, "select() failed: %s\n", strerror(errno));
                return -1;
            }
        } else if (r == 0) 
            return 1;
        else {
            
            if (FD_ISSET(fd, &fds))
                return 0;
        }

        if (end)
            gettimeofday(&now, NULL);
    }
}
예제 #19
0
static
void*
snake (void* arg)
{
  static int x = 3;
  static int y = 3;
  
  struct timeval next_activation;
  struct timeval now, timeout;
  struct timeval period = { 0, 500000 };
  
  gettimeofday (&next_activation, NULL);
  while (1) {
    gettimeofday (&now, NULL);
    timeval_sub (&timeout, &next_activation, &now);
    select (0, NULL, NULL, NULL, &timeout) ;
    timeval_add (&next_activation, &next_activation, &period);

    x += deltax;
    y += deltay;
    screen_printxy (x, y, "*");
  }
}
예제 #20
0
int wait_for_write(int fd, struct timeval *end) {
    struct timeval now;

    if (end)
        gettimeofday(&now, NULL);
    
    for (;;) {
        struct timeval tv;
        fd_set fds;
        int r;
        
        FD_ZERO(&fds);
        FD_SET(fd, &fds);

        if (end) {
            if (timeval_cmp(&now, end) >= 0)
                return 1;

            tv.tv_sec = tv.tv_usec = 0;
            timeval_add(&tv, timeval_diff(end, &now));
        }

        if ((r = select(fd+1, NULL, &fds, NULL, end ? &tv : NULL)) < 0) {
            if (errno != EINTR)
                return -1;
        } else if (r == 0)
            return 1;
        else {
            if (FD_ISSET(fd, &fds))
                return 0;
        }

        if (end)
            gettimeofday(&now, NULL);
    }
}
예제 #21
0
파일: interface.c 프로젝트: kenhys/xyzsh
void xyzsh_readline_interface_on_curses(char* cmdline, int cursor_point, char** argv, int argc, BOOL exit_in_spite_ofjob_exist, BOOL welcome_msg)
{
    gSigChld = FALSE;
    gSigWinch = FALSE;

    signal(SIGCHLD, handler);
    signal(SIGWINCH, handler);

    const int maxx = mgetmaxx();
    const int maxy = mgetmaxy();

    int temulator_y = 0;
    int temulator_x = 0;
    int temulator_height = maxy;
    int temulator_width = maxx;

    sTEmulator* temulator = temulator_init(temulator_height, temulator_width);

    struct sTEmulatorFunArg arg;

    arg.cmdline = cmdline;
    arg.cursor_point = cursor_point;
    arg.argv = argv;
    arg.argc = argc;
    arg.exit_in_spite_ofjob_exist = exit_in_spite_ofjob_exist;
    arg.welcome_msg = welcome_msg;

    temulator_open(temulator, temulator_fun, &arg);

    initscr();
    start_color();
    noecho();
    raw();
    nodelay(stdscr, TRUE);
    keypad(stdscr, TRUE);
    curs_set(0);
    ESCDELAY=50;

    temulator_init_colors();

    WINDOW* term_win = newwin(temulator_height, temulator_width, temulator_y, temulator_x);

    int pty = temulator->mFD;

    fd_set mask, read_ok;
    FD_ZERO(&mask);
    FD_SET(0, &mask);
    FD_SET(pty, &mask);

    int dirty = 0;
    struct timeval next;

    gettimeofday(&next, NULL);
    while(1) {
        struct timeval tv = { 0, 1000 * 1000 / 100 };
        read_ok = mask;

        if(select(pty+1, &read_ok, NULL, NULL, &tv) > 0) {
            if(FD_ISSET(pty, &read_ok)) {
                temulator_read(temulator);
                dirty = 1;
            }
        }

        int key;
        while((key = getch()) != ERR) {
            temulator_write(temulator, key);
            dirty = 1;
        }

        gettimeofday(&tv, NULL);
        if(dirty && is_expired(tv, next)) {
            temulator_draw_on_curses(temulator, term_win, temulator_y, temulator_x);
            wrefresh(term_win);
            dirty = 0;
            next = timeval_add(tv, slice);
        }

        if(gSigChld) {
            gSigChld = FALSE;
            break;
        }

        if(gSigWinch) {
            gSigWinch = 0;

            temulator_height = mgetmaxy();
            temulator_width = mgetmaxx();

            if(temulator_width >= 10 && temulator_height >= 10) {
                resizeterm(temulator_height, temulator_width);

                wresize(term_win, temulator_height, temulator_width);
                temulator_resize(temulator, temulator_height, temulator_width);

                dirty = 1;
            }
        }
    }

    endwin();

    temulator_final(temulator);
}
예제 #22
0
파일: util_time.c 프로젝트: AIdrifter/samba
_PUBLIC_ struct timeval timeval_current_ofs(uint32_t secs, uint32_t usecs)
{
	struct timeval tv = timeval_current();
	return timeval_add(&tv, secs, usecs);
}
예제 #23
0
/*
 * Function: main
 * Purpose:  
 * Comments: 
 */
int main(int argc, char *argv[])
{
  int                i;
  struct sigaction   si_sa;
  int                euid, ruid;
  struct host_entry *cursor;

  /*
   * first things first
   * if anything goes wrong anywhere, we want to be super careful to release
   * any file descriptor we have on /dev/lkm, and it probably makes sense to
   * shutdown the raw socket we have too.
   */
  atexit(cleanup);

  /*
   * get the effective and the real user id's so we know if we are running
   * with elevated permissions or not
   */
  euid = geteuid();
  ruid = getuid();

  /* check for the command line arguments */
  if(check_options(argc,argv) == 0)
    {
      return -1;
    }

  /*
   * open the raw socket now.  i used to have this further down closer to
   * where it was needed, but because you can't change the euid/uid to and
   * from root (unless you're the superuser) i can only do this once
   */
  if(options & OPT_IPV4)
    {
      if(open_ipmp_sockets4() == 0) return -1; 
    }
  else if(options & OPT_IPV6)
    {
      if(open_ipmp_sockets6() == 0) return -1; 
    }
  else
    {
      if(open_ipmp_sockets4() == 0) return -1;
      if(open_ipmp_sockets6() == 0) return -1;
    }

  /*
   * revoke the permissions we requested as we only need them to open a raw
   * socket.  this is to reduce the impact of any buffer overflow exploits
   * that may be present
   */
  if(ruid != euid)
    {
      setreuid(ruid, ruid);
    }

  /*
   * we get the pid so we can identify incoming ipmp packets destined for
   * this instance of ipmp_ping
   */
  pid = getpid();

  /*
   * need to know about the addresses this host has
   */
  learn_localaddresses();

  /*
   * in FreeBSD, the actual ping is done by a kernel module that has a syscall
   * in it.  the kernel module allows the protocol to get a timestamp as close
   * to when the mbuf is actually sent to ip_output as possible
   */
#if defined(__FreeBSD__)
  if((options & OPT_RAW) == 0)
    {
      i = get_syscall("ipmp_ping", &syscall_num);
      if(i != 0)
        {
          printerror(i, strerror, "could not get the syscall for ipmp_ping");
          return -1;
        }
    }
#endif

  /*
   * the -n option means that the user has supplied a list of hosts to
   * ping, so we read those entries and put them in an list of hosts with
   * details regarding each host.  the task of putting hosts into the list
   * is handled by read_hosts_file
   *
   * if the -n option isnt specified, we create a list containing just the 
   * one host to ping.  this way, all the program logic can be used in a
   * multitude of situations.
   */
  if(options & OPT_NLANR)
    {
      /*
       * if something went wrong parsing the file, we quit.
       */
      if(read_hosts_file() == 0)
	{
	  return -1;
	}
    }
  else
    {
      /*
       * if the user didnt specify a host to ping, we bail, telling them
       * why first...
       */
      if(argc - optind != 1)
	{
	  usage(0);
          return -1;
	}

      /*
       * if we can't add a host entry for the host supplied on the command line
       * tell the user that it couldnt be parse and cleanup
       */
      if(add_host_entry(argv[optind], NULL) == 0)
	{
	  return -1;
	}
    }

  /*
   * we now put some handlers into action so if the user ctrl-c's us we have
   * the opportunity to tell them what we found out first
   * also, if the user specified a timeout, put an alarm in for that so we
   * can bail when they tell us to...
   */
  sigemptyset(&si_sa.sa_mask);
  si_sa.sa_flags = 0;
  si_sa.sa_handler = alarm_bells;
  if(sigaction(SIGINT, &si_sa, 0) == -1)
    {
      printerror(errno, strerror, "could not set sigaction for SIGINT");
      return -1;
    }
  if(options & OPT_TIMEOUT)
    {
      if(sigaction(SIGALRM, &si_sa, 0) == -1)
	{
	  printerror(errno, strerror, "could not set sigaction for SIGALRM");
	  return -1;
	}
    }

  /*
   * we loop for as long as we have not been told to finish up.
   * the finish_up loop will exit when
   *  - there has been an alarm set that goes off
   *  - a SIGINT is received (from e.g. Ctrl-C)
   *  - we have got_all_response()'s
   *
   * this is not an expensive loop in terms of cpu cycles, as the
   * recv_echo_response will sleep if there is nothing to recv until we have
   * told it to stop blocking - typically one second or whatever the between
   * timeout is.
   *
   * the loop does two things:
   *  - sends echo requests
   *  - receives echo responses
   *
   * the loop sends packets, pausing for however long the timeout is set for
   * between packets.  this pause is implemented in the recv_echo_response
   * function in a call to select(2).  if we cannot send a request to one of
   * them, we bail, as this probably means the syscall could not be called.
   *
   * the loop recv's the response and associates the packet with a host_entry
   * we then parse that response for the host entry, and then check if we have
   * now got all the responses we are looking for.  if we have, we exit the
   * loop by setting the finish_up flag
   */

  sent_all_requests = 0;
  i = 0;

  cursor = head;

  while(finish_up == 0)
    {
      while(sent_all_requests == 0)
	{
	  if(send_echo_request(cursor) != 0)
	    {
	      return -1;
	    }
	  cursor->tx++;

	  if(cursor->tx == count)
	    {
	      cursor = cursor->next;
	      if(cursor == NULL)
		{
		  sent_all_requests = 1;
		  alarm(timeout);
		  break;
		}
	    }

	  if(wait_between > 0)
	    {
	      gettimeofday(&wait_between_tv, &tz);
	      timeval_add(&wait_between_tv, wait_between);
	      break;
	    }
	}

      while(time_to_send_request() == 0 && finish_up == 0)
	{
	  if(recv_echo_responses() > 0)
	    {
	      if(got_all_responses() == 1)
		{
		  finish_up = 1;
		}
	    }
	}
    }

  /*
   * if we have been given a list of hosts to ping, we have to print out which
   * hosts did not give us a reply
   */
  if(options & OPT_NLANR)
    {
      show_loss();
    }

  return 0;
}
예제 #24
0
/**
 * Send reply to mesh reply entry
 * @param m: mesh state to send it for.
 * @param rcode: if not 0, error code.
 * @param rep: reply to send (or NULL if rcode is set).
 * @param r: reply entry
 * @param prev: previous reply, already has its answer encoded in buffer.
 */
static void
mesh_send_reply(struct mesh_state* m, int rcode, struct reply_info* rep,
	struct mesh_reply* r, struct mesh_reply* prev)
{
	struct timeval end_time;
	struct timeval duration;
	int secure;
	/* examine security status */
	if(m->s.env->need_to_validate && (!(r->qflags&BIT_CD) ||
		m->s.env->cfg->ignore_cd) && rep && 
		rep->security <= sec_status_bogus) {
		rcode = LDNS_RCODE_SERVFAIL;
		if(m->s.env->cfg->stat_extended) 
			m->s.env->mesh->ans_bogus++;
	}
	if(rep && rep->security == sec_status_secure)
		secure = 1;
	else	secure = 0;
	if(!rep && rcode == LDNS_RCODE_NOERROR)
		rcode = LDNS_RCODE_SERVFAIL;
	/* send the reply */
	if(prev && prev->qflags == r->qflags && 
		prev->edns.edns_present == r->edns.edns_present && 
		prev->edns.bits == r->edns.bits && 
		prev->edns.udp_size == r->edns.udp_size) {
		/* if the previous reply is identical to this one, fix ID */
		if(prev->query_reply.c->buffer != r->query_reply.c->buffer)
			ldns_buffer_copy(r->query_reply.c->buffer, 
				prev->query_reply.c->buffer);
		ldns_buffer_write_at(r->query_reply.c->buffer, 0, 
			&r->qid, sizeof(uint16_t));
		ldns_buffer_write_at(r->query_reply.c->buffer, 12, 
			r->qname, m->s.qinfo.qname_len);
		comm_point_send_reply(&r->query_reply);
	} else if(rcode) {
		m->s.qinfo.qname = r->qname;
		error_encode(r->query_reply.c->buffer, rcode, &m->s.qinfo,
			r->qid, r->qflags, &r->edns);
		comm_point_send_reply(&r->query_reply);
	} else {
		size_t udp_size = r->edns.udp_size;
		r->edns.edns_version = EDNS_ADVERTISED_VERSION;
		r->edns.udp_size = EDNS_ADVERTISED_SIZE;
		r->edns.ext_rcode = 0;
		r->edns.bits &= EDNS_DO;
		m->s.qinfo.qname = r->qname;
		if(!reply_info_answer_encode(&m->s.qinfo, rep, r->qid, 
			r->qflags, r->query_reply.c->buffer, 0, 1, 
			m->s.env->scratch, udp_size, &r->edns, 
			(int)(r->edns.bits & EDNS_DO), secure)) 
		{
			error_encode(r->query_reply.c->buffer, 
				LDNS_RCODE_SERVFAIL, &m->s.qinfo, r->qid, 
				r->qflags, &r->edns);
		}
		comm_point_send_reply(&r->query_reply);
	}
	/* account */
	m->s.env->mesh->num_reply_addrs--;
	end_time = *m->s.env->now_tv;
	timeval_subtract(&duration, &end_time, &r->start_time);
	verbose(VERB_ALGO, "query took %d.%6.6d sec",
		(int)duration.tv_sec, (int)duration.tv_usec);
	m->s.env->mesh->replies_sent++;
	timeval_add(&m->s.env->mesh->replies_sum_wait, &duration);
	timehist_insert(m->s.env->mesh->histogram, &duration);
	if(m->s.env->cfg->stat_extended) {
		uint16_t rc = FLAGS_GET_RCODE(ldns_buffer_read_u16_at(r->
			query_reply.c->buffer, 2));
		if(secure) m->s.env->mesh->ans_secure++;
		m->s.env->mesh->ans_rcode[ rc ] ++;
		if(rc == 0 && LDNS_ANCOUNT(ldns_buffer_begin(r->
			query_reply.c->buffer)) == 0)
			m->s.env->mesh->ans_nodata++;
	}
}
예제 #25
0
파일: clock.c 프로젝트: coodie/mimiker
static void clock_init(void) {
  timeval_t now = get_uptime();
  clock_event->tev_when = timeval_add(&now, &tick);
  cpu_timer_add_event(clock_event);
}
예제 #26
0
int
server_run()
{
    struct timeval* timeout;
    struct timeval tv, current;
    timer_callback* timcb;
    socket_callback* sockcb;
    fd_set rfds, wfds;
    int r;

    /* No watches have been set */
    ASSERT(ctx.max_fd > -1);

    ctx.stopped = 0;

    while(!ctx.stopped)
    {
        /* Watch for the various fds */
        memcpy(&rfds, &ctx.read_fds, sizeof(rfds));
        memcpy(&wfds, &ctx.write_fds, sizeof(wfds));

        /* Prepare for timers */
        timeout = NULL;
        if(gettimeofday(&current, NULL) == -1)
            return -1;

        /* Cycle through timers */
        for(timcb = ctx.timers; timcb; )
        {
            ASSERT(timcb->callback);

            /* Call any timers that have already passed */
            if(timeval_compare(&current, &timcb->at) >= 0)
            {
                /* Convert to milliseconds, and make the call */
                r = (timcb->callback)(timeval_to_ms(current), timcb->arg);

                /* Reset timer if so desired */
                if (r == 1 && !timeval_empty(&timcb->interval))
                {
                    timeval_add(&timcb->at, &timcb->interval);

                    /* If the time has already passed, just use current time */
                    if(timeval_compare(&(timcb->at), &current) <= 0)
                        memcpy(&(timcb->at), &current, sizeof(timcb->at));
                }

                /* Otherwise remove it. Either one shot, or returned 0 */
                else
                {
                    timcb = remove_timer(timcb);
                    continue;
                }
            }

            /* Get soonest timer */
            if (!timeout || timeval_compare(&timcb->at, timeout) < 0)
                timeout = &timcb->at;

            timcb = timcb->next;
        }

        /* Convert to an offset */
        if(timeout)
        {
            memcpy(&tv, timeout, sizeof(tv));
            timeout = &tv;
            timeval_subtract(timeout, &current);
        }

        /* fprintf(stderr, "selecting with timeout: ");
           timeval_dump(timeout);
           fprintf(stderr, "\n"); */

        r = select(ctx.max_fd, &rfds, &wfds, NULL, timeout);
        if (r < 0)
        {
            /* Interrupted so try again, and possibly exit */
            if (errno == EINTR)
                continue;

            /* Programmer errors */
            ASSERT (errno != EBADF);
            ASSERT (errno != EINVAL);
            return r;
        }

        /* Timeout, just jump to timeout processing */
        if(r == 0)
            continue;

        for(sockcb = ctx.callbacks; sockcb; sockcb = sockcb->next)
        {
            ASSERT(sockcb->fd != -1);

            /* Call any that are set */
            if (FD_ISSET(sockcb->fd, &rfds))
                (sockcb->callback)(sockcb->fd, SERVER_READ, sockcb->arg);
            if (FD_ISSET(sockcb->fd, &wfds))
                (sockcb->callback)(sockcb->fd, SERVER_WRITE, sockcb->arg);
        }
    }

    return 0;
}
예제 #27
0
NTSTATUS gensec_ntlmssp_server_negotiate(struct gensec_security *gensec_security,
					 TALLOC_CTX *out_mem_ctx,
					 const DATA_BLOB request, DATA_BLOB *reply)
{
	struct gensec_ntlmssp_context *gensec_ntlmssp =
		talloc_get_type_abort(gensec_security->private_data,
				      struct gensec_ntlmssp_context);
	struct ntlmssp_state *ntlmssp_state = gensec_ntlmssp->ntlmssp_state;
	struct auth4_context *auth_context = gensec_security->auth_context;
	DATA_BLOB struct_blob;
	uint32_t neg_flags = 0;
	uint32_t ntlmssp_command, chal_flags;
	uint8_t cryptkey[8];
	const char *target_name;
	NTSTATUS status;
	struct timeval tv_now = timeval_current();
	/*
	 * See [MS-NLMP]
	 *
	 * Windows NT 4.0, windows_2000: use 30 minutes,
	 * Windows XP, Windows Server 2003, Windows Vista,
	 * Windows Server 2008, Windows 7, and Windows Server 2008 R2
	 * use 36 hours.
	 *
	 * Newer systems doesn't check this, likely because the
	 * connectionless NTLMSSP is no longer supported.
	 *
	 * As we expect the AUTHENTICATION_MESSAGE to arrive
	 * directly after the NEGOTIATE_MESSAGE (typically less than
	 * as 1 second later). We use a hard timeout of 30 Minutes.
	 *
	 * We don't look at AUTHENTICATE_MESSAGE.NtChallengeResponse.TimeStamp
	 * instead we just remember our own time.
	 */
	uint32_t max_lifetime = 30 * 60;
	struct timeval tv_end = timeval_add(&tv_now, max_lifetime, 0);

	/* parse the NTLMSSP packet */
#if 0
	file_save("ntlmssp_negotiate.dat", request.data, request.length);
#endif

	if (request.length) {
		if (request.length > UINT16_MAX) {
			DEBUG(1, ("ntlmssp_server_negotiate: reject large request of length %u\n",
				(unsigned int)request.length));
			return NT_STATUS_INVALID_PARAMETER;
		}

		if ((request.length < 16) || !msrpc_parse(ntlmssp_state, &request, "Cdd",
							  "NTLMSSP",
							  &ntlmssp_command,
							  &neg_flags)) {
			DEBUG(1, ("ntlmssp_server_negotiate: failed to parse NTLMSSP Negotiate of length %u\n",
				(unsigned int)request.length));
			dump_data(2, request.data, request.length);
			return NT_STATUS_INVALID_PARAMETER;
		}
		debug_ntlmssp_flags(neg_flags);

		if (DEBUGLEVEL >= 10) {
			struct NEGOTIATE_MESSAGE *negotiate = talloc(
				ntlmssp_state, struct NEGOTIATE_MESSAGE);
			if (negotiate != NULL) {
				status = ntlmssp_pull_NEGOTIATE_MESSAGE(
					&request, negotiate, negotiate);
				if (NT_STATUS_IS_OK(status)) {
					NDR_PRINT_DEBUG(NEGOTIATE_MESSAGE,
							negotiate);
				}
				TALLOC_FREE(negotiate);
			}
		}
	}

	status = ntlmssp_handle_neg_flags(ntlmssp_state, neg_flags, "negotiate");
	if (!NT_STATUS_IS_OK(status)){
		return status;
	}

	/* Ask our caller what challenge they would like in the packet */
	if (auth_context->get_ntlm_challenge) {
		status = auth_context->get_ntlm_challenge(auth_context, cryptkey);
		if (!NT_STATUS_IS_OK(status)) {
			DEBUG(1, ("gensec_ntlmssp_server_negotiate: failed to get challenge: %s\n",
				  nt_errstr(status)));
			return status;
		}
	} else {
		DEBUG(1, ("gensec_ntlmssp_server_negotiate: backend doesn't give a challenge\n"));
		return NT_STATUS_NOT_IMPLEMENTED;
	}

	/* The flags we send back are not just the negotiated flags,
	 * they are also 'what is in this packet'.  Therfore, we
	 * operate on 'chal_flags' from here on
	 */

	chal_flags = ntlmssp_state->neg_flags;
	ntlmssp_state->server.challenge_endtime = timeval_to_nttime(&tv_end);

	/* get the right name to fill in as 'target' */
	target_name = ntlmssp_target_name(ntlmssp_state,
					  neg_flags, &chal_flags);
	if (target_name == NULL)
		return NT_STATUS_INVALID_PARAMETER;

	ntlmssp_state->chal = data_blob_talloc(ntlmssp_state, cryptkey, 8);
	ntlmssp_state->internal_chal = data_blob_talloc(ntlmssp_state,
							cryptkey, 8);

	/* This creates the 'blob' of names that appears at the end of the packet */
	if (chal_flags & NTLMSSP_NEGOTIATE_TARGET_INFO) {
		enum ndr_err_code err;
		struct AV_PAIR *pairs = NULL;
		uint32_t count = 5;

		pairs = talloc_zero_array(ntlmssp_state, struct AV_PAIR, count + 1);
		if (pairs == NULL) {
			return NT_STATUS_NO_MEMORY;
		}

		pairs[0].AvId			= MsvAvNbDomainName;
		pairs[0].Value.AvNbDomainName	= target_name;

		pairs[1].AvId			= MsvAvNbComputerName;
		pairs[1].Value.AvNbComputerName	= ntlmssp_state->server.netbios_name;

		pairs[2].AvId			= MsvAvDnsDomainName;
		pairs[2].Value.AvDnsDomainName	= ntlmssp_state->server.dns_domain;

		pairs[3].AvId			= MsvAvDnsComputerName;
		pairs[3].Value.AvDnsComputerName= ntlmssp_state->server.dns_name;

		if (!ntlmssp_state->force_old_spnego) {
			pairs[4].AvId			= MsvAvTimestamp;
			pairs[4].Value.AvTimestamp	=
						timeval_to_nttime(&tv_now);
			count += 1;

			pairs[5].AvId			= MsvAvEOL;
		} else {
			pairs[4].AvId			= MsvAvEOL;
		}

		ntlmssp_state->server.av_pair_list.count = count;
		ntlmssp_state->server.av_pair_list.pair = pairs;

		err = ndr_push_struct_blob(&struct_blob,
					ntlmssp_state,
					&ntlmssp_state->server.av_pair_list,
					(ndr_push_flags_fn_t)ndr_push_AV_PAIR_LIST);
		if (!NDR_ERR_CODE_IS_SUCCESS(err)) {
			return NT_STATUS_NO_MEMORY;
		}
	} else {
예제 #28
0
/**
 * Writes a packet into the pipe
 */
void PCAPExporterPipe::receive(Packet* packet)
{
	DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive() called");
	if (onRestart){
		 DPRINTF("Dropping incoming packet, as attached process is not ready");
		 DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive() ended");
		 packet->removeReference();
		 return;
	}
	if (fifoReaderPid == 0){
		 msg(MSG_VDEBUG, "fifoReaderPid = 0...this might happen during reconfiguration");
		 DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive() ended");
		 packet->removeReference();
		 return;
	}
	if (restartInterval) {
		if (nextRestart.tv_sec==0) {
			DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive(): updating nextRestart");
			nextRestart = packet->timestamp;
			struct timeval tv = { restartInterval/1000, (restartInterval % 1000)*1000 };
			timeval_add(&nextRestart, &tv);
		} else if (compareTime(nextRestart, packet->timestamp)<0) {
			DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive(): restarting process");

			// we need to unregister our signal handlers, as we get race conditions with the signal handler for restarting the process
			unregisterSignalHandlers();
			stopProcess();
			startProcess();
			registerSignalHandlers();
			DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive(): updating nextRestart");
			timeval tvdiff;
			timeval_subtract(&tvdiff, &packet->timestamp, &nextRestart);
			uint32_t msdiff = tvdiff.tv_sec*1000+tvdiff.tv_usec/1000;
			uint32_t mswait = (msdiff/restartInterval+1)*restartInterval;
			tvdiff.tv_sec = mswait/1000;
			tvdiff.tv_usec = (mswait%1000)*1000;
			timeval_add(&nextRestart, &tvdiff);
		}
	}

	// write packet
	static struct pcap_pkthdr packetHeader;
	packetHeader.ts = packet->timestamp;
	packetHeader.caplen = packet->data_length;
	packetHeader.len = packet->pcapPacketLength;
	struct iovec wvec[2];
	wvec[0].iov_base = &packetHeader;
	wvec[0].iov_len = sizeof(packetHeader);
	wvec[1].iov_base = packet->data;
	wvec[1].iov_len = packetHeader.caplen;
	if (writev(pcapFile, wvec, 2)!=(ssize_t)(sizeof(packetHeader)+packetHeader.caplen)) {
		if (errno==EAGAIN) {
			// pipe is full, drop packet
			statBytesDropped += packet->data_length;
			statPktsDropped++;
		} else
			THROWEXCEPTION("PCAPExporterPipe: failed to write, error %u (%s)", errno, strerror(errno));
	} else {
		statBytesForwarded += packet->data_length;
		statPktsForwarded++;
	}

	packet->removeReference();
	DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive() ended");
}
예제 #29
0
static NTSTATUS wreplsrv_scavenging_owned_records(struct wreplsrv_service *service, TALLOC_CTX *tmp_mem)
{
	NTSTATUS status;
	struct winsdb_record *rec = NULL;
	struct ldb_result *res = NULL;
	const char *owner_filter;
	const char *filter;
	uint32_t i;
	int ret;
	time_t now = time(NULL);
	const char *now_timestr;
	const char *action;
	const char *old_state=NULL;
	const char *new_state=NULL;
	uint32_t modify_flags;
	BOOL modify_record;
	BOOL delete_record;
	BOOL delete_tombstones;
	struct timeval tombstone_extra_time;

	now_timestr = ldb_timestring(tmp_mem, now);
	NT_STATUS_HAVE_NO_MEMORY(now_timestr);
	owner_filter = wreplsrv_owner_filter(service, tmp_mem,
					     service->wins_db->local_owner);
	NT_STATUS_HAVE_NO_MEMORY(owner_filter);
	filter = talloc_asprintf(tmp_mem,
				 "(&%s(objectClass=winsRecord)"
				 "(expireTime<=%s))",
				 owner_filter, now_timestr);
	NT_STATUS_HAVE_NO_MEMORY(filter);
	ret = ldb_search(service->wins_db->ldb, NULL, LDB_SCOPE_SUBTREE, filter, NULL, &res);
	if (ret != LDB_SUCCESS) return NT_STATUS_INTERNAL_DB_CORRUPTION;
	talloc_steal(tmp_mem, res);
	DEBUG(10,("WINS scavenging: filter '%s' count %d\n", filter, res->count));

	tombstone_extra_time = timeval_add(&service->startup_time,
					   service->config.tombstone_extra_timeout,
					   0);
	delete_tombstones = timeval_expired(&tombstone_extra_time);

	for (i=0; i < res->count; i++) {
		/*
		 * we pass '0' as 'now' here,
		 * because we want to get the raw timestamps which are in the DB
		 */
		status = winsdb_record(service->wins_db, res->msgs[i], tmp_mem, 0, &rec);
		NT_STATUS_NOT_OK_RETURN(status);
		talloc_free(res->msgs[i]);

		modify_flags	= 0;
		modify_record	= False;
		delete_record	= False;

		switch (rec->state) {
		case WREPL_STATE_ACTIVE:
			old_state	= "active";
			new_state	= "active";
			if (!rec->is_static) {
				new_state	= "released";
				rec->state	= WREPL_STATE_RELEASED;
				rec->expire_time= service->config.tombstone_interval + now;
			}
			modify_flags	= 0;
			modify_record	= True;
			break;

		case WREPL_STATE_RELEASED:
			old_state	= "released";
			new_state	= "tombstone";
			rec->state	= WREPL_STATE_TOMBSTONE;
			rec->expire_time= service->config.tombstone_timeout + now;
			modify_flags	= WINSDB_FLAG_ALLOC_VERSION | WINSDB_FLAG_TAKE_OWNERSHIP;
			modify_record	= True;
			break;

		case WREPL_STATE_TOMBSTONE:
			old_state	= "tombstone";
			new_state	= "tombstone";
			if (!delete_tombstones) break;
			new_state	= "deleted";
			delete_record = True;
			break;

		case WREPL_STATE_RESERVED:
			DEBUG(0,("%s: corrupted record: %s\n",
				__location__, nbt_name_string(rec, rec->name)));
			return NT_STATUS_INTERNAL_DB_CORRUPTION;
		}

		if (modify_record) {
			action = "modify";
			ret = winsdb_modify(service->wins_db, rec, modify_flags);
		} else if (delete_record) {
			action = "delete";
			ret = winsdb_delete(service->wins_db, rec);
		} else {
			action = "skip";
			ret = NBT_RCODE_OK;
		}

		if (ret != NBT_RCODE_OK) {
			DEBUG(1,("WINS scavenging: failed to %s name %s (owned:%s -> owned:%s): error:%u\n",
				action, nbt_name_string(rec, rec->name), old_state, new_state, ret));
		} else {
			DEBUG(4,("WINS scavenging: %s name: %s (owned:%s -> owned:%s)\n",
				action, nbt_name_string(rec, rec->name), old_state, new_state));
		}

		talloc_free(rec);
	}

	return NT_STATUS_OK;
}
예제 #30
0
파일: userman.c 프로젝트: rchicoli/samba
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;
}