static int usr_info_cmp(const struct usrinfo *usr1, const struct usrinfo *usr2) { /* Called from qsort to compare two users in a usrinfo_t array for * sorting by login time. Return >0 if usr1 login time was later than * usr2 login time, <0 if it was earlier */ return timeval_compare(&usr1->login_time, &usr2->login_time); }
void do_resend() { struct resend *resend; resend = to_resend; while(resend) { if(!resend_expired(resend) && resend->delay > 0 && resend->max > 0) { struct timeval timeout; timeval_add_msec(&timeout, &resend->time, resend->delay); if(timeval_compare(&now, &timeout) >= 0) { switch(resend->kind) { case RESEND_REQUEST: send_multihop_request(resend->ifp, resend->prefix, resend->plen, resend->src_prefix, resend->src_plen, resend->seqno, resend->id, 127); break; case RESEND_UPDATE: send_update(resend->ifp, 1, resend->prefix, resend->plen, resend->src_prefix, resend->src_plen); break; default: abort(); } resend->delay = MIN(0xFFFF, resend->delay * 2); resend->max--; } } resend = resend->next; } recompute_resend_time(); }
Usec timeval_diff(const struct timeval *a, const struct timeval *b) { assert(a); assert(b); if (timeval_compare(a, b) < 0) return - timeval_diff(b, a); return ((Usec) a->tv_sec - b->tv_sec)*1000000 + a->tv_usec - b->tv_usec; }
/* {0, 0} represents infinity */ void timeval_min(struct timeval *d, const struct timeval *s) { if(s->tv_sec == 0) return; if(d->tv_sec == 0 || timeval_compare(d, s) > 0) { *d = *s; } }
_PUBLIC_ struct timeval timeval_until(const struct timeval *tv1, const struct timeval *tv2) { struct timeval t; if (timeval_compare(tv1, tv2) >= 0) { return timeval_zero(); } t.tv_sec = tv2->tv_sec - tv1->tv_sec; if (tv1->tv_usec > tv2->tv_usec) { t.tv_sec--; t.tv_usec = 1000000 - (tv1->tv_usec - tv2->tv_usec); } else { t.tv_usec = tv2->tv_usec - tv1->tv_usec; } return t; }
void lua_timer_execute(const struct timeval* start) { lua_State* lua = lua_api_get(); lua_Number newdelay; TIMER_FOREACH(iter, timer) { if (timeval_compare(start, &timer->time) > 0) { lua_rawgeti(lua, LUA_REGISTRYINDEX, timer->func); if (lua_pcall(lua, 0, 1, 0) != 0) { const gchar* what = lua_tostring(lua, -1); ERROR("Error in timer callback: %s", what); } else if (lua_isnumber(lua, -1) && (newdelay = lua_tonumber(lua, -1)) > 0) { timer->time = *start; timeval_add_delay(&timer->time, newdelay); } else { timer->dead = TRUE; } lua_pop(lua, 1); } } }
/* We just got an Update for the default route. */ int update_selected_route(struct interface *interface, struct in6_addr *nexthop, short interval, int metric) { struct timeval now; int n = find_neighbour(interface, nexthop, 0); if(n < 0) return 0; metric += MAX(link_cost, neighbours[n].rxcost); gettime(&now); if(selected_nexthop_metric >= INFINITY || interface != selected_interface || memcmp(nexthop, &selected_nexthop, sizeof(selected_nexthop)) != 0) { int rc; if(metric >= INFINITY || (metric >= selected_nexthop_metric + 32 && timeval_compare(&now, &selected_nexthop_timeout) < 0)) { /* Our currently selected route is just as good or better. */ return 0; } rc = install_default_route(interface->ifindex, nexthop); if(rc < 0) { perror("install_default_route"); return -1; } selected_interface = interface; memcpy(&selected_nexthop, nexthop, sizeof(selected_nexthop)); } selected_nexthop_metric = metric; /* Expire this route when we lose 3 updates in a row. */ timeval_add_msec(&selected_nexthop_timeout, &now, 3 * interval * 10 + rand() % (interval * 5)); return 1; }
NTSTATUS wreplsrv_periodic_schedule(struct wreplsrv_service *service, uint32_t next_interval) { TALLOC_CTX *tmp_mem; struct tevent_timer *new_te; struct timeval next_time; /* prevent looping */ if (next_interval == 0) next_interval = 1; next_time = timeval_current_ofs(next_interval, 5000); if (service->periodic.te) { /* * if the timestamp of the new event is higher, * as current next we don't need to reschedule */ if (timeval_compare(&next_time, &service->periodic.next_event) > 0) { return NT_STATUS_OK; } } /* reset the next scheduled timestamp */ service->periodic.next_event = next_time; new_te = event_add_timed(service->task->event_ctx, service, service->periodic.next_event, wreplsrv_periodic_handler_te, service); NT_STATUS_HAVE_NO_MEMORY(new_te); tmp_mem = talloc_new(service); DEBUG(6,("wreplsrv_periodic_schedule(%u) %sscheduled for: %s\n", next_interval, (service->periodic.te?"re":""), nt_time_string(tmp_mem, timeval_to_nttime(&next_time)))); talloc_free(tmp_mem); talloc_free(service->periodic.te); service->periodic.te = new_te; return NT_STATUS_OK; }
struct timed_event *add_timed_event(TALLOC_CTX *mem_ctx, struct timeval when, const char *event_name, void (*handler)(struct timed_event *te, const struct timeval *now, void *private_data), void *private_data) { struct timed_event *te, *last_te, *cur_te; te = TALLOC_P(mem_ctx, struct timed_event); if (te == NULL) { DEBUG(0, ("talloc failed\n")); return NULL; } te->when = when; te->event_name = event_name; te->handler = handler; te->private_data = private_data; /* keep the list ordered */ last_te = NULL; for (cur_te = timed_events; cur_te; cur_te = cur_te->next) { /* if the new event comes before the current one break */ if (!timeval_is_zero(&cur_te->when) && timeval_compare(&te->when, &cur_te->when) < 0) { break; } last_te = cur_te; } DLIST_ADD_AFTER(timed_events, te, last_te); talloc_set_destructor(te, timed_event_destructor); DEBUG(10, ("Added timed event \"%s\": %lx\n", event_name, (unsigned long)te)); return te; }
static inline int frames_to_send(struct timeval *today, struct timeval *diff, struct timeval *log) { /* return value <0 when log + diff < today */ struct timeval cmp; cmp.tv_sec = log->tv_sec + diff->tv_sec; cmp.tv_usec = log->tv_usec + diff->tv_usec; if (cmp.tv_usec > 1000000) { cmp.tv_usec -= 1000000; cmp.tv_sec++; } if (cmp.tv_usec < 0) { cmp.tv_usec += 1000000; cmp.tv_sec--; } return timeval_compare(&cmp, today); }
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; }
void process_blocking_lock_queue(void) { struct timeval tv_curr = timeval_current(); struct blocking_lock_record *blr, *next = NULL; bool recalc_timeout = False; /* * Go through the queue and see if we can get any of the locks. */ for (blr = blocking_lock_queue; blr; blr = next) { next = blr->next; /* * Go through the remaining locks and try and obtain them. * The call returns True if all locks were obtained successfully * and False if we still need to wait. */ DEBUG(10, ("Processing BLR = %p\n", blr)); if(blocking_lock_record_process(blr)) { struct byte_range_lock *br_lck = brl_get_locks( talloc_tos(), blr->fsp); DEBUG(10, ("BLR_process returned true: cancelling and " "removing lock. BLR = %p\n", blr)); if (br_lck) { brl_lock_cancel(br_lck, blr->lock_pid, procid_self(), blr->offset, blr->count, blr->lock_flav, blr); TALLOC_FREE(br_lck); } DLIST_REMOVE(blocking_lock_queue, blr); TALLOC_FREE(blr); recalc_timeout = True; continue; } /* * We couldn't get the locks for this record on the list. * If the time has expired, return a lock error. */ if (!timeval_is_zero(&blr->expire_time) && timeval_compare(&blr->expire_time, &tv_curr) <= 0) { struct byte_range_lock *br_lck = brl_get_locks( talloc_tos(), blr->fsp); DEBUG(10, ("Lock timed out! BLR = %p\n", blr)); /* * Lock expired - throw away all previously * obtained locks and return lock error. */ if (br_lck) { DEBUG(5,("process_blocking_lock_queue: " "pending lock fnum = %d for file %s " "timed out.\n", blr->fsp->fnum, blr->fsp->fsp_name )); brl_lock_cancel(br_lck, blr->lock_pid, procid_self(), blr->offset, blr->count, blr->lock_flav, blr); TALLOC_FREE(br_lck); } blocking_lock_reply_error(blr,NT_STATUS_FILE_LOCK_CONFLICT); DLIST_REMOVE(blocking_lock_queue, blr); TALLOC_FREE(blr); recalc_timeout = True; } } if (recalc_timeout) { recalc_brl_timeout(); } }
static int fork_tcon_client(struct torture_context *tctx, int *tcon_count, unsigned tcon_timelimit, const char *host, const char *share) { pid_t child; struct smbcli_state *cli; struct timeval end; struct timeval now; struct smbcli_options options; struct smbcli_session_options session_options; lpcfg_smbcli_options(tctx->lp_ctx, &options); lpcfg_smbcli_session_options(tctx->lp_ctx, &session_options); child = fork(); if (child == -1) { printf("failed to fork child: %s\n,", strerror(errno)); return -1; } else if (child != 0) { /* Parent, just return. */ return 0; } /* Child. Just make as many connections as possible within the * time limit. Don't bother synchronising the child start times * because it's probably not work the effort, and a bit of startup * jitter is probably a more realistic test. */ end = timeval_current(); now = timeval_current(); end.tv_sec += tcon_timelimit; *tcon_count = 0; while (timeval_compare(&now, &end) == -1) { NTSTATUS status; status = smbcli_full_connection(NULL, &cli, host, lpcfg_smb_ports(tctx->lp_ctx), share, NULL, lpcfg_socket_options(tctx->lp_ctx), cmdline_credentials, lpcfg_resolve_context(tctx->lp_ctx), tctx->ev, &options, &session_options, lpcfg_gensec_settings(tctx, tctx->lp_ctx)); if (!NT_STATUS_IS_OK(status)) { printf("failed to connect to //%s/%s: %s\n", host, share, nt_errstr(status)); goto done; } smbcli_tdis(cli); talloc_free(cli); *tcon_count = *tcon_count + 1; now = timeval_current(); } done: exit(0); }
static int compare_share_mode_times(const void *p1, const void *p2) { const struct share_mode_entry *s1 = (const struct share_mode_entry *)p1; const struct share_mode_entry *s2 = (const struct share_mode_entry *)p2; return timeval_compare(&s1->time, &s2->time); }
void process_blocking_lock_queue(struct smbd_server_connection *sconn) { struct timeval tv_curr = timeval_current(); struct blocking_lock_record *blr, *next = NULL; if (sconn->using_smb2) { process_blocking_lock_queue_smb2(sconn, tv_curr); return; } /* * Go through the queue and see if we can get any of the locks. */ for (blr = sconn->smb1.locks.blocking_lock_queue; blr; blr = next) { next = blr->next; /* * Go through the remaining locks and try and obtain them. * The call returns True if all locks were obtained successfully * and False if we still need to wait. */ DEBUG(10, ("Processing BLR = %p\n", blr)); /* We use set_current_service so connections with * pending locks are not marked as idle. */ set_current_service(blr->fsp->conn, SVAL(blr->req->inbuf,smb_flg), false); if(blocking_lock_record_process(blr)) { struct byte_range_lock *br_lck = brl_get_locks( talloc_tos(), blr->fsp); DEBUG(10, ("BLR_process returned true: cancelling and " "removing lock. BLR = %p\n", blr)); if (br_lck) { brl_lock_cancel(br_lck, blr->smblctx, messaging_server_id(sconn->msg_ctx), blr->offset, blr->count, blr->lock_flav, blr); TALLOC_FREE(br_lck); } DLIST_REMOVE(sconn->smb1.locks.blocking_lock_queue, blr); TALLOC_FREE(blr); continue; } /* * We couldn't get the locks for this record on the list. * If the time has expired, return a lock error. */ if (!timeval_is_zero(&blr->expire_time) && timeval_compare(&blr->expire_time, &tv_curr) <= 0) { struct byte_range_lock *br_lck = brl_get_locks( talloc_tos(), blr->fsp); DEBUG(10, ("Lock timed out! BLR = %p\n", blr)); /* * Lock expired - throw away all previously * obtained locks and return lock error. */ if (br_lck) { DEBUG(5,("process_blocking_lock_queue: " "pending lock for %s, file %s " "timed out.\n", fsp_fnum_dbg(blr->fsp), fsp_str_dbg(blr->fsp))); brl_lock_cancel(br_lck, blr->smblctx, messaging_server_id(sconn->msg_ctx), blr->offset, blr->count, blr->lock_flav, blr); TALLOC_FREE(br_lck); } blocking_lock_reply_error(blr,NT_STATUS_FILE_LOCK_CONFLICT); DLIST_REMOVE(sconn->smb1.locks.blocking_lock_queue, blr); TALLOC_FREE(blr); } } recalc_brl_timeout(sconn); }
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(¤t, 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(¤t, &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), ¤t) <= 0) memcpy(&(timcb->at), ¤t, 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, ¤t); } /* 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; }
/* Return true if the ith neighbour has expired. */ int neighbour_expired(int i, const struct timeval *now) { return (timeval_compare(now, &neighbours[i].timeout) > 0); }
int main(int argc, char **argv) { struct sockaddr_in6 sin6; int rc, fd, i, opt; time_t expiry_time, source_expiry_time, kernel_dump_time; const char **config_files = NULL; int num_config_files = 0; void *vrc; unsigned int seed; struct interface *ifp; gettime(&now); rc = read_random_bytes(&seed, sizeof(seed)); if(rc < 0) { perror("read(random)"); seed = 42; } seed ^= (now.tv_sec ^ now.tv_usec); srandom(seed); parse_address("ff02:0:0:0:0:0:1:6", protocol_group, NULL); protocol_port = 6696; change_smoothing_half_life(4); has_ipv6_subtrees = kernel_has_ipv6_subtrees(); while(1) { opt = getopt(argc, argv, "m:p:h:H:i:k:A:sruS:d:g:G:lwz:M:t:T:c:C:DL:I:V"); if(opt < 0) break; switch(opt) { case 'm': rc = parse_address(optarg, protocol_group, NULL); if(rc < 0) goto usage; if(protocol_group[0] != 0xff) { fprintf(stderr, "%s is not a multicast address\n", optarg); goto usage; } if(protocol_group[1] != 2) { fprintf(stderr, "Warning: %s is not a link-local multicast address\n", optarg); } break; case 'p': protocol_port = parse_nat(optarg); if(protocol_port <= 0 || protocol_port > 0xFFFF) goto usage; break; case 'h': default_wireless_hello_interval = parse_thousands(optarg); if(default_wireless_hello_interval <= 0 || default_wireless_hello_interval > 0xFFFF * 10) goto usage; break; case 'H': default_wired_hello_interval = parse_thousands(optarg); if(default_wired_hello_interval <= 0 || default_wired_hello_interval > 0xFFFF * 10) goto usage; break; case 'k': kernel_metric = parse_nat(optarg); if(kernel_metric < 0 || kernel_metric > 0xFFFF) goto usage; break; case 'A': allow_duplicates = parse_nat(optarg); if(allow_duplicates < 0 || allow_duplicates > 0xFFFF) goto usage; break; case 's': split_horizon = 0; break; case 'r': random_id = 1; break; case 'u': keep_unfeasible = 1; break; case 'S': state_file = optarg; break; case 'd': debug = parse_nat(optarg); if(debug < 0) goto usage; break; case 'g': case 'G': if(opt == 'g') local_server_write = 0; else local_server_write = 1; if(optarg[0] == '/') { local_server_port = -1; free(local_server_path); local_server_path = strdup(optarg); } else { local_server_port = parse_nat(optarg); free(local_server_path); local_server_path = NULL; if(local_server_port <= 0 || local_server_port > 0xFFFF) goto usage; } break; case 'l': link_detect = 1; break; case 'w': all_wireless = 1; break; case 'z': { char *comma; diversity_kind = (int)strtol(optarg, &comma, 0); if(*comma == '\0') diversity_factor = 128; else if(*comma == ',') diversity_factor = parse_nat(comma + 1); else goto usage; if(diversity_factor <= 0 || diversity_factor > 256) goto usage; } break; case 'M': { int l = parse_nat(optarg); if(l < 0 || l > 3600) goto usage; change_smoothing_half_life(l); break; } case 't': export_table = parse_nat(optarg); if(export_table < 0 || export_table > 0xFFFF) goto usage; break; case 'T': if(add_import_table(parse_nat(optarg))) goto usage; break; case 'c': config_files = realloc(config_files, (num_config_files + 1) * sizeof(char*)); if(config_files == NULL) { fprintf(stderr, "Couldn't allocate config file.\n"); exit(1); } config_files[num_config_files++] = optarg; break; case 'C': rc = parse_config_from_string(optarg, strlen(optarg), NULL); if(rc != CONFIG_ACTION_DONE) { fprintf(stderr, "Couldn't parse configuration from command line.\n"); exit(1); } break; case 'D': do_daemonise = 1; break; case 'L': logfile = optarg; break; case 'I': pidfile = optarg; break; case 'V': fprintf(stderr, "%s\n", BABELD_VERSION); exit(0); break; default: goto usage; } } if(num_config_files == 0) { if(access("/etc/babeld.conf", F_OK) >= 0) { config_files = malloc(sizeof(char*)); if(config_files == NULL) { fprintf(stderr, "Couldn't allocate config file.\n"); exit(1); } config_files[num_config_files++] = "/etc/babeld.conf"; } } for(i = 0; i < num_config_files; i++) { int line; rc = parse_config_from_file(config_files[i], &line); if(rc < 0) { fprintf(stderr, "Couldn't parse configuration from file %s " "(error at line %d).\n", config_files[i], line); exit(1); } } free(config_files); if(default_wireless_hello_interval <= 0) default_wireless_hello_interval = 4000; default_wireless_hello_interval = MAX(default_wireless_hello_interval, 5); if(default_wired_hello_interval <= 0) default_wired_hello_interval = 4000; default_wired_hello_interval = MAX(default_wired_hello_interval, 5); resend_delay = 2000; resend_delay = MIN(resend_delay, default_wireless_hello_interval / 2); resend_delay = MIN(resend_delay, default_wired_hello_interval / 2); resend_delay = MAX(resend_delay, 20); if(do_daemonise) { if(logfile == NULL) logfile = "/var/log/babeld.log"; } rc = reopen_logfile(); if(rc < 0) { perror("reopen_logfile()"); exit(1); } fd = open("/dev/null", O_RDONLY); if(fd < 0) { perror("open(null)"); exit(1); } rc = dup2(fd, 0); if(rc < 0) { perror("dup2(null, 0)"); exit(1); } close(fd); if(do_daemonise) { rc = daemonise(); if(rc < 0) { perror("daemonise"); exit(1); } } if(pidfile && pidfile[0] != '\0') { int pfd, len; char buf[100]; len = snprintf(buf, 100, "%lu", (unsigned long)getpid()); if(len < 0 || len >= 100) { perror("snprintf(getpid)"); exit(1); } pfd = open(pidfile, O_WRONLY | O_CREAT | O_EXCL, 0644); if(pfd < 0) { char buf[40]; snprintf(buf, 40, "creat(%s)", pidfile); buf[39] = '\0'; perror(buf); exit(1); } rc = write(pfd, buf, len); if(rc < len) { perror("write(pidfile)"); goto fail_pid; } close(pfd); } rc = kernel_setup(1); if(rc < 0) { fprintf(stderr, "kernel_setup failed.\n"); goto fail_pid; } rc = kernel_setup_socket(1); if(rc < 0) { fprintf(stderr, "kernel_setup_socket failed.\n"); kernel_setup(0); goto fail_pid; } rc = finalise_config(); if(rc < 0) { fprintf(stderr, "Couldn't finalise configuration.\n"); goto fail; } for(i = optind; i < argc; i++) { vrc = add_interface(argv[i], NULL); if(vrc == NULL) goto fail; } if(interfaces == NULL) { fprintf(stderr, "Eek... asked to run on no interfaces!\n"); goto fail; } if(!have_id && !random_id) { /* We use all available interfaces here, since this increases the chances of getting a stable router-id in case the set of Babel interfaces changes. */ for(i = 1; i < 256; i++) { char buf[IF_NAMESIZE], *ifname; unsigned char eui[8]; ifname = if_indextoname(i, buf); if(ifname == NULL) continue; rc = if_eui64(ifname, i, eui); if(rc < 0) continue; memcpy(myid, eui, 8); have_id = 1; break; } } if(!have_id) { if(!random_id) fprintf(stderr, "Warning: couldn't find router id -- " "using random value.\n"); rc = read_random_bytes(myid, 8); if(rc < 0) { perror("read(random)"); goto fail; } /* Clear group and global bits */ myid[0] &= ~3; } myseqno = (random() & 0xFFFF); fd = open(state_file, O_RDONLY); if(fd < 0 && errno != ENOENT) perror("open(babel-state)"); rc = unlink(state_file); if(fd >= 0 && rc < 0) { perror("unlink(babel-state)"); /* If we couldn't unlink it, it's probably stale. */ close(fd); fd = -1; } if(fd >= 0) { char buf[100]; int s; rc = read(fd, buf, 99); if(rc < 0) { perror("read(babel-state)"); } else { buf[rc] = '\0'; rc = sscanf(buf, "%d\n", &s); if(rc == 1 && s >= 0 && s <= 0xFFFF) { myseqno = seqno_plus(s, 1); } else { fprintf(stderr, "Couldn't parse babel-state.\n"); } } close(fd); fd = -1; } protocol_socket = babel_socket(protocol_port); if(protocol_socket < 0) { perror("Couldn't create link local socket"); goto fail; } if(local_server_port >= 0) { local_server_socket = tcp_server_socket(local_server_port, 1); if(local_server_socket < 0) { perror("local_server_socket"); goto fail; } } else if(local_server_path) { local_server_socket = unix_server_socket(local_server_path); if(local_server_socket < 0) { perror("local_server_socket"); goto fail; } } init_signals(); rc = resize_receive_buffer(1500); if(rc < 0) goto fail; if(receive_buffer == NULL) goto fail; check_interfaces(); rc = check_xroutes(0); if(rc < 0) fprintf(stderr, "Warning: couldn't check exported routes.\n"); rc = check_rules(); if(rc < 0) fprintf(stderr, "Warning: couldn't check rules.\n"); kernel_routes_changed = 0; kernel_rules_changed = 0; kernel_link_changed = 0; kernel_addr_changed = 0; kernel_dump_time = now.tv_sec + roughly(30); schedule_neighbours_check(5000, 1); schedule_interfaces_check(30000, 1); expiry_time = now.tv_sec + roughly(30); source_expiry_time = now.tv_sec + roughly(300); /* Make some noise so that others notice us, and send retractions in case we were restarted recently */ FOR_ALL_INTERFACES(ifp) { if(!if_up(ifp)) continue; /* Apply jitter before we send the first message. */ usleep(roughly(10000)); gettime(&now); send_hello(ifp); send_wildcard_retraction(ifp); } FOR_ALL_INTERFACES(ifp) { if(!if_up(ifp)) continue; usleep(roughly(10000)); gettime(&now); send_hello(ifp); send_wildcard_retraction(ifp); send_self_update(ifp); send_request(ifp, NULL, 0, NULL, 0); flushupdates(ifp); flushbuf(ifp); } debugf("Entering main loop.\n"); while(1) { struct timeval tv; fd_set readfds; gettime(&now); tv = check_neighbours_timeout; timeval_min(&tv, &check_interfaces_timeout); timeval_min_sec(&tv, expiry_time); timeval_min_sec(&tv, source_expiry_time); timeval_min_sec(&tv, kernel_dump_time); timeval_min(&tv, &resend_time); FOR_ALL_INTERFACES(ifp) { if(!if_up(ifp)) continue; timeval_min(&tv, &ifp->flush_timeout); timeval_min(&tv, &ifp->hello_timeout); timeval_min(&tv, &ifp->update_timeout); timeval_min(&tv, &ifp->update_flush_timeout); } timeval_min(&tv, &unicast_flush_timeout); FD_ZERO(&readfds); if(timeval_compare(&tv, &now) > 0) { int maxfd = 0; timeval_minus(&tv, &tv, &now); FD_SET(protocol_socket, &readfds); maxfd = MAX(maxfd, protocol_socket); if(kernel_socket < 0) kernel_setup_socket(1); if(kernel_socket >= 0) { FD_SET(kernel_socket, &readfds); maxfd = MAX(maxfd, kernel_socket); } if(local_server_socket >= 0 && num_local_sockets < MAX_LOCAL_SOCKETS) { FD_SET(local_server_socket, &readfds); maxfd = MAX(maxfd, local_server_socket); } for(i = 0; i < num_local_sockets; i++) { FD_SET(local_sockets[i].fd, &readfds); maxfd = MAX(maxfd, local_sockets[i].fd); } rc = select(maxfd + 1, &readfds, NULL, NULL, &tv); if(rc < 0) { if(errno != EINTR) { perror("select"); sleep(1); } rc = 0; FD_ZERO(&readfds); } } gettime(&now); if(exiting) break; if(kernel_socket >= 0 && FD_ISSET(kernel_socket, &readfds)) { struct kernel_filter filter = {0}; filter.route = kernel_route_notify; filter.addr = kernel_addr_notify; filter.link = kernel_link_notify; filter.rule = kernel_rule_notify; kernel_callback(&filter); } if(FD_ISSET(protocol_socket, &readfds)) { rc = babel_recv(protocol_socket, receive_buffer, receive_buffer_size, (struct sockaddr*)&sin6, sizeof(sin6)); if(rc < 0) { if(errno != EAGAIN && errno != EINTR) { perror("recv"); sleep(1); } } else { FOR_ALL_INTERFACES(ifp) { if(!if_up(ifp)) continue; if(ifp->ifindex == sin6.sin6_scope_id) { parse_packet((unsigned char*)&sin6.sin6_addr, ifp, receive_buffer, rc); VALGRIND_MAKE_MEM_UNDEFINED(receive_buffer, receive_buffer_size); break; } } } } if(local_server_socket >= 0 && FD_ISSET(local_server_socket, &readfds)) accept_local_connections(); i = 0; while(i < num_local_sockets) { if(FD_ISSET(local_sockets[i].fd, &readfds)) { rc = local_read(&local_sockets[i]); if(rc <= 0) { if(rc < 0) { if(errno == EINTR || errno == EAGAIN) continue; perror("read(local_socket)"); } local_socket_destroy(i); } } i++; } if(reopening) { kernel_dump_time = now.tv_sec; check_neighbours_timeout = now; expiry_time = now.tv_sec; rc = reopen_logfile(); if(rc < 0) { perror("reopen_logfile"); break; } reopening = 0; } if(kernel_link_changed || kernel_addr_changed) { check_interfaces(); kernel_link_changed = 0; } if(kernel_routes_changed || kernel_addr_changed || kernel_rules_changed || now.tv_sec >= kernel_dump_time) { rc = check_xroutes(1); if(rc < 0) fprintf(stderr, "Warning: couldn't check exported routes.\n"); rc = check_rules(); if(rc < 0) fprintf(stderr, "Warning: couldn't check rules.\n"); kernel_routes_changed = kernel_rules_changed = kernel_addr_changed = 0; if(kernel_socket >= 0) kernel_dump_time = now.tv_sec + roughly(300); else kernel_dump_time = now.tv_sec + roughly(30); } if(timeval_compare(&check_neighbours_timeout, &now) < 0) { int msecs; msecs = check_neighbours(); /* Multiply by 3/2 to allow neighbours to expire. */ msecs = MAX(3 * msecs / 2, 10); schedule_neighbours_check(msecs, 1); } if(timeval_compare(&check_interfaces_timeout, &now) < 0) { check_interfaces(); schedule_interfaces_check(30000, 1); } if(now.tv_sec >= expiry_time) { expire_routes(); expire_resend(); expiry_time = now.tv_sec + roughly(30); } if(now.tv_sec >= source_expiry_time) { expire_sources(); source_expiry_time = now.tv_sec + roughly(300); } FOR_ALL_INTERFACES(ifp) { if(!if_up(ifp)) continue; if(timeval_compare(&now, &ifp->hello_timeout) >= 0) send_hello(ifp); if(timeval_compare(&now, &ifp->update_timeout) >= 0) send_update(ifp, 0, NULL, 0, NULL, 0); if(timeval_compare(&now, &ifp->update_flush_timeout) >= 0) flushupdates(ifp); } if(resend_time.tv_sec != 0) { if(timeval_compare(&now, &resend_time) >= 0) do_resend(); } if(unicast_flush_timeout.tv_sec != 0) { if(timeval_compare(&now, &unicast_flush_timeout) >= 0) flush_unicast(1); } FOR_ALL_INTERFACES(ifp) { if(!if_up(ifp)) continue; if(ifp->flush_timeout.tv_sec != 0) { if(timeval_compare(&now, &ifp->flush_timeout) >= 0) flushbuf(ifp); } } if(UNLIKELY(debug || dumping)) { dump_tables(stdout); dumping = 0; } }
int main(int argc, char **argv) { int i, opt, rc; int sock; struct timeval now; gettime(&now); inet_pton(AF_INET6, "ff02::1:6", &babel_group); babel_port = 6696; srand(now.tv_sec ^ now.tv_usec); while(1) { opt = getopt(argc, argv, "p:u:h:c:"); if(opt < 0) break; switch(opt) { case 'p': /* prefix */ if(have_prefix) goto usage; rc = inet_pton(AF_INET6, optarg, &myprefix); if(rc != 1) goto usage; have_prefix = 1; break; case 'u': /* update interval */ update_interval = atoi(optarg); if(update_interval <= 0) goto usage; break; case 'h': /* hello interval */ hello_interval = atoi(optarg); if(hello_interval <= 0) goto usage; break; case 'c': /* link cost */ link_cost = atoi(optarg); if(link_cost <= 0) goto usage; break; default: goto usage; } } if(!have_prefix) fprintf(stderr, "Warning: you didn't ask me to announce a prefix.\n"); if(argc - optind > MAXINTERFACES) { fprintf(stderr, "Too many interfaces.\n"); exit(1); } for(i = 0; i < argc - optind; i++) { int index; index = if_nametoindex(argv[optind + i]); if(index <= 0) { fprintf(stderr, "Unknown interface %s\n", argv[i]); exit(1); } memset(&interfaces[i], 0, sizeof(interfaces[i])); interfaces[i].ifindex = index; interfaces[i].ifname = argv[optind + i]; rc = get_local_address(interfaces[i].ifindex, &interfaces[i].address); if(rc < 0) { perror("get_local_address"); fprintf(stderr, "Continuing anyway -- " "won't perform reachibility detection " "on interface %s.\n", interfaces[i].ifname); } interfaces[i].seqno = rand() & 0xFFFF; } numinterfaces = argc - optind; random_eui64(my_router_id); myseqno = rand() & 0xFFFF; sock = babel_socket(babel_port); if(sock < 0) { perror("babel_socket"); exit(1); } for(i = 0; i < numinterfaces; i++) { rc = join_group(sock, interfaces[i].ifindex, &babel_group); if(rc < 0) { perror("setsockopt(IPV6_JOIN_GROUP)"); exit(1); } } catch_signals(sigexit); while(!exiting) { struct sockaddr_in6 sin6; unsigned char buf[BUF_SIZE]; struct timeval tv, update, zerotv = {0, 0}; fd_set readfds; int hello_count = 0; /* Compute when to wake up. */ gettime(&now); timeval_add_msec(&tv, &last_hello, hello_interval * 700 + rand() % 300); timeval_add_msec(&update, &last_update, update_interval * 700 + rand() % 300); timeval_min(&tv, &update); if(selected_nexthop_metric < INFINITY) { int n = find_neighbour(selected_interface, &selected_nexthop, 0); assert(n >= 0); timeval_min(&tv, &neighbours[n].timeout); timeval_min(&tv, &selected_nexthop_timeout); } if(timeval_compare(&tv, &now) > 0) timeval_minus(&tv, &tv, &now); else tv = zerotv; FD_ZERO(&readfds); FD_SET(sock, &readfds); rc = select(sock + 1, &readfds, NULL, NULL, &tv); if(rc < 0 && errno != EINTR) { perror("select"); nap(1000); continue; } if(rc > 0) { /* Oh good, a packet. */ socklen_t sin6len = sizeof(sin6); rc = recvfrom(sock, buf, BUF_SIZE, 0, (struct sockaddr*)&sin6, &sin6len); if(rc < 0 || rc >= BUF_SIZE) { if(rc < 0 && errno != EAGAIN) { perror("recv"); nap(100); } continue; } if(sin6.sin6_family != PF_INET6) { fprintf(stderr, "Received unexpected packet in family %d.\n", sin6.sin6_family); nap(100); continue; } i = find_interface(sin6.sin6_scope_id); if(i < 0) { fprintf(stderr, "Received packet on unknown interface %d.\n", sin6.sin6_scope_id); nap(100); continue; } handle_packet(sock, buf, rc, &interfaces[i], &sin6.sin6_addr); } gettime(&now); if(selected_nexthop_metric < INFINITY) { int n = find_neighbour(selected_interface, &selected_nexthop, 0); assert(n >= 0); if(neighbour_expired(n, &now)) { /* Expire neighbour. */ flush_default_route(); delete_neighbour(n); } else if(timeval_compare(&now, &selected_nexthop_timeout) > 0) { /* Expire route. */ flush_default_route(); } /* Send a request? */ } /* Is it time to send hellos? */ if(timeval_minus_msec(&now, &last_hello) > hello_interval * 700) { for(i = 0; i < numinterfaces; i++) send_hello(sock, &interfaces[i]); last_hello = now; hello_count++; /* Make an expiry pass every ten hellos. */ if(hello_count >= 10) { expire_neighbours(); hello_count = 0; } } /* Is it time to send an update? */ if(timeval_minus_msec(&now, &last_update) > update_interval * 700) { for(i = 0; i < numinterfaces; i++) send_update(sock, &interfaces[i], 0); last_update = now; } } /* Send a bunch of retractions. */ for(i = 0; i < numinterfaces; i++) send_update(sock, &interfaces[i], 1); flush_default_route(); return 0; usage: fprintf(stderr, "Usage: sbabeld " "[-p prefix] [-u interval] [-h interval] [-c cost] interface...\n"); return 1; }