code:
diff -up dhcp-4.2.0/client/dhclient.c.ifup dhcp-4.2.0/client/dhclient.c
--- dhcp-4.2.0/client/dhclient.c.ifup	2010-07-21 13:30:10.000000000 +0200
+++ dhcp-4.2.0/client/dhclient.c	2010-07-21 13:37:03.000000000 +0200
@@ -497,9 +497,81 @@ main(int argc, char **argv) {
 					kill(oldpid, SIGTERM);
 			}
 			fclose(pidfd);
+		} else {
+			/* handle release for interfaces requested with Red Hat
+			 * /sbin/ifup - pidfile will be /var/run/dhclient-$interface.pid
+			 */
+
+			if ((path_dhclient_pid == NULL) || (*path_dhclient_pid == '\0'))
+				path_dhclient_pid = "/var/run/dhclient.pid";
+
+			char *new_path_dhclient_pid;
+			struct interface_info *ip;
+			int pdp_len = strlen(path_dhclient_pid), pfx, dpfx;
+
+			/* find append point: beginning of any trailing '.pid'
+			 * or '-$IF.pid' */
+			for (pfx=pdp_len; (pfx >= 0) && (path_dhclient_pid[pfx] != '.') && (path_dhclient_pid[pfx] != '/'); pfx--);
+				if (pfx == -1)
+					pfx = pdp_len;
+
+			if (path_dhclient_pid[pfx] == '/')
+				pfx += 1;
+
+			for (dpfx=pfx; (dpfx >= 0) && (path_dhclient_pid[dpfx] != '-') && (path_dhclient_pid[dpfx] != '/'); dpfx--);
+				if ((dpfx > -1) && (path_dhclient_pid[dpfx] != '/'))
+					pfx = dpfx;
+
+			for (ip = interfaces; ip; ip = ip->next) {
+				if (interfaces_requested && (ip->flags & (INTERFACE_REQUESTED)) && (ip->name != NULL)) {
+					int n_len = strlen(ip->name);
+
+					new_path_dhclient_pid = (char*) malloc(pfx + n_len + 6);
+					strncpy(new_path_dhclient_pid, path_dhclient_pid, pfx);
+					sprintf(new_path_dhclient_pid + pfx, "-%s.pid", ip->name);
+
+					if ((pidfd = fopen(new_path_dhclient_pid, "r")) != NULL) {
+						e = fscanf(pidfd, "%ld\n", &temp);
+						oldpid = (pid_t)temp;
+
+						if (e != 0 && e != EOF) {
+							if (oldpid) {
+								if (kill(oldpid, SIGTERM) == 0)
+									unlink(path_dhclient_pid);
+							}
+						}
+
+						fclose(pidfd);
+					}
+
+					free(new_path_dhclient_pid);
+				}
+			}
+		}
+	} else {
+		FILE *pidfp = NULL;
+		long temp = 0;
+		pid_t dhcpid = 0;
+		int dhc_running = 0;
+		char procfn[256] = "";
+
+		if ((pidfp = fopen(path_dhclient_pid, "r")) != NULL) {
+			if ((fscanf(pidfp, "%ld", &temp)==1) && ((dhcpid=(pid_t)temp) > 0)) {
+				snprintf(procfn,256,"/proc/%u",dhcpid);
+				dhc_running = (access(procfn, F_OK) == 0);
+			}
+
+			fclose(pidfp);
+		}
+
+		if (dhc_running) {
+			log_fatal("dhclient(%u) is already running - exiting. ", dhcpid);
+			return(1);
 		}
 	}

+	write_client_pid_file();
+
 	if (!quiet) {
 		log_info("%s %s", message, PACKAGE_VERSION);
 		log_info(copyright);


code:
diff -up dhcp-4.2.0/client/dhc6.c.sendDecline dhcp-4.2.0/client/dhc6.c
--- dhcp-4.2.0/client/dhc6.c.sendDecline	2009-11-20 02:48:58.000000000 +0100
+++ dhcp-4.2.0/client/dhc6.c	2010-07-21 16:18:51.000000000 +0200
@@ -95,6 +95,8 @@ void do_select6(void *input);
 void do_refresh6(void *input);
 static void do_release6(void *input);
 static void start_bound(struct client_state *client);
+static void start_decline6(struct client_state *client);
+static void do_decline6(void *input);
 static void start_informed(struct client_state *client);
 void informed_handler(struct packet *packet, struct client_state *client);
 void bound_handler(struct packet *packet, struct client_state *client);
@@ -2140,6 +2142,7 @@ start_release6(struct client_state *clie
 	cancel_timeout(do_select6, client);
 	cancel_timeout(do_refresh6, client);
 	cancel_timeout(do_release6, client);
+	cancel_timeout(do_decline6, client);
 	client->state = S_STOPPED;

 	/*
@@ -2790,6 +2793,7 @@ dhc6_check_reply(struct client_state *cl
 		break;

 	      case S_STOPPED:
+	      case S_DECLINED:
 		action = dhc6_stop_action;
 		break;

@@ -2891,6 +2895,7 @@ dhc6_check_reply(struct client_state *cl
 		break;

 	      case S_STOPPED:
+	      case S_DECLINED:
 		/* Nothing critical to do at this stage. */
 		break;

@@ -3933,17 +3938,23 @@ reply_handler(struct packet *packet, str
 	cancel_timeout(do_select6, client);
 	cancel_timeout(do_refresh6, client);
 	cancel_timeout(do_release6, client);
+	cancel_timeout(do_decline6, client);

 	/* If this is in response to a Release/Decline, clean up and return. */
-	if (client->state == S_STOPPED) {
-		if (client->active_lease == NULL)
-			return;
+	if ((client->state == S_STOPPED) ||
+	    (client->state == S_DECLINED)) {
+
+		if (client->active_lease != NULL) {
+			dhc6_lease_destroy(&client->active_lease, MDL);
+			client->active_lease = NULL;
+			/* We should never wait for nothing!? */
+			if (stopping_finished())
+				exit(0);
+		}
+
+		if (client->state == S_DECLINED)
+			start_init6(client);

-		dhc6_lease_destroy(&client->active_lease, MDL);
-		client->active_lease = NULL;
-		/* We should never wait for nothing!? */
-		if (stopping_finished())
-			exit(0);
 		return;
 	}

@@ -4470,7 +4481,11 @@ start_bound(struct client_state *client)
 						     oldia, oldaddr);
 			dhc6_marshall_values("new_", client, lease, ia, addr);

-			script_go(client);
+			// when script returns 3, DAD failed
+			if (script_go(client) == 3) {
+				start_decline6(client);
+				return;
+			}
 		}

 		/* XXX: maybe we should loop on the old values instead? */
@@ -4516,6 +4531,151 @@ start_bound(struct client_state *client)
 	dhc6_check_times(client);
 }

+/*
+ * Decline addresses.
+ */
+void
+start_decline6(struct client_state *client)
+{
+	/* Cancel any pending transmissions */
+	cancel_timeout(do_confirm6, client);
+	cancel_timeout(do_select6, client);
+	cancel_timeout(do_refresh6, client);
+	cancel_timeout(do_release6, client);
+	cancel_timeout(do_decline6, client);
+	client->state = S_DECLINED;
+
+	if (client->active_lease == NULL)
+		return;
+
+	/* Set timers per RFC3315 section 18.1.7. */
+	client->IRT = DEC_TIMEOUT * 100;
+	client->MRT = 0;
+	client->MRC = DEC_MAX_RC;
+	client->MRD = 0;
+
+	dhc6_retrans_init(client);
+	client->v6_handler = reply_handler;
+
+	client->refresh_type = DHCPV6_DECLINE;
+	do_decline6(client);
+}
+
+/*
+ * do_decline6() creates a Decline packet and transmits it.
+ */
+static void
+do_decline6(void *input)
+{
+	struct client_state *client;
+	struct data_string ds;
+	int send_ret;
+	struct timeval elapsed, tv;
+
+	client = input;
+
+	if ((client->active_lease == NULL) || !active_prefix(client))
+		return;
+
+	if ((client->MRC != 0) && (client->txcount > client->MRC))  {
+		log_info("Max retransmission count exceeded.");
+		goto decline_done;
+	}
+
+	/*
+	 * Start_time starts at the first transmission.
+	 */
+	if (client->txcount == 0) {
+		client->start_time.tv_sec = cur_tv.tv_sec;
+		client->start_time.tv_usec = cur_tv.tv_usec;
+	}
+
+	/* elapsed = cur - start */
+	elapsed.tv_sec = cur_tv.tv_sec - client->start_time.tv_sec;
+	elapsed.tv_usec = cur_tv.tv_usec - client->start_time.tv_usec;
+	if (elapsed.tv_usec < 0) {
+		elapsed.tv_sec -= 1;
+		elapsed.tv_usec += 1000000;
+	}
+
+	memset(&ds, 0, sizeof(ds));
+	if (!buffer_allocate(&ds.buffer, 4, MDL)) {
+		log_error("Unable to allocate memory for Decline.");
+		goto decline_done;
+	}
+
+	ds.data = ds.buffer->data;
+	ds.len = 4;
+	ds.buffer->data[0] = DHCPV6_DECLINE;
+	memcpy(ds.buffer->data + 1, client->dhcpv6_transaction_id, 3);
+
+	/* Form an elapsed option. */
+	/* Maximum value is 65535 1/100s coded as 0xffff. */
+	if ((elapsed.tv_sec < 0) || (elapsed.tv_sec > 655) ||
+	    ((elapsed.tv_sec == 655) && (elapsed.tv_usec > 350000))) {
+		client->elapsed = 0xffff;
+	} else {
+		client->elapsed = elapsed.tv_sec * 100;
+		client->elapsed += elapsed.tv_usec / 10000;
+	}
+
+	client->elapsed = htons(client->elapsed);
+
+	log_debug("XMT: Forming Decline.");
+	make_client6_options(client, &client->sent_options,
+			     client->active_lease, DHCPV6_DECLINE);
+	dhcpv6_universe.encapsulate(&ds, NULL, NULL, client, NULL,
+				    client->sent_options, &global_scope,
+				    &dhcpv6_universe);
+
+	/* Append IA's (but don't release temporary addresses). */
+	if (wanted_ia_na &&
+	    dhc6_add_ia_na(client, &ds, client->active_lease,
+			   DHCPV6_DECLINE) != ISC_R_SUCCESS) {
+		data_string_forget(&ds, MDL);
+		goto decline_done;
+	}
+	if (wanted_ia_pd &&
+	    dhc6_add_ia_pd(client, &ds, client->active_lease,
+			   DHCPV6_DECLINE) != ISC_R_SUCCESS) {
+		data_string_forget(&ds, MDL);
+		goto decline_done;
+	}
+
+	/* Transmit and wait. */
+	log_info("XMT: Decline on %s, interval %ld0ms.",
+		 client->name ? client->name : client->interface->name,
+		 (long int)client->RT);
+
+	send_ret = send_packet6(client->interface, ds.data, ds.len,
+				&DHCPv6DestAddr);
+	if (send_ret != ds.len) {
+		log_error("dhc6: sendpacket6() sent %d of %d bytes",
+			  send_ret, ds.len);
+	}
+
+	data_string_forget(&ds, MDL);
+
+	/* Wait RT */
+	tv.tv_sec = cur_tv.tv_sec + client->RT / 100;
+	tv.tv_usec = cur_tv.tv_usec + (client->RT % 100) * 10000;
+	if (tv.tv_usec >= 1000000) {
+		tv.tv_sec += 1;
+		tv.tv_usec -= 1000000;
+	}
+	add_timeout(&tv, do_decline6, client, NULL, NULL);
+	dhc6_retrans_advance(client);
+	return;
+
+decline_done:
+	if (client->active_lease != NULL) {
+		dhc6_lease_destroy(&client->active_lease, MDL);
+		client->active_lease = NULL;
+	}
+	start_init6(client);
+	return;
+}
+
 /* While bound, ignore packets.  In the future we'll want to answer
  * Reconfigure-Request messages and the like.
  */

repo_name: ayhanyalcinsoy/main


code:
diff -up dhcp-4.2.0/server/bootp.c.unicast dhcp-4.2.0/server/bootp.c
--- dhcp-4.2.0/server/bootp.c.unicast	2009-11-20 02:49:03.000000000 +0100
+++ dhcp-4.2.0/server/bootp.c	2010-07-21 13:40:25.000000000 +0200
@@ -58,6 +58,7 @@ void bootp (packet)
 	char msgbuf [1024];
 	int ignorep;
 	int peer_has_leases = 0;
+	int norelay = 0;

 	if (packet -> raw -> op != BOOTREQUEST)
 		return;
@@ -73,7 +74,7 @@ void bootp (packet)
 		 ? inet_ntoa (packet -> raw -> giaddr)
 		 : packet -> interface -> name);

-	if (!locate_network (packet)) {
+	if ((norelay = locate_network (packet)) == 0) {
 		log_info ("%s: network unknown", msgbuf);
 		return;
 	}
@@ -390,6 +391,13 @@ void bootp (packet)
 					      from, &to, &hto);
 			goto out;
 		}
+	} else if (norelay == 2) {
+		to.sin_addr = raw.ciaddr;
+		to.sin_port = remote_port;
+		if (fallback_interface) {
+			result = send_packet (fallback_interface, (struct packet *)0, &raw, outgoing.packet_length, from, &to, &hto);
+			goto out;
+		}

 	/* If it comes from a client that already knows its address
 	   and is not requesting a broadcast response, and we can
diff -up dhcp-4.2.0/server/dhcp.c.unicast dhcp-4.2.0/server/dhcp.c
--- dhcp-4.2.0/server/dhcp.c.unicast	2010-06-01 19:29:59.000000000 +0200
+++ dhcp-4.2.0/server/dhcp.c	2010-07-21 13:40:25.000000000 +0200
@@ -4185,6 +4185,7 @@ int locate_network (packet)
 	struct data_string data;
 	struct subnet *subnet = (struct subnet *)0;
 	struct option_cache *oc;
+	int norelay = 0;

 	/* See if there's a Relay Agent Link Selection Option, or a
 	 * Subnet Selection Option.  The Link-Select and Subnet-Select
@@ -4200,12 +4201,24 @@ int locate_network (packet)
 	   from the interface, if there is one.   If not, fail. */
 	if (!oc && !packet -> raw -> giaddr.s_addr) {
 		if (packet -> interface -> shared_network) {
-			shared_network_reference
-				(&packet -> shared_network,
-				 packet -> interface -> shared_network, MDL);
-			return 1;
+			struct in_addr any_addr;
+			any_addr.s_addr = INADDR_ANY;
+
+			if (!packet -> packet_type && memcmp(&packet -> raw -> ciaddr, &any_addr, 4)) {
+				struct iaddr cip;
+				memcpy(cip.iabuf, &packet -> raw -> ciaddr, 4);
+				cip.len = 4;
+				if (!find_grouped_subnet(&subnet, packet->interface->shared_network, cip, MDL))
+					norelay = 2;
+			}
+
+			if (!norelay) {
+				shared_network_reference(&packet -> shared_network, packet -> interface -> shared_network, MDL);
+				return 1;
+			}
+		} else {
+			return 0;
 		}
-		return 0;
 	}

 	/* If there's an option indicating link connection, and it's valid,
@@ -4228,7 +4241,10 @@ int locate_network (packet)
 		data_string_forget (&data, MDL);
 	} else {
 		ia.len = 4;
-		memcpy (ia.iabuf, &packet -> raw -> giaddr, 4);
+		if (norelay)
+			memcpy (ia.iabuf, &packet->raw->ciaddr, 4);
+		else
+			memcpy (ia.iabuf, &packet->raw->giaddr, 4);
 	}

 	/* If we know the subnet on which the IP address lives, use it. */
@@ -4236,7 +4252,10 @@ int locate_network (packet)
 		shared_network_reference (&packet -> shared_network,
 					  subnet -> shared_network, MDL);
 		subnet_dereference (&subnet, MDL);
-		return 1;
+		if (norelay)
+			return norelay;
+		else
+			return 1;
 	}

 	/* Otherwise, fail. */


code:
diff -up dhcp-4.2.1b1/client/dhc6.c.retransmission dhcp-4.2.1b1/client/dhc6.c
--- dhcp-4.2.1b1/client/dhc6.c.retransmission	2011-01-28 08:40:56.000000000 +0100
+++ dhcp-4.2.1b1/client/dhc6.c	2011-01-28 08:39:22.000000000 +0100
@@ -361,7 +361,7 @@ dhc6_retrans_init(struct client_state *c
 static void
 dhc6_retrans_advance(struct client_state *client)
 {
-	struct timeval elapsed;
+	struct timeval elapsed, elapsed_after_RT;

 	/* elapsed = cur - start */
 	elapsed.tv_sec = cur_tv.tv_sec - client->start_time.tv_sec;
@@ -378,6 +378,8 @@ dhc6_retrans_advance(struct client_state
 		elapsed.tv_sec += 1;
 		elapsed.tv_usec -= 1000000;
 	}
+	elapsed_after_RT.tv_sec = elapsed.tv_sec;
+	elapsed_after_RT.tv_usec = elapsed.tv_usec;

 	/*
 	 * RT for each subsequent message transmission is based on the previous
@@ -415,13 +417,10 @@ dhc6_retrans_advance(struct client_state
 		elapsed.tv_usec -= 1000000;
 	}
 	if (elapsed.tv_sec >= client->MRD) {
-		/*
-		 * wake at RT + cur = start + MRD
-		 */
-		client->RT = client->MRD +
-			(client->start_time.tv_sec - cur_tv.tv_sec);
-		client->RT = client->RT * 100 +
-			(client->start_time.tv_usec - cur_tv.tv_usec) / 10000;
+		client->RT = client->MRD - elapsed_after_RT.tv_sec;
+		client->RT = client->RT * 100 - elapsed_after_RT.tv_usec / 10000;
+		if (client->RT < 0)
+			client->RT = 0;
 	}
 	client->txcount++;
 }
@@ -1497,7 +1496,7 @@ check_timing6 (struct client_state *clie
 	}

 	/* Check if finished (-1 argument). */
-	if ((client->MRD != 0) && (elapsed.tv_sec > client->MRD)) {
+	if ((client->MRD != 0) && (elapsed.tv_sec >= client->MRD)) {
 		log_info("Max retransmission duration exceeded.");
 		return(CHK_TIM_MRD_EXCEEDED);
 	}


code:
diff -up dhcp-4.3.0a1/client/dhc6.c.PPP dhcp-4.3.0a1/client/dhc6.c
--- dhcp-4.3.0a1/client/dhc6.c.PPP	2013-12-19 16:16:45.925550229 +0100
+++ dhcp-4.3.0a1/client/dhc6.c	2013-12-19 16:16:45.930550159 +0100
@@ -5080,7 +5080,8 @@ make_client6_options(struct client_state
 	 */
 	if ((oc = lookup_option(&dhcpv6_universe, *op,
 				D6O_CLIENTID)) == NULL) {
-		if (!option_cache(&oc, &default_duid, NULL, clientid_option,
+		if (default_duid.len == 0 ||
+		    !option_cache(&oc, &default_duid, NULL, clientid_option,
 				  MDL))
 			log_fatal("Failure assembling a DUID.");

diff -up dhcp-4.3.0a1/client/dhclient.c.PPP dhcp-4.3.0a1/client/dhclient.c
--- dhcp-4.3.0a1/client/dhclient.c.PPP	2013-12-19 16:16:45.932550131 +0100
+++ dhcp-4.3.0a1/client/dhclient.c	2013-12-19 16:27:38.334473958 +0100
@@ -926,8 +926,8 @@ main(int argc, char **argv) {
 			if (default_duid.buffer != NULL)
 				data_string_forget(&default_duid, MDL);

-			form_duid(&default_duid, MDL);
-			write_duid(&default_duid);
+			if (form_duid(&default_duid, MDL) == ISC_R_SUCCESS)
+				write_duid(&default_duid);
 		}
 	}

@@ -3225,7 +3225,7 @@ write_options(struct client_state *clien
  * is not how it is intended.  Upcoming rearchitecting the client should
  * address this "one daemon model."
  */
-void
+isc_result_t
 form_duid(struct data_string *duid, const char *file, int line)
 {
 	struct interface_info *ip;
@@ -3237,6 +3237,15 @@ form_duid(struct data_string *duid, cons
 	if (ip == NULL)
 		log_fatal("Impossible condition at %s:%d.", MDL);

+	while (ip && ip->hw_address.hbuf[0] == HTYPE_RESERVED) {
+		/* Try the other interfaces */
+		log_debug("Cannot form default DUID from interface %s.", ip->name);
+		ip = ip->next;
+	}
+	if (ip == NULL) {
+		return ISC_R_UNEXPECTED;
+	}
+
 	if ((ip->hw_address.hlen == 0) ||
 	    (ip->hw_address.hlen > sizeof(ip->hw_address.hbuf)))
 		log_fatal("Impossible hardware address length at %s:%d.", MDL);
@@ -3272,6 +3281,8 @@ form_duid(struct data_string *duid, cons
 		memcpy(duid->buffer->data + 4, ip->hw_address.hbuf + 1,
 		       ip->hw_address.hlen - 1);
 	}
+
+	return ISC_R_SUCCESS;
 }

 /* Write the default DUID to the lease store. */
diff -up dhcp-4.3.0a1/common/bpf.c.PPP dhcp-4.3.0a1/common/bpf.c
--- dhcp-4.3.0a1/common/bpf.c.PPP	2013-12-19 16:16:45.868551024 +0100
+++ dhcp-4.3.0a1/common/bpf.c	2013-12-19 16:16:45.934550103 +0100
@@ -602,6 +602,22 @@ get_hw_addr(const char *name, struct har
                         memcpy(&hw->hbuf[1], LLADDR(sa), sa->sdl_alen);
                         break;
 #endif /* IFT_FDDI */
+#if defined(IFT_PPP)
+                case IFT_PPP:
+                        if (local_family != AF_INET6)
+                             log_fatal("Unsupported device type %d for \"%s\"",
+                                        sa->sdl_type, name);
+                        hw->hlen = 0;
+                        hw->hbuf[0] = HTYPE_RESERVED;
+                        /* 0xdeadbeef should never occur on the wire,
+                         *  and is a signature that something went wrong.
+                         */
+                        hw->hbuf[1] = 0xde;
+                        hw->hbuf[2] = 0xad;
+                        hw->hbuf[3] = 0xbe;
+                        hw->hbuf[4] = 0xef;
+                        break;
+#endif
                 default:
                         log_fatal("Unsupported device type %d for \"%s\"",
                                   sa->sdl_type, name);
diff -up dhcp-4.3.0a1/common/lpf.c.PPP dhcp-4.3.0a1/common/lpf.c
--- dhcp-4.3.0a1/common/lpf.c.PPP	2013-12-19 16:16:45.848551303 +0100
+++ dhcp-4.3.0a1/common/lpf.c	2013-12-19 16:16:45.934550103 +0100
@@ -511,6 +511,22 @@ get_hw_addr(const char *name, struct har
 			hw->hbuf[0] = HTYPE_FDDI;
 			memcpy(&hw->hbuf[1], sa->sa_data, 6);
 			break;
+#if defined(ARPHRD_PPP)
+		case ARPHRD_PPP:
+			if (local_family != AF_INET6)
+				log_fatal("Unsupported device type %d for \"%s\"",
+				           sa->sa_family, name);
+			hw->hlen = 0;
+			hw->hbuf[0] = HTYPE_RESERVED;
+			/* 0xdeadbeef should never occur on the wire,
+			 * and is a signature that something went wrong.
+			 */
+			hw->hbuf[1] = 0xde;
+			hw->hbuf[2] = 0xad;
+			hw->hbuf[3] = 0xbe;
+			hw->hbuf[4] = 0xef;
+			break;
+#endif
 		default:
 			log_fatal("Unsupported device type %ld for \"%s\"",
 				  (long int)sa->sa_family, name);
diff -up dhcp-4.3.0a1/includes/dhcp.h.PPP dhcp-4.3.0a1/includes/dhcp.h
--- dhcp-4.3.0a1/includes/dhcp.h.PPP	2013-12-19 16:16:45.919550313 +0100
+++ dhcp-4.3.0a1/includes/dhcp.h	2013-12-19 16:16:45.936550076 +0100
@@ -85,6 +85,8 @@ struct dhcp_packet {
 					 * is no standard for this so we
 					 * just steal a type            */

+#define HTYPE_RESERVED	0		/* RFC 5494 */
+
 /* Magic cookie validating dhcp options field (and bootp vendor
    extensions field). */
 #define DHCP_OPTIONS_COOKIE	"\143\202\123\143"
diff -up dhcp-4.3.0a1/includes/dhcpd.h.PPP dhcp-4.3.0a1/includes/dhcpd.h
--- dhcp-4.3.0a1/includes/dhcpd.h.PPP	2013-12-19 16:16:45.935550090 +0100
+++ dhcp-4.3.0a1/includes/dhcpd.h	2013-12-19 16:28:33.468709007 +0100
@@ -2824,7 +2824,7 @@ void client_dns_remove(struct client_sta

 void dhcpv4_client_assignments(void);
 void dhcpv6_client_assignments(void);
-void form_duid(struct data_string *duid, const char *file, int line);
+isc_result_t form_duid(struct data_string *duid, const char *file, int line);

 /* dhc6.c */
 void dhc6_lease_destroy(struct dhc6_lease **src, const char *file, int line);
diff -up dhcp-4.3.0a1/server/dhcpv6.c.PPP dhcp-4.3.0a1/server/dhcpv6.c
--- dhcp-4.3.0a1/server/dhcpv6.c.PPP	2013-12-19 16:16:45.901550564 +0100
+++ dhcp-4.3.0a1/server/dhcpv6.c	2013-12-19 16:16:45.937550062 +0100
@@ -307,6 +307,9 @@ generate_new_server_duid(void) {
 		if (p->hw_address.hlen > 0) {
 			break;
 		}
+		if (p->next == NULL && p->hw_address.hbuf[0] == HTYPE_RESERVED) {
+			log_error("Can not generate DUID from interfaces which do not have hardware addresses, please configure server-duid!");
+		}
 	}
 	if (p == NULL) {
 		return ISC_R_UNEXPECTED;


code:
diff -up dhcp-4.3.0a1/omapip/errwarn.c.errwarn dhcp-4.3.0a1/omapip/errwarn.c
--- dhcp-4.3.0a1/omapip/errwarn.c.errwarn	2012-07-11 22:46:29.000000000 +0200
+++ dhcp-4.3.0a1/omapip/errwarn.c	2013-12-19 15:09:17.857125042 +0100
@@ -76,20 +76,13 @@ void log_fatal (const char * fmt, ... )

 #if !defined (NOMINUM)
   log_error ("%s", "");
-  log_error ("If you did not get this software from ftp.isc.org, please");
-  log_error ("get the latest from ftp.isc.org and install that before");
-  log_error ("requesting help.");
+  log_error ("This version of ISC DHCP is based on the release available");
+  log_error ("on ftp.isc.org.  Features have been added and other changes");
+  log_error ("have been made to the base software release in order to make");
+  log_error ("it work better with this distribution.");
   log_error ("%s", "");
-  log_error ("If you did get this software from ftp.isc.org and have not");
-  log_error ("yet read the README, please read it before requesting help.");
-  log_error ("If you intend to request help from the dhcp-server@isc.org");
-  log_error ("mailing list, please read the section on the README about");
-  log_error ("submitting bug reports and requests for help.");
-  log_error ("%s", "");
-  log_error ("Please do not under any circumstances send requests for");
-  log_error ("help directly to the authors of this software - please");
-  log_error ("send them to the appropriate mailing list as described in");
-  log_error ("the README file.");
+  log_error ("Please report for this software via the Red Hat Bugzilla site:");
+  log_error ("    http://bugzilla.redhat.com");
   log_error ("%s", "");
   log_error ("exiting.");
 #endif


code:
# DHCP Server Configuration file for Pisi Linux

# Specify a configuration file - the default is /etc/dhcp/dhcpd.conf
DHCPD_CONF="/etc/dhcp/dhcpd.conf"

# Configure which interface or interfaces to for dhcpd to listen on.
# List all interfaces space separated. If this is not specified then
# we listen on all interfaces.
INTERFACES=""

# Insert any other dhcpd options - see the man page for a full list.
DHCPD_ARGS=""

# Wait for interfaces being up (in seconds.)
TIMEOUT=10

path: server/dhcp/files/dhcpd


code:
# DHCP Server Configuration file.
#   see /usr/share/doc/dhcp/dhcpd.conf.sample
#   see 'man 5 dhcpd.conf'
#
#############################################
# ddns-update-style               none;
#
# default-lease-time              21600;
# max-lease-time                  21600;
#
# option subnet-mask              255.255.255.0;
# option broadcast-address        10.0.0.255;
# option routers                  10.0.0.1;
# option domain-name-servers      10.0.0.1;
# option domain-name              "pisilinux";
#
# next-server                     10.0.0.1;
# get-lease-hostnames             on;
#
# option root-path	      "10.0.0.1:/opt/ptsp";
#
# subnet 10.0.0.0 netmask 255.255.255.0 {
#     range 10.0.0.1  10.0.0.99;

      #Send this file for pxe file requests
      #filename "/pts/latest-ptsp/pxelinux.0";
# }
# host AccessPoint {
#    hardware ethernet XX:XX:XX:XX:XX:XX;
#    fixed-address 10.0.0.120;
#}


code:
# DHCPv6 Server Configuration file for Pisi Linux

# Specify a configuration file - the default is /etc/dhcp/dhcpd.conf
DHCPD_CONF="/etc/dhcp/dhcpd.conf"

# Configure which interface or interfaces to for dhcpd to listen on.
# List all interfaces space separated. If this is not specified then
# we listen on all interfaces.
INTERFACES=""

# Insert any other dhcpd options - see the man page for a full list.
DHCPD_ARGS=""

# Wait for interfaces being up (in seconds.)
TIMEOUT=10


code:
# DHCP for IPv6  Server Configuration file.
#   see /usr/share/doc/dhcp/dhcpd6.conf.sample
#   see 'man 5 dhcpd.conf'
#   run 'service dhcpd6 start' or 'dhcpd -6 -cf /etc/dhcp/dhcpd6.conf'
#
#############################################
# ddns-update-style               none;
#
# default-lease-time              21600;
# max-lease-time                  21600;
#
# option subnet-mask              255.255.255.0;
# option broadcast-address        10.0.0.255;
# option routers                  10.0.0.1;
# option domain-name-servers      10.0.0.1;
# option domain-name              "pisilinux";
#
# next-server                     10.0.0.1;
# get-lease-hostnames             on;
#
# option root-path	      "10.0.0.1:/opt/ptsp";
#
# subnet 10.0.0.0 netmask 255.255.255.0 {
#     range 10.0.0.1  10.0.0.99;

      #Send this file for pxe file requests
      #filename "/pts/latest-ptsp/pxelinux.0";
# }
# host AccessPoint {
#    hardware ethernet XX:XX:XX:XX:XX:XX;
#    fixed-address 10.0.0.120;
#}


code:
# DHCP Relay Server Configuration file for Pisi Linux

# Configure which interface or interfaces to for dhcpd to listen on.
# List all interfaces space separated. If this is not specified then
# we listen on all interfaces.
#
# DHCPv4 only
INTERFACES=""

#DHCPv4 only
DHCP_SERVERS=""

# Insert any other dhcpd options - see the man page for a full list.
DHCRELAY_ARGS=""

path: server/dhcp/files/dhcrelay


code:
<?xml version="1.0" ?>
<!DOCTYPE PISI SYSTEM "http://www.pisilinux.org/projeler/pisi/pisi-spec.dtd">
<PISI>
    <Source>
        <Name>dhcp</Name>
        <Homepage>http://www.isc.org/products/DHCP</Homepage>
        <Packager>
            <Name>PisiLinux Community</Name>
            <Email>admins@pisilinux.org</Email>
        </Packager>
        <License>isc-dhcp</License>
        <IsA>app:console</IsA>
        <IsA>library</IsA>
        <IsA>service</IsA>
        Dynamic host configuration protocol software
        <Description>DHCP (Dynamic Host Configuration Protocol) is a protocol which allows individual devices on an IP network to get their own network configuration information (IP address, subnetmask, broadcast address, etc.) from a DHCP server.</Description>
        <Archive sha1sum="fb0417530e49368fe032cd9722f51c74f93180ac" type="targz">http://ftp.isc.org/isc/dhcp/4.3.6/dhcp-4.3.6.tar.gz</Archive>
        <BuildDependencies>
            <Dependency>groff</Dependency>
            <Dependency>openldap-client</Dependency>

        </BuildDependencies>
        <Patches>
            <Patch level="1">0001-dhcp-honor-expired.patch</Patch>
        </Patches>
    </Source>

    <Package>
        <Name>dhcp</Name>
        <RuntimeDependencies>
            <Dependency>openldap-client</Dependency>

        </RuntimeDependencies>
        <Files>
            <Path fileType="config">/etc</Path>
            <Path fileType="executable">/usr/bin</Path>
            <Path fileType="executable">/usr/sbin</Path>
            <Path fileType="library">/usr/lib</Path>
            <Path fileType="data">/var/lib</Path>
            <Path fileType="data">/run</Path>
            <Path fileType="man">/usr/share/man</Path>
            <Path fileType="doc">/usr/share/doc</Path>
        </Files>
        <AdditionalFiles>
            <AdditionalFile owner="root" permission="0644" target="/etc/conf.d/dhcpd">dhcpd</AdditionalFile>
            <AdditionalFile owner="root" permission="0644" target="/etc/conf.d/dhcpd6">dhcpd6</AdditionalFile>
            <AdditionalFile owner="root" permission="0644" target="/etc/conf.d/dhcrelay">dhcrelay</AdditionalFile>
            <AdditionalFile owner="root" permission="0644" target="/etc/dhcp/dhcpd.conf">dhcpd.conf</AdditionalFile>

        </AdditionalFiles>
        <Provides>
            <COMAR script="dhcpd.py" name="dhcpd">System.Service</COMAR>
            <COMAR script="dhcpd6.py" name="dhcpd6">System.Service</COMAR>
            <COMAR script="dhcrelay.py" name="dhcrelay">System.Service</COMAR>
            <COMAR script="package.py">System.Package</COMAR>
        </Provides>
    </Package>

    <Package>
        <Name>dhclient</Name>
        <IsA>app:console</IsA>
        <PartOf>network.connection</PartOf>
        Provides the dhclient ISC DHCP client daemon
        <RuntimeDependencies>

        </RuntimeDependencies>
        <Files>

            <Path fileType="config">/etc/dhcp/dhclient.conf</Path>
            <Path fileType="executable">/usr/sbin/dhclient</Path>

            <Path fileType="data">/var/lib/dhclient</Path>
            <Path fileType="man">/usr/share/man/man5/dhclient*</Path>
            <Path fileType="man">/usr/share/man/man8/dhclient*</Path>
            <Path fileType="man">/usr/share/man/man5/dhcp-options*</Path>
            <Path fileType="man">/usr/share/man/man5/dhcp-eval*</Path>
            <Path fileType="doc">/usr/share/doc/dhcp/dhclient*</Path>
        </Files>
        <AdditionalFiles>
            <AdditionalFile owner="root" permission="0644" target="/etc/dhcp/dhclient.conf">dhclient.conf</AdditionalFile>

        </AdditionalFiles>
    </Package>

    <Package>
        <Name>dhcp-devel</Name>
        Development files for dhcp
        <RuntimeDependencies>
            <Dependency release="current">dhcp</Dependency>
        </RuntimeDependencies>
        <Files>
            <Path fileType="header">/usr/include</Path>
            <Path fileType="man">/usr/share/man/man3</Path>
        </Files>
    </Package>

    <History>
        <Update release="4">
            <Date>2017-10-25</Date>
            <Version>4.3.6</Version>
            <Comment>Version bump,fix #2943</Comment>
            <Name>Ertuğrul Erata</Name>
            <Email>ertugrulerata@gmail.com</Email>
        </Update>
        <Update release="3">
            <Date>2017-05-09</Date>
            <Version>4.3.0</Version>
            <Comment>Release Bump</Comment>
            <Name>Kamil Atlı</Name>
            <Email>admin@pisilinux.org</Email>
        </Update>
        <Update release="2">
            <Date>2016-06-08</Date>
            <Version>4.3.0</Version>
            <Comment>Release Bump</Comment>
            <Name>Pisi Linux Community</Name>
            <Email>admin@pisilinux.org</Email>
        </Update>
        <Update release="1">
            <Date>2014-05-19</Date>
            <Version>4.3.0</Version>
            <Comment>First release</Comment>
            <Name>Vedat Demir</Name>
            <Email>vedat@pisilinux.org</Email>
        </Update>
    </History>
</PISI>


code:
<?xml version="1.0" ?>
<PISI>
    <Source>
        <Name>dhcp</Name>
        DHCP Sunucusu
        <Description xml:lang="tr">IP adresi atanmasını ve TCP/IP bilgilerinin yapılandırılmasını sağlayan DHCP Sunucusu</Description>
        DHCP-Server
    </Source>

    <Package>
        <Name>dhclient</Name>
        DHCP İstemcisi
    </Package>

    <Package>
        <Name>dhcp-devel</Name>
        dhcp için geliştirme dosyaları
    </Package>
</PISI>


code:
<PISI>
    <Name>server.misc</Name>
</PISI>


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/licenses/gpl.txt

from pisi.actionsapi import autotools
from pisi.actionsapi import pisitools
from pisi.actionsapi import get

WorkDir = "LibVNCServer-%s" % get.srcVERSION()

def setup():
    autotools.configure("--disable-static \
                         --disable-dependency-tracking \
                         --with-24bpp \
                         --with-zlib \
                         --with-jpeg")

    pisitools.dosed("libtool", " -shared ", " -shared -Wl,--as-needed")

def build():
    autotools.make()

def install():
    autotools.rawInstall("DESTDIR=%s" % get.installDIR())
    pisitools.remove("/usr/bin/linuxvnc")


code:
<?xml version="1.0" ?>
<!DOCTYPE PISI SYSTEM "http://www.pisilinux.org/projeler/pisi/pisi-spec.dtd">
<PISI>
    <Source>
        <Name>libvncserver</Name>
        <Homepage>http://libvncserver.sourceforge.net/</Homepage>
        <Packager>
            <Name>PisiLinux Community</Name>
            <Email>admins@pisilinux.org</Email>
        </Packager>
        <License>GPLv2</License>
        <IsA>app:console</IsA>
        Library for creating VNC (Virtual Network Computing) servers
        <Description>libvncserver provides a C library to create VNC servers.</Description>
        <Archive sha1sum="2004c6ae493baeff3da40b61e0a0f73c83182dad" type="targz">mirrors://sourceforge/libvncserver/LibVNCServer-0.9.9.tar.gz</Archive>
        <BuildDependencies>
            <Dependency>gnutls-devel</Dependency>
            <Dependency>libjpeg-turbo-devel</Dependency>
            <Dependency>libgcrypt-devel</Dependency>
            <Dependency>libpng-devel</Dependency>
            <Dependency>openssl-devel</Dependency>
        </BuildDependencies>
        <Patches>
        </Patches>
    </Source>

    <Package>
        <Name>libvncserver</Name>
        <RuntimeDependencies>
            <Dependency>zlib</Dependency>
            <Dependency>libpng</Dependency>
            <Dependency>libgcrypt</Dependency>
            <Dependency>gnutls</Dependency>
            <Dependency>libjpeg-turbo</Dependency>
            <Dependency>openssl</Dependency>
        </RuntimeDependencies>
        <Files>
            <Path fileType="executable">/usr/bin/*-config</Path>
            <Path fileType="library">/usr/lib</Path>
        </Files>
    </Package>

    <Package>
        <Name>libvncserver-devel</Name>
        Development files for libvncserver
        <RuntimeDependencies>
            <Dependency release="current">libvncserver</Dependency>
            <Dependency>zlib-devel</Dependency>
            <Dependency>libpng-devel</Dependency>
            <Dependency>libgcrypt-devel</Dependency>
            <Dependency>gnutls-devel</Dependency>
            <Dependency>libjpeg-turbo-devel</Dependency>
        </RuntimeDependencies>
        <Files>
            <Path fileType="header">/usr/include</Path>
            <Path fileType="data">/usr/lib/pkgconfig</Path>
        </Files>
    </Package>

    <History>
        <Update release="3">
            <Date>2017-01-29</Date>
            <Version>0.9.9</Version>
            <Comment>Rebuild</Comment>
            <Name>Pisi Linux Community</Name>
            <Email>admin@pisilinux.org</Email>
        </Update>
        <Update release="2">
            <Date>2016-06-08</Date>
            <Version>0.9.9</Version>
            <Comment>Release Bump</Comment>
            <Name>Pisi Linux Community</Name>
            <Email>admin@pisilinux.org</Email>
        </Update>
        <Update release="1">
            <Date>2014-06-14</Date>
            <Version>0.9.9</Version>
            <Comment>First release</Comment>
            <Name>PisiLinux Community</Name>
            <Email>admins@pisilinux.org</Email>
        </Update>
    </History>
</PISI>


code:
<?xml version="1.0" ?>
<PISI>
    <Source>
        <Name>libvncserver</Name>
        VNC sunucu oluşturmak için kütüphane
        Biblioteka do łatwego implementowania serwera VNC
        <Description xml:lang="tr">VNC sunucu benzeri kendi VNC (Virtual Network Computing) sunucunuzu oluşturmak isterseniz gerekli kütüphane</Description>
        <Description xml:lang="pl">Wieloplatformowa biblioteka C, pozwalającą na łatwą implementację trybu serwera lub klienta VNC (Virtual Network Computing) we własnym programie.</Description>
    </Source>

    <Package>
        <Name>libvncserver-devel</Name>
        libvncserver için geliştirme dosyaları
        Pliki nagłówkowe libvncserver
    </Package>
</PISI>


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/licenses/gpl.txt

from pisi.actionsapi import shelltools
from pisi.actionsapi import autotools
from pisi.actionsapi import pisitools
from pisi.actionsapi import get

WorkDir="%s" % get.srcDIR().replace("_", "")

def setup():
    shelltools.export("CFLAGS", "%s -pie -fPIE -fno-strict-aliasing" % get.CFLAGS())

    # needed to link with avahi
    shelltools.export("ac_cv_header_dns_sd_h", "yes")
    shelltools.export("ac_cv_lib_dns_sd_DNSServiceRegister", "yes")

    #pisitools.dosed("ntpstat-0.2/Makefile", "^CC=.*gcc", "CC=%s" % get.CC())
    #pisitools.dosed("ntpstat-0.2/Makefile", "^CFLAGS=.*", "CFLAGS=%s" % get.CFLAGS())

    autotools.configure("--enable-all-clocks \
                         --enable-parse-clocks \
                         --enable-linuxcaps \
                         --enable-ipv6 \
                         --with-crypto")

def build():
    autotools.make()
    #autotools.make("-C ntpstat-0.2")

    #shelltools.cd("html")
    #shelltools.system("../scripts/html2man")
    #shelltools.system("../fix-man-pages")

def install():
    autotools.rawInstall("DESTDIR=%s" % get.installDIR())

    # Remove autotools installed man pages
    pisitools.removeDir("/usr/share/man")

   # pisitools.doman("html/man/man5/*.5", "html/man/man8/*.8")

    for sbin in ["sntp", "ntpdc", "ntpd", "ntp-keygen", "ntp-wait",
                 "ntpq", "ntptime", "ntptrace", "tickadj", "ntpsnmpd", "ntpdate"]:
        pisitools.domove("/usr/bin/%s" % sbin, "/usr/sbin")

    # Additional ntpstat binary and man page
    #pisitools.dobin("ntpstat-0.2/ntpstat")
    #pisitools.doman("ntpstat-0.2/ntpstat.1")

    pisitools.dodir("/var/lib/ntp")

    #pisitools.removeDir("/usr/lib")

    pisitools.dohtml("html/*")
    pisitools.dodoc("ChangeLog", "NEWS", "README", "TODO", "WHERE-TO-START")


code:
#!/usr/bin/python

import os

def postInstall(fromVersion, fromRelease, toVersion, toRelease):
    os.system("chown -R ntp:ntp /var/lib/ntp")
    os.system("chown -R root:ntp /etc/ntp/crypto")
    os.chmod("/etc/ntp/crypto", 0750)


code:
# -*- coding: utf-8 -*-
from comar.service import *

import os

serviceType = "server"
serviceDesc = _({"en": "NTP Daemon",
                 "tr": "NTP Hizmeti"})
serviceConf = "ntpd"

PIDFILE = "/run/ntpd.pid"

@synchronized
def start():
    startService(command="/usr/sbin/ntpd",
                 args=config.get("OPTIONS", "-u ntp:ntp -p %s -g" % PIDFILE),
                 donotify=True)

@synchronized
def stop():
    stopService(pidfile=PIDFILE,
                donotify=True)

    if os.path.exists(PIDFILE):
        os.unlink(PIDFILE)

def status():
    return isServiceRunning(pidfile=PIDFILE)


code:
#!/usr/bin/python

import os

def postInstall(fromVersion, fromRelease, toVersion, toRelease):
    os.system("/bin/chown root:wheel /usr/sbin/ntpdate")
    os.system("/bin/chmod 04710 /usr/sbin/ntpdate")


code:
# -*- coding: utf-8 -*-
from comar.service import *

import re

serviceType = "local"
serviceDesc = _({"en": "Set the date & time via NTP",
                 "tr": "Tarih & zamanı NTP ile ayarlayın"})
serviceConf = "ntpdate"
serviceDefault = "conditional"

# ntpdate will run if it finds a ticker in any of the configuration files

NTPCONF = "/etc/ntp.conf"
NTPSTEP = "/etc/ntp/step-tickers"
PIDFILE = "/run/ntpdate.pid"

MSG_NOSERVER = _({"en"  : "NTP server not specified in %s or %s." % (NTPSTEP, NTPCONF),
                  "tr"  : "%s veya %s dosyasında hiç NTP sunucu belirtilmemiş." % (NTPSTEP, NTPCONF)})

def parse_tickers():
    tickers = []
    if os.path.exists(NTPSTEP):
        for line in open(NTPSTEP, "r").read().strip().split("\n"):
            if line and not line.startswith("#"):
                tickers.append(line)

    if tickers:
        return tickers

    if os.path.exists(NTPCONF):
        for line in open(NTPCONF, "r").read().strip().split("\n"):
            if line.startswith(("server", "peer")):
                try:
                    peer = line.split()[1]
                    if not re.match("127\.127\.[0-9]+\.[0-9]+", peer):
                        tickers.append(peer)
                except IndexError:
                    pass

    return tickers

@synchronized
def start():
    tickers = parse_tickers()

    if len(tickers) == 0:
        fail(MSG_NOSERVER)

    tickers = " ".join(tickers)

    # Eventhough the ntpdate is a oneshot process, the pidfile hack is used to
    # work around COMAR's silly status() check in startService()
    startService(command="/usr/sbin/ntpdate",
                 args="%s %s" % (config.get("OPTIONS", "-U ntp -s -b"), tickers),
                 makepid=True,
                 pidfile=PIDFILE,
                 donotify=True)

    if os.path.exists(PIDFILE):
        os.unlink(PIDFILE)

    if config.get("SYNC_HWCLOCK", "no") == "yes":
        run("/sbin/hwclock --systohc")

def ready():
    status = is_on()
    tickers = parse_tickers()
    if status == "on" or (status == "conditional" and tickers):
        start()

@synchronized
def stop():
    # There's nothing to do
    pass

def status():
    # No need to supply a status as the service is oneshot
    return


code:
diff -up ntp-4.2.4p7/ntpd/ntp_proto.c.getprecision ntp-4.2.4p7/ntpd/ntp_proto.c
--- ntp-4.2.4p7/ntpd/ntp_proto.c.getprecision	2009-09-29 14:16:22.000000000 +0200
+++ ntp-4.2.4p7/ntpd/ntp_proto.c	2009-09-29 14:18:13.000000000 +0200
@@ -3099,7 +3099,7 @@ peer_unfit(
 /*
  * Find the precision of this particular machine
  */
-#define MINSTEP 100e-9		/* minimum clock increment (s) */
+#define MINSTEP 10e-9		/* minimum clock increment (s) */
 #define MAXSTEP 20e-3		/* maximum clock increment (s) */
 #define MINLOOPS 5		/* minimum number of step samples */


code:
diff -up ntp-4.2.6p1/ntpd/ntp_io.c.bcast ntp-4.2.6p1/ntpd/ntp_io.c
--- ntp-4.2.6p1/ntpd/ntp_io.c.bcast	2009-12-09 08:36:37.000000000 +0100
+++ ntp-4.2.6p1/ntpd/ntp_io.c	2010-03-05 14:49:25.000000000 +0100
@@ -151,6 +151,8 @@ int ninterfaces;			/* Total number of in

 int disable_dynamic_updates;		/* scan interfaces once only */

+static int pktinfo_status = 0;		/* is IP_PKTINFO on wildipv4 iface enabled? */
+
 #ifdef REFCLOCK
 /*
  * Refclock stuff.	We keep a chain of structures with data concerning
@@ -1937,6 +1939,17 @@ set_reuseaddr(
 #endif /* ! SO_EXCLUSIVEADDRUSE */
 }

+static void
+set_pktinfo(int flag)
+{
+	if (wildipv4 == NULL)
+		return;
+	if (setsockopt(wildipv4->fd, SOL_IP, IP_PKTINFO, &flag, sizeof (flag))) {
+		msyslog(LOG_ERR, "set_pktinfo: setsockopt(IP_PKTINFO, %s) failed: %m", flag ? "on" : "off");
+	} else
+		pktinfo_status = flag;
+}
+
 /*
  * This is just a wrapper around an internal function so we can
  * make other changes as necessary later on
@@ -2374,6 +2387,7 @@ io_setbclient(void)
 		}
 	}
 	set_reuseaddr(0);
+	set_pktinfo(1);
 	if (nif > 0)
 		DPRINTF(1, ("io_setbclient: Opened broadcast clients\n"));
 	else if (!nif)
@@ -2405,6 +2419,7 @@ io_unsetbclient(void)

 		socket_broadcast_disable(interf, &interf->sin);
 	}
+	set_pktinfo(0);
 }

 /*
@@ -3130,7 +3145,8 @@ read_network_packet(
 #ifdef HAVE_TIMESTAMP
 	struct msghdr msghdr;
 	struct iovec iovec;
-	char control[TIMESTAMP_CTLMSGBUF_SIZE];
+	char control[sizeof (struct cmsghdr) * 2 + sizeof (struct timeval) +
+		sizeof (struct in_pktinfo) + 32];
 #endif

 	/*
@@ -3141,7 +3157,7 @@ read_network_packet(
 	 */

 	rb = get_free_recv_buffer();
-	if (NULL == rb || itf->ignore_packets) {
+	if (NULL == rb || (itf->ignore_packets && !(pktinfo_status && itf == wildipv4))) {
 		char buf[RX_BUFF_SIZE];
 		sockaddr_u from;

@@ -3201,6 +3217,27 @@ read_network_packet(
 		return (buflen);
 	}

+	if (pktinfo_status && itf->ignore_packets && itf == wildipv4) {
+		/* check for broadcast on 255.255.255.255, exception allowed on wildipv4 */
+		struct cmsghdr *cmsg;
+		struct in_pktinfo *pktinfo = NULL;
+
+		if ((cmsg = CMSG_FIRSTHDR(&msghdr)))
+			do {
+				if (cmsg->cmsg_level == SOL_IP && cmsg->cmsg_type == IP_PKTINFO)
+					pktinfo = (struct in_pktinfo *) CMSG_DATA(cmsg);
+			} while ((cmsg = CMSG_NXTHDR(&msghdr, cmsg)));
+		if (pktinfo && pktinfo->ipi_addr.s_addr == INADDR_BROADCAST) {
+			DPRINTF(4, ("INADDR_BROADCAST\n"));
+		} else {
+			DPRINTF(4, ("%s on (%lu) fd=%d from %s\n", "ignore",
+				free_recvbuffs(), fd, stoa(&rb->recv_srcadr)));
+			packets_ignored++;
+			freerecvbuf(rb);
+			return (buflen);
+		}
+	}
+
 	DPRINTF(3, ("read_network_packet: fd=%d length %d from %s\n",
 		    fd, buflen, stoa(&rb->recv_srcadr)));


code:
diff -up ntp-4.2.6p1/ntpd/ntp_io.c.cmsgalign ntp-4.2.6p1/ntpd/ntp_io.c
--- ntp-4.2.6p1/ntpd/ntp_io.c.cmsgalign	2010-03-04 18:28:53.000000000 +0100
+++ ntp-4.2.6p1/ntpd/ntp_io.c	2010-03-04 18:30:34.000000000 +0100
@@ -3194,8 +3194,8 @@ read_network_packet(
 	msghdr.msg_namelen    = fromlen;
 	msghdr.msg_iov        = &iovec;
 	msghdr.msg_iovlen     = 1;
-	msghdr.msg_control    = (void *)&control;
-	msghdr.msg_controllen = sizeof(control);
+	msghdr.msg_control    = (void *)((long)(control + 7) & -8); /* align to 8 bytes */
+	msghdr.msg_controllen = sizeof(control) - 8;
 	msghdr.msg_flags      = 0;
 	rb->recv_length       = recvmsg(fd, &msghdr, 0);
 #endif


code:
diff -up ntp-4.2.6p1/html/ntpdate.html.droproot ntp-4.2.6p1/html/ntpdate.html
--- ntp-4.2.6p1/html/ntpdate.html.droproot	2006-12-28 13:02:58.000000000 +0100
+++ ntp-4.2.6p1/html/ntpdate.html	2010-03-03 15:32:08.000000000 +0100
@@ -18,7 +18,7 @@

Disclaimer: The functionality of this program is now available in the <tt>ntpd</tt> program. See the <tt>-q</tt> command line option in the <tt>ntpd</tt> - Network Time Protocol (NTP) daemon page. After a suitable period of mourning, the <tt>ntpdate</tt> program is to be retired from this distribution

Synopsis

-		<tt>ntpdate [ -bBdoqsuv ] [ -a key ] [ -e authdelay ] [ -k keyfile ] [ -o version ] [ -p samples ] [ -t timeout ] server [ ... ]</tt>
+		<tt>ntpdate [ -bBdoqsuv ] [ -a key ] [ -e authdelay ] [ -k keyfile ] [ -o version ] [ -p samples ] [ -t timeout ] [ -U user_name ] server [ ... ]</tt>

Description

 		<tt>ntpdate</tt> sets the local date and time by polling the Network Time Protocol (NTP) server(s) given as the server arguments to determine the correct time. It must be run as root on the local host. A number of samples are obtained from each of the servers specified and a subset of the NTP clock filter and selection algorithms are applied to select the best of these. Note that the accuracy and reliability of <tt>ntpdate</tt> depends on the number of servers, the number of polls each time it is run and the interval between runs.

<tt>ntpdate</tt> can be run manually as necessary to set the host clock, or it can be run from the host startup script to set the clock at boot time. This is useful in some cases to set the clock initially before starting the NTP daemon <tt>ntpd</tt>. It is also possible to run <tt>ntpdate</tt> from a <tt>cron</tt> script. However, it is important to note that <tt>ntpdate</tt> with contrived <tt>cron</tt> scripts is no substitute for the NTP daemon, which uses sophisticated algorithms to maximize accuracy and reliability while minimizing resource use. Finally, since <tt>ntpdate</tt> does not discipline the host clock frequency as does <tt>ntpd</tt>, the accuracy using <tt>ntpdate</tt> is limited.

@@ -58,6 +58,11 @@

Direct <tt>ntpdate</tt> to use an unprivileged port or outgoing packets. This is most useful when behind a firewall that blocks incoming traffic to privileged ports, and you want to synchronise with hosts beyond the firewall. Note that the <tt>-d</tt> option always uses unprivileged ports.

<tt>-v</tt>

Be verbose. This option will cause <tt>ntpdate</tt>'s version identification string to be logged.
+
+
<tt>-U user_name</tt>

+
ntpdate process drops root privileges and changes user ID to
+			user_name and group ID to the primary group of
+			server_user.

Diagnostics

 		<tt>ntpdate</tt>'s exit status is zero if it finds a server and updates the clock, and nonzero otherwise.
diff -up ntp-4.2.6p1/ntpdate/ntpdate.c.droproot ntp-4.2.6p1/ntpdate/ntpdate.c
--- ntp-4.2.6p1/ntpdate/ntpdate.c.droproot	2009-12-09 08:36:35.000000000 +0100
+++ ntp-4.2.6p1/ntpdate/ntpdate.c	2010-03-03 15:33:06.000000000 +0100
@@ -48,6 +48,12 @@

 #include <arpa/inet.h>

+/* Linux capabilities */
+#include <sys/capability.h>
+#include <sys/prctl.h>
+#include <pwd.h>
+#include <grp.h>
+
 #ifdef SYS_VXWORKS
 # include "ioLib.h"
 # include "sockLib.h"
@@ -152,6 +158,11 @@ int simple_query = 0;
 int unpriv_port = 0;

 /*
+ * Use capabilities to drop privileges and switch uids
+ */
+char *server_user;
+
+/*
  * Program name.
  */
 char *progname;
@@ -293,6 +304,88 @@ void clear_globals()
 static ni_namelist *getnetinfoservers (void);
 #endif

+/* This patch is adapted (copied) from Chris Wings drop root patch
+ * for xntpd.
+ */
+void drop_root(uid_t server_uid, gid_t server_gid)
+{
+  cap_t caps;
+
+  if (prctl(PR_SET_KEEPCAPS, 1)) {
+		if (syslogit) {
+			msyslog(LOG_ERR, "prctl(PR_SET_KEEPCAPS, 1) failed");
+		}
+		else {
+			fprintf(stderr, "prctl(PR_SET_KEEPCAPS, 1) failed.\n");
+		}
+    exit(1);
+  }
+
+  if ( setgroups(0, NULL) == -1 ) {
+		if (syslogit) {
+			msyslog(LOG_ERR, "setgroups failed.");
+		}
+		else {
+			fprintf(stderr, "setgroups failed.\n");
+		}
+    exit(1);
+  }
+
+  if ( setegid(server_gid) == -1 || seteuid(server_uid) == -1 ) {
+		if (syslogit) {
+			msyslog(LOG_ERR, "setegid/seteuid to uid=%d/gid=%d failed.", server_uid,
+							server_gid);
+		}
+		else {
+			fprintf(stderr, "setegid/seteuid to uid=%d/gid=%d failed.\n", server_uid,
+							server_gid);
+		}
+    exit(1);
+  }
+
+  caps = cap_from_text("cap_sys_time=epi");
+  if (caps == NULL) {
+		if (syslogit) {
+			msyslog(LOG_ERR, "cap_from_text failed.");
+		}
+		else {
+			fprintf(stderr, "cap_from_text failed.\n");
+		}
+    exit(1);
+  }
+
+  if (cap_set_proc(caps) == -1) {
+		if (syslogit) {
+			msyslog(LOG_ERR, "cap_set_proc failed.");
+		}
+		else {
+			fprintf(stderr, "cap_set_proc failed.\n");
+		}
+    exit(1);
+  }
+
+  /* Try to free the memory from cap_from_text */
+  cap_free( caps );
+
+  if ( setregid(server_gid, server_gid) == -1 ||
+       setreuid(server_uid, server_uid) == -1 ) {
+		if (syslogit) {
+			msyslog(LOG_ERR, "setregid/setreuid to uid=%d/gid=%d failed.",
+							server_uid, server_gid);
+		}
+		else {
+			fprintf(stderr, "setregid/setreuid to uid=%d/gid=%d failed.\n",
+							server_uid, server_gid);
+		}
+    exit(1);
+  }
+
+	if (syslogit) {
+		msyslog(LOG_DEBUG, "running as uid(%d)/gid(%d) euid(%d)/egid(%d).",
+						getuid(), getgid(), geteuid(), getegid());
+	}
+}
+
 /*
  * Main program.  Initialize us and loop waiting for I/O and/or
  * timer expiries.
@@ -340,6 +433,8 @@ ntpdatemain (

 	init_lib();	/* sets up ipv4_works, ipv6_works */

+	server_user = NULL;
+
 	/* Check to see if we have IPv6. Otherwise default to IPv4 */
 	if (!ipv6_works)
 		ai_fam_templ = AF_INET;
@@ -351,7 +446,7 @@ ntpdatemain (
 	/*
 	 * Decode argument list
 	 */
-	while ((c = ntp_getopt(argc, argv, "46a:bBde:k:o:p:qst:uv")) != EOF)
+ 	while ((c = ntp_getopt(argc, argv, "46a:bBde:k:o:p:qst:uvU:")) != EOF)
 		switch (c)
 		{
 		case '4':
@@ -429,6 +524,14 @@ ntpdatemain (
 		case 'u':
 			unpriv_port = 1;
 			break;
+ 		case 'U':
+ 			if (ntp_optarg) {
+ 				server_user = strdup(ntp_optarg);
+ 			}
+ 			else {
+ 				++errflg;
+ 			}
+ 			break;
 		case '?':
 			++errflg;
 			break;
@@ -438,7 +541,7 @@ ntpdatemain (

 	if (errflg) {
 		(void) fprintf(stderr,
-		    "usage: %s [-46bBdqsuv] [-a key#] [-e delay] [-k file] [-p samples] [-o version#] [-t timeo] server ...\n",
+		    "usage: %s [-46bBdqsuv] [-a key#] [-e delay] [-k file] [-p samples] [-o version#] [-t timeo] [-U username] server ...\n",
 		    progname);
 		exit(2);
 	}
@@ -544,6 +647,24 @@ ntpdatemain (
 	initializing = 0;
 	was_alarmed = 0;

+	if (server_user) {
+		struct passwd *pwd = NULL;
+
+		/* Lookup server_user uid/gid before chroot/chdir */
+		pwd = getpwnam( server_user );
+		if ( pwd == NULL ) {
+			if (syslogit) {
+				msyslog(LOG_ERR, "Failed to lookup user '%s'.", server_user);
+			}
+			else {
+				fprintf(stderr, "Failed to lookup user '%s'.\n", server_user);
+			}
+			exit(1);
+		}
+		drop_root(pwd->pw_uid, pwd->pw_gid);
+	}
+
+
 	while (complete_servers < sys_numservers) {
 #ifdef HAVE_POLL_H
 		struct pollfd* rdfdes;


code:
diff -up ntp-4.2.6p1/ntpd/ntp_config.c.logdefault ntp-4.2.6p1/ntpd/ntp_config.c
--- ntp-4.2.6p1/ntpd/ntp_config.c.logdefault	2010-01-24 11:01:45.000000000 +0100
+++ ntp-4.2.6p1/ntpd/ntp_config.c	2010-03-09 17:44:09.000000000 +0100
@@ -3794,7 +3794,7 @@ getconfig(

 #endif /* SYS_WINNT */
 	res_fp = NULL;
-	ntp_syslogmask = NLOG_SYNCMASK; /* set more via logconfig */
+	ntp_syslogmask = NLOG_SYNCMASK | NLOG_EVENT | NLOG_STATUS; /* set more via logconfig */

 	/*
 	 * install a non default variable with this daemon version


code:
diff -up ntp-4.2.6p1/include/ntp_syscall.h.nano ntp-4.2.6p1/include/ntp_syscall.h
--- ntp-4.2.6p1/include/ntp_syscall.h.nano	2009-12-09 08:36:37.000000000 +0100
+++ ntp-4.2.6p1/include/ntp_syscall.h	2010-03-03 15:42:18.000000000 +0100
@@ -14,6 +14,14 @@
 # include <sys/timex.h>
 #endif

+#if defined(ADJ_NANO) && !defined(MOD_NANO)
+#define MOD_NANO ADJ_NANO
+#endif
+
+#if defined(ADJ_TAI) && !defined(MOD_TAI)
+#define MOD_TAI ADJ_TAI
+#endif
+
 #ifndef NTP_SYSCALLS_LIBC
 #ifdef NTP_SYSCALLS_STD
 # define ntp_adjtime(t)		syscall(SYS_ntp_adjtime, (t))


code:
diff -up ntp-4.2.6p1/configure.rtnetlink ntp-4.2.6p1/configure
--- ntp-4.2.6p1/configure.rtnetlink	2010-02-09 11:19:49.000000000 +0100
+++ ntp-4.2.6p1/configure	2010-03-04 17:11:50.000000000 +0100
@@ -20579,6 +20579,7 @@ else
 /* end confdefs.h.  */

 #include <stddef.h>
+#include <sys/socket.h>
 #include <linux/rtnetlink.h>
 int
 main ()
diff -up ntp-4.2.6p1/ntpd/ntp_io.c.rtnetlink ntp-4.2.6p1/ntpd/ntp_io.c
--- ntp-4.2.6p1/ntpd/ntp_io.c.rtnetlink	2009-12-09 08:36:37.000000000 +0100
+++ ntp-4.2.6p1/ntpd/ntp_io.c	2010-03-04 17:11:32.000000000 +0100
@@ -4304,10 +4304,7 @@ init_async_notifications()
 #ifdef HAVE_RTNETLINK
 	memset(&sa, 0, sizeof(sa));
 	sa.nl_family = PF_NETLINK;
-	sa.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR
-		       | RTMGRP_IPV6_IFADDR | RTMGRP_IPV4_ROUTE
-		       | RTMGRP_IPV4_MROUTE | RTMGRP_IPV6_ROUTE
-		       | RTMGRP_IPV6_MROUTE;
+	sa.nl_groups = RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR;
 	if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
 		msyslog(LOG_ERR,
 			"bind failed on routing socket (%m) - using polled interface update");


code:
diff -up ntp-4.2.6p1/include/ntp_refclock.h.sleep ntp-4.2.6p1/include/ntp_refclock.h
--- ntp-4.2.6p1/include/ntp_refclock.h.sleep	2009-12-09 08:36:35.000000000 +0100
+++ ntp-4.2.6p1/include/ntp_refclock.h	2010-03-10 19:27:46.000000000 +0100
@@ -260,6 +260,7 @@ extern	void	refclock_control (sockaddr_u
 				    struct refclockstat *);
 extern	int	refclock_open	(char *, u_int, u_int);
 extern	int	refclock_setup	(int, u_int, u_int);
+extern	int	refclock_timer_needed	(struct peer *);
 extern	void	refclock_timer	(struct peer *);
 extern	void	refclock_transmit (struct peer *);
 extern	int	refclock_ioctl	(int, u_int);
diff -up ntp-4.2.6p1/include/ntp_stdlib.h.sleep ntp-4.2.6p1/include/ntp_stdlib.h
--- ntp-4.2.6p1/include/ntp_stdlib.h.sleep	2009-12-09 08:36:35.000000000 +0100
+++ ntp-4.2.6p1/include/ntp_stdlib.h	2010-03-10 19:27:46.000000000 +0100
@@ -116,6 +116,7 @@ extern	const char * FindConfig	(const ch
 extern	void	signal_no_reset (int, RETSIGTYPE (*func)(int));

 extern	void	getauthkeys 	(const char *);
+extern	int	auth_agekeys_needed (void);
 extern	void	auth_agekeys	(void);
 extern	void	rereadkeys	(void);

diff -up ntp-4.2.6p1/include/ntpd.h.sleep ntp-4.2.6p1/include/ntpd.h
--- ntp-4.2.6p1/include/ntpd.h.sleep	2009-12-09 08:36:35.000000000 +0100
+++ ntp-4.2.6p1/include/ntpd.h	2010-03-10 19:27:46.000000000 +0100
@@ -112,8 +112,10 @@ extern	void	block_io_and_alarm	(void);
 /* ntp_loopfilter.c */
 extern	void	init_loopfilter(void);
 extern	int 	local_clock(struct peer *, double);
-extern	void	adj_host_clock(void);
+extern	int	adj_host_clock_needed(void);
+extern	void	adj_host_clock(int);
 extern	void	loop_config(int, double);
+extern	int	huffpuff_enabled(void);
 extern	void	huffpuff(void);
 extern	u_long	sys_clocktime;
 extern	u_int	sys_tai;
@@ -219,6 +221,8 @@ extern	void	hack_restrict	(int, sockaddr
 /* ntp_timer.c */
 extern	void	init_timer	(void);
 extern	void	reinit_timer	(void);
+extern	double	get_timeout	(l_fp *);
+extern	int	timer_elapsed	(l_fp, int);
 extern	void	timer		(void);
 extern	void	timer_clr_stats (void);
 extern  void    timer_interfacetimeout (u_long);
diff -up ntp-4.2.6p1/libntp/authkeys.c.sleep ntp-4.2.6p1/libntp/authkeys.c
--- ntp-4.2.6p1/libntp/authkeys.c.sleep	2009-12-09 08:36:35.000000000 +0100
+++ ntp-4.2.6p1/libntp/authkeys.c	2010-03-10 19:27:46.000000000 +0100
@@ -445,6 +445,25 @@ auth_delkeys(void)
 	}
 }

+int
+auth_agekeys_needed(void) {
+	struct savekey *sk;
+	int i;
+
+	if (authnumkeys > 20)
+		return 1;
+
+	for (i = 0; i < HASHSIZE; i++) {
+		sk = key_hash[i];
+		while (sk != 0) {
+			if (sk->lifetime > 0)
+				return 1;
+			sk = sk->next;
+		}
+	}
+	return 0;
+}
+
 /*
  * auth_agekeys - delete keys whose lifetimes have expired
  */
diff -up ntp-4.2.6p1/ntpd/ntp_loopfilter.c.sleep ntp-4.2.6p1/ntpd/ntp_loopfilter.c
--- ntp-4.2.6p1/ntpd/ntp_loopfilter.c.sleep	2009-12-09 08:36:36.000000000 +0100
+++ ntp-4.2.6p1/ntpd/ntp_loopfilter.c	2010-03-10 19:27:46.000000000 +0100
@@ -677,6 +677,13 @@ local_clock(
 #endif /* LOCKCLOCK */
 }

+int
+adj_host_clock_needed(void)
+{
+	return !(!ntp_enable || mode_ntpdate || (pll_control &&
+	    kern_enable));
+}
+

 /*
  * adj_host_clock - Called once every second to update the local clock.
@@ -686,7 +693,7 @@ local_clock(
  */
 void
 adj_host_clock(
-	void
+	int time_elapsed
 	)
 {
 	double	adjustment;
@@ -698,7 +705,7 @@ adj_host_clock(
 	 * since the poll interval can exceed one day, the old test
 	 * would be counterproductive.
 	 */
-	sys_rootdisp += clock_phi;
+	sys_rootdisp += clock_phi * time_elapsed;

 #ifndef LOCKCLOCK
 	/*
@@ -819,6 +826,12 @@ set_freq(
 #endif /* KERNEL_PLL */
 }

+int
+huffpuff_enabled(void)
+{
+	return sys_huffpuff != NULL;
+}
+
 /*
  * huff-n'-puff filter
  */
diff -up ntp-4.2.6p1/ntpd/ntp_refclock.c.sleep ntp-4.2.6p1/ntpd/ntp_refclock.c
--- ntp-4.2.6p1/ntpd/ntp_refclock.c.sleep	2009-12-09 08:36:36.000000000 +0100
+++ ntp-4.2.6p1/ntpd/ntp_refclock.c	2010-03-10 19:27:46.000000000 +0100
@@ -268,6 +268,21 @@ refclock_unpeer(
 }

+int
+refclock_timer_needed(
+	struct peer *peer	/* peer structure pointer */
+	)
+{
+	u_char clktype;
+	int unit;
+
+	clktype = peer->refclktype;
+	unit = peer->refclkunit;
+	if (refclock_conf[clktype]->clock_timer != noentry)
+		return 1;
+	return 0;
+}
+
 /*
  * refclock_timer - called once per second for housekeeping.
  */
diff -up ntp-4.2.6p1/ntpd/ntp_timer.c.sleep ntp-4.2.6p1/ntpd/ntp_timer.c
--- ntp-4.2.6p1/ntpd/ntp_timer.c.sleep	2009-12-09 08:36:35.000000000 +0100
+++ ntp-4.2.6p1/ntpd/ntp_timer.c	2010-03-11 15:23:59.000000000 +0100
@@ -56,7 +56,6 @@ static	u_long adjust_timer;	/* second ti
 static	u_long stats_timer;	/* stats timer */
 static	u_long huffpuff_timer;	/* huff-n'-puff timer */
 u_long	leapsec;		/* leapseconds countdown */
-l_fp	sys_time;		/* current system time */
 #ifdef OPENSSL
 static	u_long revoke_timer;	/* keys revoke timer */
 static	u_long keys_timer;	/* session key timer */
@@ -74,6 +73,12 @@ volatile u_long alarm_overflow;
 #define	DAY	(24 * HOUR)

 u_long current_time;		/* seconds since startup */
+l_fp timer_base;
+int time_elapsed;
+
+#define TIMEOUT_TS_SIZE 2
+l_fp timeout_ts[TIMEOUT_TS_SIZE];
+unsigned int timeout_ts_index;

 /*
  * Stats.  Number of overflows and number of calls to transmit().
@@ -110,6 +115,8 @@ static	RETSIGTYPE alarming (int);
 void
 reinit_timer(void)
 {
+	get_systime(&timer_base);
+#if 0
 #if !defined(SYS_WINNT) && !defined(VMS)
 #  if defined(HAVE_TIMER_CREATE) && defined(HAVE_TIMER_SETTIME)
 	timer_gettime(ntpd_timerid, &itimer);
@@ -143,6 +150,7 @@ reinit_timer(void)
 	setitimer(ITIMER_REAL, &itimer, (struct itimerval *)0);
 #  endif
 # endif /* VMS */
+#endif
 }

 /*
@@ -165,6 +173,12 @@ init_timer(void)
 	timer_xmtcalls = 0;
 	timer_timereset = 0;

+	get_systime(&timer_base);
+
+	for (timeout_ts_index = 0; timeout_ts_index < TIMEOUT_TS_SIZE; timeout_ts_index++)
+		L_CLR(&timeout_ts[timeout_ts_index]);
+	timeout_ts_index = 0;
+#if 0
 #if !defined(SYS_WINNT)
 	/*
 	 * Set up the alarm interrupt.	The first comes 2**EVENT_TIMEOUT
@@ -226,6 +240,7 @@ init_timer(void)
 	}

 #endif /* SYS_WINNT */
+#endif
 }

 #if defined(SYS_WINNT)
@@ -236,6 +251,104 @@ get_timer_handle(void)
 }
 #endif

+double
+get_timeout(l_fp *now)
+{
+	register struct peer *peer, *next_peer;
+	u_int	n;
+	double r;
+	int next;
+	l_fp ts;
+
+	ts = *now;
+	L_SUB(&ts, &timeout_ts[timeout_ts_index]);
+	timeout_ts[timeout_ts_index] = *now;
+	timeout_ts_index = (timeout_ts_index + 1) % TIMEOUT_TS_SIZE;
+
+	/* don't waste CPU time if called too frequently */
+	if (ts.l_ui == 0) {
+		next = 1;
+		goto finish;
+	}
+
+	next = current_time + HOUR;
+
+	if (adj_host_clock_needed()) {
+		next = 1;
+		goto finish;
+	}
+	for (n = 0; n < NTP_HASH_SIZE; n++) {
+		for (peer = peer_hash[n]; peer != 0; peer = next_peer) {
+			next_peer = peer->next;
+#ifdef REFCLOCK
+			if (peer->flags & FLAG_REFCLOCK && refclock_timer_needed(peer)) {
+				next = 1;
+				goto finish;
+			}
+#endif /* REFCLOCK */
+			if (peer->action)
+			       next = min(next, peer->nextaction);
+			next = min(next, peer->nextdate);
+		}
+	}
+
+	if (leapsec > 0)
+		next = min(next, leapsec);
+
+	if (huffpuff_enabled())
+		next = min(next, huffpuff_timer);
+
+#ifdef OPENSSL
+	if (auth_agekeys_needed())
+		next = min(next, keys_timer);
+	if (sys_leap != LEAP_NOTINSYNC)
+		next = min(next, revoke_timer);
+#endif /* OPENSSL */
+
+	if (interface_interval)
+		next = min(next, interface_timer);
+
+	next = min(next, stats_timer);
+
+	next -= current_time;
+	if (next <= 0)
+		next = 1;
+finish:
+	ts = timer_base;
+	ts.l_ui += next;
+	L_SUB(&ts, now);
+	LFPTOD(&ts, r);
+#ifdef DEBUG
+	DPRINTF(2, ("timer: timeout %f\n", r));
+#endif
+
+	return r;
+}
+
+int
+timer_elapsed(l_fp now, int timeout)
+{
+	int elapsed;
+
+	L_SUB(&now, &timer_base);
+	elapsed = now.l_i;
+	if (elapsed < 0 || elapsed > timeout + 10) {
+#ifdef DEBUG
+		DPRINTF(2, ("timer: unexpected time jump\n"));
+#endif
+		elapsed = 0;
+		reinit_timer();
+
+	}
+	timer_base.l_ui += elapsed;
+	time_elapsed += elapsed;
+	current_time += elapsed;
+#ifdef DEBUG
+	DPRINTF(2, ("timer: time elapsed %d\n", time_elapsed));
+#endif
+	return time_elapsed;
+}
+
 /*
  * timer - event timer
  */
@@ -251,11 +364,9 @@ timer(void)
 	 * kiss-o'-deatch function and implement the association
 	 * polling function..
 	 */
-	current_time++;
-	get_systime(&sys_time);
 	if (adjust_timer <= current_time) {
-		adjust_timer += 1;
-		adj_host_clock();
+		adjust_timer += time_elapsed;
+		adj_host_clock(time_elapsed);
 #ifdef REFCLOCK
 		for (n = 0; n < NTP_HASH_SIZE; n++) {
 			for (peer = peer_hash[n]; peer != 0; peer = next_peer) {
@@ -286,7 +397,7 @@ timer(void)
 			 * 128 s or less.
 			 */
 			if (peer->throttle > 0)
-				peer->throttle--;
+				peer->throttle -= min(peer->throttle, time_elapsed);
 			if (peer->nextdate <= current_time) {
 #ifdef REFCLOCK
 				if (peer->flags & FLAG_REFCLOCK)
@@ -333,7 +444,7 @@ timer(void)
 	 * set.
 	 */
 	if (leapsec > 0) {
-		leapsec--;
+		leapsec -= min(leapsec, time_elapsed);
 		if (leapsec == 0) {
 			sys_leap = LEAP_NOWARNING;
 			sys_tai = leap_tai;
@@ -398,11 +509,15 @@ timer(void)
 	 * Finally, write hourly stats.
 	 */
 	if (stats_timer <= current_time) {
+		l_fp sys_time;
+		get_systime(&sys_time);
 		stats_timer += HOUR;
 		write_stats();
 		if (sys_tai != 0 && sys_time.l_ui > leap_expire)
 			report_event(EVNT_LEAPVAL, NULL, NULL);
 	}
+
+	time_elapsed = 0;
 }

diff -up ntp-4.2.6p1/ntpd/ntpd.c.sleep ntp-4.2.6p1/ntpd/ntpd.c
--- ntp-4.2.6p1/ntpd/ntpd.c.sleep	2010-03-10 19:27:46.000000000 +0100
+++ ntp-4.2.6p1/ntpd/ntpd.c	2010-03-10 19:27:46.000000000 +0100
@@ -195,8 +195,6 @@ extern const char *Version;

 char const *progname;

-int was_alarmed;
-
 #ifdef DECL_SYSCALL
 /*
  * We put this here, since the argument profile is syscall-specific
@@ -1033,7 +1031,7 @@ getgroup:
 #else /* normal I/O */

 	BLOCK_IO_AND_ALARM();
-	was_alarmed = 0;
+
 	for (;;)
 	{
 # if !defined(HAVE_SIGNALED_IO)
@@ -1041,42 +1039,39 @@ getgroup:
 		extern int maxactivefd;

 		fd_set rdfdes;
-		int nfound;
-# endif
+		int nfound, time_elapsed;

-		if (alarm_flag)		/* alarmed? */
-		{
-			was_alarmed = 1;
-			alarm_flag = 0;
-		}
+		time_elapsed = 0;
+# endif

-		if (!was_alarmed && has_full_recv_buffer() == ISC_FALSE)
+		if (has_full_recv_buffer() == ISC_FALSE)
 		{
 			/*
 			 * Nothing to do.  Wait for something.
 			 */
 # ifndef HAVE_SIGNALED_IO
+			double timeout;
+
 			rdfdes = activefds;
-#  if defined(VMS) || defined(SYS_VXWORKS)
-			/* make select() wake up after one second */
-			{
-				struct timeval t1;
+			get_systime(&now);
+			timeout = get_timeout(&now);

-				t1.tv_sec = 1; t1.tv_usec = 0;
+			if (timeout > 0.0) {
+ 				struct timeval t1;
+
+				t1.tv_sec = timeout;
+				t1.tv_usec = (timeout - t1.tv_sec) * 1000000;
 				nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0,
 						(fd_set *)0, &t1);
-			}
-#  else
-			nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0,
-					(fd_set *)0, (struct timeval *)0);
-#  endif /* VMS */
-			if (nfound > 0)
-			{
-				l_fp ts;
+				get_systime(&now);
+			} else
+				nfound = 0;

-				get_systime(&ts);
+			time_elapsed = timer_elapsed(now, timeout);

-				(void)input_handler(&ts);
+			if (nfound > 0)
+			{
+				(void)input_handler(&now);
 			}
 			else if (nfound == -1 && errno != EINTR)
 				msyslog(LOG_ERR, "select() error: %m");
@@ -1085,17 +1080,13 @@ getgroup:
 				msyslog(LOG_DEBUG, "select(): nfound=%d, error: %m", nfound);
 #  endif /* DEBUG */
 # else /* HAVE_SIGNALED_IO */
+#  error not supported by sleep patch

 			wait_for_signal();
 # endif /* HAVE_SIGNALED_IO */
-			if (alarm_flag)		/* alarmed? */
-			{
-				was_alarmed = 1;
-				alarm_flag = 0;
-			}
 		}

-		if (was_alarmed)
+		if (time_elapsed > 0)
 		{
 			UNBLOCK_IO_AND_ALARM();
 			/*
@@ -1103,7 +1094,6 @@ getgroup:
 			 * to process expiry.
 			 */
 			timer();
-			was_alarmed = 0;
 			BLOCK_IO_AND_ALARM();
 		}

@@ -1121,19 +1111,8 @@ getgroup:
 			rbuf = get_full_recv_buffer();
 			while (rbuf != NULL)
 			{
-				if (alarm_flag)
-				{
-					was_alarmed = 1;
-					alarm_flag = 0;
-				}
 				UNBLOCK_IO_AND_ALARM();

-				if (was_alarmed)
-				{	/* avoid timer starvation during lengthy I/O handling */
-					timer();
-					was_alarmed = 0;
-				}
-
 				/*
 				 * Call the data procedure to handle each received
 				 * packet.


code:
diff -up ntp-4.2.6p2/scripts/html2man.in.html2man ntp-4.2.6p2/scripts/html2man.in
--- ntp-4.2.6p2/scripts/html2man.in.html2man	2006-06-06 22:17:10.000000000 +0200
+++ ntp-4.2.6p2/scripts/html2man.in	2010-09-15 16:56:55.000000000 +0200
@@ -20,31 +20,33 @@ $MANDIR = "./man";
 #   name of man page, man section, 'see also' section
 %manfiles = (
 	     'ntpd' => ['ntpd', 8, 'ntp.conf(5), ntpq(8), ntpdc(8)'],
-	     'ntpq' => ['ntpq', 8, 'ntpd(8), ntpdc(8)'],
+	     'ntpq' => ['ntpq', 8, 'ntp_decode(5), ntpd(8), ntpdc(8)'],
 	     'ntpdate' => ['ntpdate', 8, 'ntpd(8)'],
 	     'ntpdc' => ['ntpdc', 8, 'ntpd(8)'],
-	     'ntptime' => ['ntpdtime', 8, 'ntpd(8), ntpdate(8)'],
+	     'ntptime' => ['ntptime', 8, 'ntpd(8), ntpdate(8)'],
 	     'ntptrace' => ['ntptrace', 8, 'ntpd(8)'],
+	     'ntp-wait' => ['ntp-wait', 8, 'ntpd(8)'],
 	     'keygen' => ['ntp-keygen', 8, 'ntpd(8), ntp_auth(5)'],
-	     'confopt' => ['ntp.conf', 5, 'ntpd(8)'],
+	     'tickadj' => ['tickadj', 8, 'ntpd(8)'],
+	     'confopt' => ['ntp.conf', 5, 'ntpd(8), ntp_auth(5), ntp_mon(5), ntp_acc(5), ntp_clock(5), ntp_misc(5)'],
 	     'authopt' => ['ntp_auth', 5, 'ntp.conf(5), ntpd(8)'],
-	     'monopt' => ['ntp_mon', 5, 'ntp.conf(5)'],
+	     'monopt' => ['ntp_mon', 5, 'ntp.conf(5), ntp_decode(5)'],
 	     'accopt' => ['ntp_acc', 5, 'ntp.conf(5)'],
 	     'clockopt' => ['ntp_clock', 5, 'ntp.conf(5)'],
+	     'decode' => ['ntp_decode', 5, 'ntpq(8), ntp_mon(5)'],
 	     'miscopt' => ['ntp_misc', 5, 'ntp.conf(5)']);

+%table_headers = (
+    'ntpd' => 'l l l l.',
+    'ntpq' => 'l l.',
+    'monopt' => 'l l l.',
+    'decode' => 'l l l l.',
+    'authopt' => 'c c c c c c.'
+);
+
 # Disclaimer to go in SEE ALSO section of the man page
-$seealso_disclaimer = 'These man pages are automatically hacked from the main NTP ' .
-    'documentation pages, which are maintained in HTML format.  These files are ' .
-    'included in the NTP source distribution.  If you installed NTP from a binary ' .
-    'package, or it came pre-installed on your system, chances are the documentation ' .
-    'was also included in the usual place for your system.  The HTML files are more ' .
-    'correct and complete than these man pages, which are provided for your reference ' .
-    'only.';
-
-# Disclaimer to go right at the top
-$top_disclaimer = 'This file was automatically generated from HTML source, and may be ' .
-    'incorrect.  See the SEE ALSO section at the end of this file for more info';
+$seealso_disclaimer = "HTML documentation in ntp-doc package.\n\n" .
+    "This file was automatically generated from HTML source.\n";

 mkdir $MANDIR, 0777;
 mkdir "$MANDIR/man8", 0777;
@@ -64,7 +66,8 @@ sub process {
     $fileinfo = $manfiles{$filename};

     $p = HTML::TokeParser->new("$filename.html") || die "Can't open $filename.html: $!";
-    open(MANOUT, ">$MANDIR/man$fileinfo->[1]/$fileinfo->[0].$fileinfo->[1]")
+    $fileout = "$MANDIR/man$fileinfo->[1]/$fileinfo->[0].$fileinfo->[1]";
+    open(MANOUT, ">$fileout")
 	|| die "Can't open: $!";

     $p->get_tag("title");
@@ -73,7 +76,6 @@ sub process {

     # Setup man header
     print MANOUT ".TH " . $fileinfo->[0] . " " . $fileinfo->[1] .  "\n";
-    print MANOUT ".UC 4\n";
     print MANOUT ".SH NAME\n";
     $pat = $fileinfo->[0];
     if ($name =~ /$pat/) {
@@ -81,10 +83,13 @@ sub process {
 	# Add the manpage name, if not in the HTML title already
 	print MANOUT "$fileinfo->[0] - ";
     }
-    print MANOUT "$name\n\n";
-
-    print MANOUT "$top_disclaimer\n";
+    print MANOUT "$name\n.SH \\ \n\n";

+    @fontstack = ();
+    $deflevel = 0;
+    $pre = 0;
+    $ignore = 0;
+    $first_td = 1;
     # Now start scanning.  We basically print everything after translating some tags.
     # $token->[0] has "T", "S", "E" for Text, Start, End
     # $token->[1] has the tag name, or text (for "T" case)
@@ -92,19 +97,37 @@ sub process {
     while (my $token = $p->get_token) {
 	if($token->[0] eq "T") {
 	    my $text = $token->[1];
-	    if($tag) {
-		$text =~ s/^[\n ]*//;
-		$text =~ s/[\n ]*$/ /;
+	    if (!$pre) {
+		if($tag) {
+		    $text =~ s/^[\n\t ]*//;
+		}
+		$text =~ s/^[\n\t ][\n\t ]+$//;
+		$text =~ s/[\n\t ]+/ /g;
+		$text =~ s/&nbsp\;/ /g;
+		$text =~ s/&gt\;/>/g;
+		$text =~ s/&lt\;/</g;
+		$text =~ s/&quot\;/"/g;
+		$text =~ s/&amp\;/&/g;
+		$text =~ s/^\./\\[char46]/;
 	    }
-	    $text =~ s/&nbsp\;/ /g;
-	    $text =~ s/^\./\\./;
 	    print MANOUT "$text";
 	    $tag = 0;
 	}
 	if($token->[0] eq "S") {
 	    if($token->[1] eq "h4") {
 		my $text = uc($p->get_trimmed_text("/h4"));
-		print MANOUT ".SH $text\n";
+		# ignore these sections in ntpd.html
+		if ($filename eq "ntpd" &&
+		    ($text eq "CONFIGURATION OPTIONS")) {
+			$ignore = 1;
+			close(MANOUT);
+			open(MANOUT, ">/dev/null");
+		} elsif ($ignore) {
+		    $ignore = 0;
+		    close(MANOUT);
+		    open(MANOUT, ">>$fileout");
+		}
+		print MANOUT "\n\n.SH $text\n";
 	    }
 	    if($token->[1] eq "tt") {
 		push @fontstack, "tt";
@@ -118,22 +141,42 @@ sub process {
 		my $text = $p->get_trimmed_text("/address");
 		print MANOUT "\n.SH AUTHOR\n$text\n";
 	    }
-	    if($token->[1] eq "dt") {
-		$tmp = $deflevel-4;
-		print MANOUT "\n.RS $tmp\n";
+	    if($token->[1] eq "dt" || $token->[1] eq "br" && $deflevel > 0) {
+		print MANOUT "\n.TP 8\n";
 		$tag = 1;
 	    }
 	    if($token->[1] eq "dd") {
-		print MANOUT "\n.RS $deflevel\n";
+		print MANOUT "\n";
 		$tag = 1;
 	    }
 	    if($token->[1] eq "dl") {
-		$deflevel+=4;
+		$deflevel+=1;
+		if ($deflevel > 0) {
+		    print MANOUT "\n.RS ", $deflevel > 1 ? 8 : 0;
+		}
+	    }
+	    if($token->[1] eq "p") {
+		print MANOUT "\n";
+	    }
+	    if($token->[1] eq "pre") {
+		print MANOUT "\n.nf";
+		$pre = 1;
+	    }
+	    if($token->[1] eq "table") {
+		print MANOUT "\n.TS\n";
+		print MANOUT "expand allbox tab(%);\n";
+		print MANOUT $table_headers{$filename};
+		print MANOUT "\n";
+	    }
+	    if($token->[1] eq "td") {
+		if ($first_td == 0) {
+		    print MANOUT " % ";
+		}
+		$first_td = 0;
 	    }
 	}
 	elsif($token->[0] eq "E") {
-	    if($token->[1] eq "dd") {
-		print MANOUT "\n.RE\n";
+	    if($token->[1] eq "h4") {
 		$tag = 1;
 	    }
 	    if($token->[1] eq "tt") {
@@ -157,15 +200,34 @@ sub process {
 		print MANOUT "$fontswitch";
 	    }
 	    if($token->[1] eq "dl") {
-		$deflevel-=4;
+		if ($deflevel > 0) {
+		    print MANOUT "\n.RE";
+		}
+		print MANOUT "\n";
+		$deflevel-=1;
 	    }
-	    if($token->[1] eq "dt") {
-		print MANOUT "\n.RE";
+	    if($token->[1] eq "p") {
+		print MANOUT "\n";
 		$tag = 1;
 	    }
+	    if($token->[1] eq "pre") {
+		print MANOUT "\n.fi";
+		$pre = 0;
+	    }
+	    if($token->[1] eq "table") {
+		print MANOUT ".TE\n";
+	    }
+	    if($token->[1] eq "tr") {
+		print MANOUT "\n";
+		$first_td = 1;
+	    }
 	}
     }
-    print MANOUT ".SH SEE ALSO\n\n";
+    if ($ignore) {
+	close(MANOUT);
+	open(MANOUT, ">>$fileout");
+    }
+    print MANOUT "\n.SH SEE ALSO\n\n";
     print MANOUT "$fileinfo->[2]\n\n";
     print MANOUT "$seealso_disclaimer\n";
     close(MANOUT);