ntpd.c 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851
  1. /*
  2. * NTP client/server, based on OpenNTPD 3.9p1
  3. *
  4. * Busybox port author: Adam Tkac (C) 2009 <vonsch@gmail.com>
  5. *
  6. * OpenNTPd 3.9p1 copyright holders:
  7. * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
  8. * Copyright (c) 2004 Alexander Guy <alexander.guy@andern.org>
  9. *
  10. * OpenNTPd code is licensed under ISC-style licence:
  11. *
  12. * Permission to use, copy, modify, and distribute this software for any
  13. * purpose with or without fee is hereby granted, provided that the above
  14. * copyright notice and this permission notice appear in all copies.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  17. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  19. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  20. * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
  21. * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
  22. * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  23. ***********************************************************************
  24. *
  25. * Parts of OpenNTPD clock syncronization code is replaced by
  26. * code which is based on ntp-4.2.6, which carries the following
  27. * copyright notice:
  28. *
  29. * Copyright (c) University of Delaware 1992-2009
  30. *
  31. * Permission to use, copy, modify, and distribute this software and
  32. * its documentation for any purpose with or without fee is hereby
  33. * granted, provided that the above copyright notice appears in all
  34. * copies and that both the copyright notice and this permission
  35. * notice appear in supporting documentation, and that the name
  36. * University of Delaware not be used in advertising or publicity
  37. * pertaining to distribution of the software without specific,
  38. * written prior permission. The University of Delaware makes no
  39. * representations about the suitability this software for any
  40. * purpose. It is provided "as is" without express or implied warranty.
  41. ***********************************************************************
  42. */
  43. //config:config NTPD
  44. //config: bool "ntpd (22 kb)"
  45. //config: default y
  46. //config: help
  47. //config: The NTP client/server daemon.
  48. //config:
  49. //config:config FEATURE_NTPD_SERVER
  50. //config: bool "Make ntpd usable as a NTP server"
  51. //config: default y
  52. //config: depends on NTPD
  53. //config: help
  54. //config: Make ntpd usable as a NTP server. If you disable this option
  55. //config: ntpd will be usable only as a NTP client.
  56. //config:
  57. //config:config FEATURE_NTPD_CONF
  58. //config: bool "Make ntpd understand /etc/ntp.conf"
  59. //config: default y
  60. //config: depends on NTPD
  61. //config: help
  62. //config: Make ntpd look in /etc/ntp.conf for peers. Only "server address"
  63. //config: is supported.
  64. //config:
  65. //config:config FEATURE_NTP_AUTH
  66. //config: bool "Support md5/sha1 message authentication codes"
  67. //config: default y
  68. //config: depends on NTPD
  69. //applet:IF_NTPD(APPLET(ntpd, BB_DIR_USR_SBIN, BB_SUID_DROP))
  70. //kbuild:lib-$(CONFIG_NTPD) += ntpd.o
  71. //usage:#define ntpd_trivial_usage
  72. //usage: "[-dnqNw"IF_FEATURE_NTPD_SERVER("l] [-I IFACE")"] [-S PROG]"
  73. //usage: IF_NOT_FEATURE_NTP_AUTH(" [-p PEER]...")
  74. //usage: IF_FEATURE_NTP_AUTH(" [-k KEYFILE] [-p [keyno:N:]PEER]...")
  75. //usage:#define ntpd_full_usage "\n\n"
  76. //usage: "NTP client/server\n"
  77. //usage: "\n -d[d] Verbose"
  78. //usage: "\n -n Run in foreground"
  79. //usage: "\n -q Quit after clock is set"
  80. //usage: "\n -N Run at high priority"
  81. //usage: "\n -w Do not set time (only query peers), implies -n"
  82. //usage: "\n -S PROG Run PROG after stepping time, stratum change, and every 11 min"
  83. //usage: IF_NOT_FEATURE_NTP_AUTH(
  84. //usage: "\n -p PEER Obtain time from PEER (may be repeated)"
  85. //usage: )
  86. //usage: IF_FEATURE_NTP_AUTH(
  87. //usage: "\n -k FILE Key file (ntp.keys compatible)"
  88. //usage: "\n -p [keyno:NUM:]PEER"
  89. //usage: "\n Obtain time from PEER (may be repeated)"
  90. //usage: "\n Use key NUM for authentication"
  91. //usage: )
  92. //usage: IF_FEATURE_NTPD_CONF(
  93. //usage: "\n If -p is not given, 'server HOST' lines"
  94. //usage: "\n from /etc/ntp.conf are used"
  95. //usage: )
  96. //usage: IF_FEATURE_NTPD_SERVER(
  97. //usage: "\n -l Also run as server on port 123"
  98. //usage: "\n -I IFACE Bind server to IFACE, implies -l"
  99. //usage: )
  100. // -l and -p options are not compatible with "standard" ntpd:
  101. // it has them as "-l logfile" and "-p pidfile".
  102. // -S and -w are not compat either, "standard" ntpd has no such opts.
  103. #include "libbb.h"
  104. #include <math.h>
  105. #include <netinet/ip.h> /* For IPTOS_DSCP_AF21 definition */
  106. #include <sys/timex.h>
  107. #ifndef IPTOS_DSCP_AF21
  108. # define IPTOS_DSCP_AF21 0x48
  109. #endif
  110. #if defined(__FreeBSD__)
  111. /* see sys/timex.h */
  112. # define adjtimex ntp_adjtime
  113. # define ADJ_OFFSET MOD_OFFSET
  114. # define ADJ_STATUS MOD_STATUS
  115. # define ADJ_TIMECONST MOD_TIMECONST
  116. #endif
  117. /* Verbosity control (max level of -dddd options accepted).
  118. * max 6 is very talkative (and bloated). 3 is non-bloated,
  119. * production level setting.
  120. */
  121. #define MAX_VERBOSE 3
  122. /* High-level description of the algorithm:
  123. *
  124. * We start running with very small poll_exp, BURSTPOLL,
  125. * in order to quickly accumulate INITIAL_SAMPLES datapoints
  126. * for each peer. Then, time is stepped if the offset is larger
  127. * than STEP_THRESHOLD, otherwise it isn't stepped.
  128. *
  129. * Then poll_exp is set to MINPOLL, and we enter "steady state": we collect
  130. * a datapoint, we select the best peer, if this datapoint is not a new one
  131. * (IOW: if this datapoint isn't for selected peer), sleep
  132. * and collect another one; otherwise, use its offset to update
  133. * frequency drift, if offset is somewhat large, reduce poll_exp,
  134. * otherwise increase poll_exp.
  135. *
  136. * If offset is larger than STEP_THRESHOLD, which shouldn't normally
  137. * happen, we assume that something "bad" happened (computer
  138. * was hibernated, someone set totally wrong date, etc),
  139. * then the time is stepped, all datapoints are discarded,
  140. * and we go back to steady state.
  141. *
  142. * Made some changes to speed up re-syncing after our clock goes bad
  143. * (tested with suspending my laptop):
  144. * - if largish offset (>= STEP_THRESHOLD == 1 sec) is seen
  145. * from a peer, schedule next query for this peer soon
  146. * without drastically lowering poll interval for everybody.
  147. * This makes us collect enough data for step much faster:
  148. * e.g. at poll = 10 (1024 secs), step was done within 5 minutes
  149. * after first reply which indicated that our clock is 14 seconds off.
  150. * - on step, do not discard d_dispersion data of the existing datapoints,
  151. * do not clear reachable_bits. This prevents discarding first ~8
  152. * datapoints after the step.
  153. */
  154. #define INITIAL_SAMPLES 3 /* how many samples do we want for init */
  155. #define MIN_FREQHOLD 10 /* adjust offset, but not freq in this many first adjustments */
  156. #define BAD_DELAY_GROWTH 4 /* drop packet if its delay grew by more than this factor */
  157. #define RETRY_INTERVAL 32 /* on send/recv error, retry in N secs (need to be power of 2) */
  158. #define NOREPLY_INTERVAL 512 /* sent, but got no reply: cap next query by this many seconds */
  159. #define RESPONSE_INTERVAL 16 /* wait for reply up to N secs */
  160. #define HOSTNAME_INTERVAL 4 /* hostname lookup failed. Wait N * peer->dns_errors secs for next try */
  161. #define DNS_ERRORS_CAP 0x3f /* peer->dns_errors is in [0..63] */
  162. /* Step threshold (sec). std ntpd uses 0.128.
  163. */
  164. #define STEP_THRESHOLD 1
  165. /* Slew threshold (sec): adjtimex() won't accept offsets larger than this.
  166. * Using exact power of 2 (1/8, 1/2 etc) results in smaller code
  167. */
  168. #define SLEW_THRESHOLD 0.5
  169. // ^^^^ used to be 0.125.
  170. // Since Linux 2.6.26 (circa 2006), kernel accepts (-0.5s, +0.5s) range
  171. // #define PANIC_THRESHOLD 1000 /* panic threshold (sec) */
  172. /* If we got |offset| > BIGOFF from a peer, cap next query interval
  173. * for this peer by this many seconds:
  174. */
  175. #define BIGOFF STEP_THRESHOLD
  176. #define BIGOFF_INTERVAL (1 << 7) /* 128 s */
  177. #define FREQ_TOLERANCE 0.000015 /* frequency tolerance (15 PPM) */
  178. #define BURSTPOLL 0 /* initial poll */
  179. #define MINPOLL 5 /* minimum poll interval. std ntpd uses 6 (6: 64 sec) */
  180. /* If offset > discipline_jitter * POLLADJ_GATE, and poll interval is > 2^BIGPOLL,
  181. * then it is decreased _at once_. (If <= 2^BIGPOLL, it will be decreased _eventually_).
  182. */
  183. #define BIGPOLL 9 /* 2^9 sec ~= 8.5 min */
  184. #define MAXPOLL 12 /* maximum poll interval (12: 1.1h, 17: 36.4h). std ntpd uses 17 */
  185. /* Actively lower poll when we see such big offsets.
  186. * With SLEW_THRESHOLD = 0.125, it means we try to sync more aggressively
  187. * if offset increases over ~0.04 sec
  188. */
  189. // #define POLLDOWN_OFFSET (SLEW_THRESHOLD / 3)
  190. #define MINDISP 0.01 /* minimum dispersion (sec) */
  191. #define MAXDISP 16 /* maximum dispersion (sec) */
  192. #define MAXSTRAT 16 /* maximum stratum (infinity metric) */
  193. #define MAXDIST 1 /* distance threshold (sec) */
  194. #define MIN_SELECTED 1 /* minimum intersection survivors */
  195. #define MIN_CLUSTERED 3 /* minimum cluster survivors */
  196. /* Correct frequency ourself (0) or let kernel do it (1)? */
  197. #define USING_KERNEL_PLL_LOOP 1
  198. // /* frequency drift we can correct (500 PPM) */
  199. // #define MAXDRIFT 0.000500
  200. // /* Compromise Allan intercept (sec). doc uses 1500, std ntpd uses 512 */
  201. // #define ALLAN 512
  202. // /* PLL loop gain */
  203. // #define PLL 65536
  204. // /* FLL loop gain [why it depends on MAXPOLL??] */
  205. // #define FLL (MAXPOLL + 1)
  206. /* Poll-adjust threshold.
  207. * When we see that offset is small enough compared to discipline jitter,
  208. * we grow a counter: += MINPOLL. When counter goes over POLLADJ_LIMIT,
  209. * we poll_exp++. If offset isn't small, counter -= poll_exp*2,
  210. * and when it goes below -POLLADJ_LIMIT, we poll_exp--.
  211. * (Bumped from 30 to 40 since otherwise I often see poll_exp going *2* steps down)
  212. */
  213. #define POLLADJ_LIMIT 40
  214. /* If offset < discipline_jitter * POLLADJ_GATE, then we decide to increase
  215. * poll interval (we think we can't improve timekeeping
  216. * by staying at smaller poll).
  217. */
  218. #define POLLADJ_GATE 4
  219. #define TIMECONST_HACK_GATE 2
  220. /* Parameter averaging constant */
  221. #define AVG 4
  222. #define MAX_KEY_NUMBER 65535
  223. #define KEYID_SIZE sizeof(uint32_t)
  224. enum {
  225. NTP_VERSION = 4,
  226. NTP_MAXSTRATUM = 15,
  227. NTP_MD5_DIGESTSIZE = 16,
  228. NTP_MSGSIZE_NOAUTH = 48,
  229. NTP_MSGSIZE_MD5_AUTH = NTP_MSGSIZE_NOAUTH + KEYID_SIZE + NTP_MD5_DIGESTSIZE,
  230. NTP_SHA1_DIGESTSIZE = 20,
  231. NTP_MSGSIZE_SHA1_AUTH = NTP_MSGSIZE_NOAUTH + KEYID_SIZE + NTP_SHA1_DIGESTSIZE,
  232. /* Status Masks */
  233. MODE_MASK = (7 << 0),
  234. VERSION_MASK = (7 << 3),
  235. VERSION_SHIFT = 3,
  236. LI_MASK = (3 << 6),
  237. /* Leap Second Codes (high order two bits of m_status) */
  238. LI_NOWARNING = (0 << 6), /* no warning */
  239. LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
  240. LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
  241. LI_ALARM = (3 << 6), /* alarm condition */
  242. /* Mode values */
  243. MODE_RES0 = 0, /* reserved */
  244. MODE_SYM_ACT = 1, /* symmetric active */
  245. MODE_SYM_PAS = 2, /* symmetric passive */
  246. MODE_CLIENT = 3, /* client */
  247. MODE_SERVER = 4, /* server */
  248. MODE_BROADCAST = 5, /* broadcast */
  249. MODE_RES1 = 6, /* reserved for NTP control message */
  250. MODE_RES2 = 7, /* reserved for private use */
  251. };
  252. //TODO: better base selection
  253. #define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
  254. #define NUM_DATAPOINTS 8
  255. typedef struct {
  256. uint32_t int_partl;
  257. uint32_t fractionl;
  258. } l_fixedpt_t;
  259. typedef struct {
  260. uint16_t int_parts;
  261. uint16_t fractions;
  262. } s_fixedpt_t;
  263. typedef struct {
  264. uint8_t m_status; /* status of local clock and leap info */
  265. uint8_t m_stratum;
  266. uint8_t m_ppoll; /* poll value */
  267. int8_t m_precision_exp;
  268. s_fixedpt_t m_rootdelay;
  269. s_fixedpt_t m_rootdisp;
  270. uint32_t m_refid;
  271. l_fixedpt_t m_reftime;
  272. l_fixedpt_t m_orgtime;
  273. l_fixedpt_t m_rectime;
  274. l_fixedpt_t m_xmttime;
  275. uint32_t m_keyid;
  276. uint8_t m_digest[ENABLE_FEATURE_NTP_AUTH ? NTP_SHA1_DIGESTSIZE : NTP_MD5_DIGESTSIZE];
  277. } msg_t;
  278. typedef struct {
  279. double d_offset;
  280. double d_recv_time;
  281. double d_dispersion;
  282. } datapoint_t;
  283. #if ENABLE_FEATURE_NTP_AUTH
  284. enum {
  285. HASH_MD5,
  286. HASH_SHA1,
  287. };
  288. typedef struct {
  289. unsigned id; //try uint16_t?
  290. smalluint type;
  291. smalluint msg_size;
  292. smalluint key_length;
  293. char key[0];
  294. } key_entry_t;
  295. #endif
  296. typedef struct {
  297. len_and_sockaddr *p_lsa;
  298. char *p_dotted;
  299. #if ENABLE_FEATURE_NTP_AUTH
  300. key_entry_t *key_entry;
  301. #endif
  302. int p_fd;
  303. int datapoint_idx;
  304. #if ENABLE_FEATURE_NTPD_SERVER
  305. uint32_t p_refid;
  306. #endif
  307. uint32_t lastpkt_refid;
  308. uint8_t lastpkt_status;
  309. uint8_t lastpkt_stratum;
  310. uint8_t reachable_bits;
  311. uint8_t dns_errors;
  312. /* when to send new query (if p_fd == -1)
  313. * or when receive times out (if p_fd >= 0): */
  314. double next_action_time;
  315. double p_xmttime;
  316. double p_raw_delay;
  317. /* p_raw_delay is set even by "high delay" packets */
  318. /* lastpkt_delay isn't */
  319. double lastpkt_recv_time;
  320. double lastpkt_delay;
  321. double lastpkt_rootdelay;
  322. double lastpkt_rootdisp;
  323. /* produced by filter algorithm: */
  324. double filter_offset;
  325. double filter_dispersion;
  326. double filter_jitter;
  327. datapoint_t filter_datapoint[NUM_DATAPOINTS];
  328. /* last sent packet: */
  329. msg_t p_xmt_msg;
  330. char p_hostname[1];
  331. } peer_t;
  332. enum {
  333. OPT_n = (1 << 0),
  334. OPT_q = (1 << 1),
  335. OPT_N = (1 << 2),
  336. OPT_x = (1 << 3),
  337. OPT_k = (1 << 4) * ENABLE_FEATURE_NTP_AUTH,
  338. /* Insert new options above this line. */
  339. /* Non-compat options: */
  340. OPT_w = (1 << (4+ENABLE_FEATURE_NTP_AUTH)),
  341. OPT_p = (1 << (5+ENABLE_FEATURE_NTP_AUTH)),
  342. OPT_S = (1 << (6+ENABLE_FEATURE_NTP_AUTH)),
  343. OPT_l = (1 << (7+ENABLE_FEATURE_NTP_AUTH)) * ENABLE_FEATURE_NTPD_SERVER,
  344. OPT_I = (1 << (8+ENABLE_FEATURE_NTP_AUTH)) * ENABLE_FEATURE_NTPD_SERVER,
  345. /* We hijack some bits for other purposes */
  346. OPT_qq = (1 << 31),
  347. };
  348. struct globals {
  349. double cur_time;
  350. /* total round trip delay to currently selected reference clock */
  351. double rootdelay;
  352. /* reference timestamp: time when the system clock was last set or corrected */
  353. double reftime;
  354. /* total dispersion to currently selected reference clock */
  355. double rootdisp;
  356. double last_script_run;
  357. char *script_name;
  358. llist_t *ntp_peers;
  359. #if ENABLE_FEATURE_NTPD_SERVER
  360. int listen_fd;
  361. char *if_name;
  362. # define G_listen_fd (G.listen_fd)
  363. #else
  364. # define G_listen_fd (-1)
  365. #endif
  366. unsigned verbose;
  367. unsigned peer_cnt;
  368. /* refid: 32-bit code identifying the particular server or reference clock
  369. * in stratum 0 packets this is a four-character ASCII string,
  370. * called the kiss code, used for debugging and monitoring
  371. * in stratum 1 packets this is a four-character ASCII string
  372. * assigned to the reference clock by IANA. Example: "GPS "
  373. * in stratum 2+ packets, it's IPv4 address or 4 first bytes
  374. * of MD5 hash of IPv6
  375. */
  376. #if ENABLE_FEATURE_NTPD_SERVER
  377. uint32_t refid;
  378. #endif
  379. uint8_t ntp_status;
  380. /* precision is defined as the larger of the resolution and time to
  381. * read the clock, in log2 units. For instance, the precision of a
  382. * mains-frequency clock incrementing at 60 Hz is 16 ms, even when the
  383. * system clock hardware representation is to the nanosecond.
  384. *
  385. * Delays, jitters of various kinds are clamped down to precision.
  386. *
  387. * If precision_sec is too large, discipline_jitter gets clamped to it
  388. * and if offset is smaller than discipline_jitter * POLLADJ_GATE, poll
  389. * interval grows even though we really can benefit from staying at
  390. * smaller one, collecting non-lagged datapoits and correcting offset.
  391. * (Lagged datapoits exist when poll_exp is large but we still have
  392. * systematic offset error - the time distance between datapoints
  393. * is significant and older datapoints have smaller offsets.
  394. * This makes our offset estimation a bit smaller than reality)
  395. * Due to this effect, setting G_precision_sec close to
  396. * STEP_THRESHOLD isn't such a good idea - offsets may grow
  397. * too big and we will step. I observed it with -6.
  398. *
  399. * OTOH, setting precision_sec far too small would result in futile
  400. * attempts to synchronize to an unachievable precision.
  401. *
  402. * -6 is 1/64 sec, -7 is 1/128 sec and so on.
  403. * -8 is 1/256 ~= 0.003906 (worked well for me --vda)
  404. * -9 is 1/512 ~= 0.001953 (let's try this for some time)
  405. */
  406. #define G_precision_exp -9
  407. /*
  408. * G_precision_exp is used only for constructing outgoing packets.
  409. * It's ok to set G_precision_sec to a slightly different value
  410. * (One which is "nicer looking" in logs).
  411. * Exact value would be (1.0 / (1 << (- G_precision_exp))):
  412. */
  413. #define G_precision_sec 0.002
  414. uint8_t stratum;
  415. //uint8_t discipline_state; // doc calls it c.state
  416. uint8_t poll_exp; // s.poll
  417. int polladj_count; // c.count
  418. int FREQHOLD_cnt;
  419. long kernel_freq_drift;
  420. peer_t *last_update_peer;
  421. double last_update_offset; // c.last
  422. double last_update_recv_time; // s.t
  423. double discipline_jitter; // c.jitter
  424. /* Since we only compare it with ints, can simplify code
  425. * by not making this variable floating point:
  426. */
  427. unsigned offset_to_jitter_ratio;
  428. //double cluster_offset; // s.offset
  429. //double cluster_jitter; // s.jitter
  430. #if !USING_KERNEL_PLL_LOOP
  431. double discipline_freq_drift; // c.freq
  432. /* Maybe conditionally calculate wander? it's used only for logging */
  433. double discipline_wander; // c.wander
  434. #endif
  435. };
  436. #define G (*ptr_to_globals)
  437. #define VERB1 if (MAX_VERBOSE && G.verbose)
  438. #define VERB2 if (MAX_VERBOSE >= 2 && G.verbose >= 2)
  439. #define VERB3 if (MAX_VERBOSE >= 3 && G.verbose >= 3)
  440. #define VERB4 if (MAX_VERBOSE >= 4 && G.verbose >= 4)
  441. #define VERB5 if (MAX_VERBOSE >= 5 && G.verbose >= 5)
  442. #define VERB6 if (MAX_VERBOSE >= 6 && G.verbose >= 6)
  443. static double LOG2D(int a)
  444. {
  445. if (a < 0)
  446. return 1.0 / (1UL << -a);
  447. return 1UL << a;
  448. }
  449. static ALWAYS_INLINE double SQUARE(double x)
  450. {
  451. return x * x;
  452. }
  453. static ALWAYS_INLINE double MAXD(double a, double b)
  454. {
  455. if (a > b)
  456. return a;
  457. return b;
  458. }
  459. #if !USING_KERNEL_PLL_LOOP
  460. static ALWAYS_INLINE double MIND(double a, double b)
  461. {
  462. if (a < b)
  463. return a;
  464. return b;
  465. }
  466. #endif
  467. static NOINLINE double my_SQRT(double X)
  468. {
  469. union {
  470. float f;
  471. int32_t i;
  472. } v;
  473. double invsqrt;
  474. double Xhalf = X * 0.5;
  475. /* Fast and good approximation to 1/sqrt(X), black magic */
  476. v.f = X;
  477. /*v.i = 0x5f3759df - (v.i >> 1);*/
  478. v.i = 0x5f375a86 - (v.i >> 1); /* - this constant is slightly better */
  479. invsqrt = v.f; /* better than 0.2% accuracy */
  480. /* Refining it using Newton's method: x1 = x0 - f(x0)/f'(x0)
  481. * f(x) = 1/(x*x) - X (f==0 when x = 1/sqrt(X))
  482. * f'(x) = -2/(x*x*x)
  483. * f(x)/f'(x) = (X - 1/(x*x)) / (2/(x*x*x)) = X*x*x*x/2 - x/2
  484. * x1 = x0 - (X*x0*x0*x0/2 - x0/2) = 1.5*x0 - X*x0*x0*x0/2 = x0*(1.5 - (X/2)*x0*x0)
  485. */
  486. invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); /* ~0.05% accuracy */
  487. /* invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); 2nd iter: ~0.0001% accuracy */
  488. /* With 4 iterations, more than half results will be exact,
  489. * at 6th iterations result stabilizes with about 72% results exact.
  490. * We are well satisfied with 0.05% accuracy.
  491. */
  492. return X * invsqrt; /* X * 1/sqrt(X) ~= sqrt(X) */
  493. }
  494. static ALWAYS_INLINE double SQRT(double X)
  495. {
  496. /* If this arch doesn't use IEEE 754 floats, fall back to using libm */
  497. if (sizeof(float) != 4)
  498. return sqrt(X);
  499. /* This avoids needing libm, saves about 0.5k on x86-32 */
  500. return my_SQRT(X);
  501. }
  502. static double
  503. gettime1900d(void)
  504. {
  505. struct timeval tv;
  506. xgettimeofday(&tv);
  507. G.cur_time = tv.tv_sec + (1.0e-6 * tv.tv_usec) + OFFSET_1900_1970;
  508. return G.cur_time;
  509. }
  510. static void
  511. d_to_tv(struct timeval *tv, double d)
  512. {
  513. tv->tv_sec = (long)d;
  514. tv->tv_usec = (d - tv->tv_sec) * 1000000;
  515. }
  516. static NOINLINE double
  517. lfp_to_d(l_fixedpt_t lfp)
  518. {
  519. double ret;
  520. lfp.int_partl = ntohl(lfp.int_partl);
  521. lfp.fractionl = ntohl(lfp.fractionl);
  522. ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
  523. return ret;
  524. }
  525. static NOINLINE double
  526. sfp_to_d(s_fixedpt_t sfp)
  527. {
  528. double ret;
  529. sfp.int_parts = ntohs(sfp.int_parts);
  530. sfp.fractions = ntohs(sfp.fractions);
  531. ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
  532. return ret;
  533. }
  534. #if ENABLE_FEATURE_NTPD_SERVER
  535. static NOINLINE void
  536. d_to_lfp(l_fixedpt_t *lfp, double d)
  537. {
  538. uint32_t intl;
  539. uint32_t frac;
  540. intl = (uint32_t)d;
  541. frac = (uint32_t)((d - intl) * UINT_MAX);
  542. lfp->int_partl = htonl(intl);
  543. lfp->fractionl = htonl(frac);
  544. }
  545. static NOINLINE void
  546. d_to_sfp(s_fixedpt_t *sfp, double d)
  547. {
  548. uint16_t ints;
  549. uint16_t frac;
  550. ints = (uint16_t)d;
  551. frac = (uint16_t)((d - ints) * USHRT_MAX);
  552. sfp->int_parts = htons(ints);
  553. sfp->fractions = htons(frac);
  554. }
  555. #endif
  556. static double
  557. dispersion(const datapoint_t *dp)
  558. {
  559. return dp->d_dispersion + FREQ_TOLERANCE * (G.cur_time - dp->d_recv_time);
  560. }
  561. static double
  562. root_distance(peer_t *p)
  563. {
  564. /* The root synchronization distance is the maximum error due to
  565. * all causes of the local clock relative to the primary server.
  566. * It is defined as half the total delay plus total dispersion
  567. * plus peer jitter.
  568. */
  569. return MAXD(MINDISP, p->lastpkt_rootdelay + p->lastpkt_delay) / 2
  570. + p->lastpkt_rootdisp
  571. + p->filter_dispersion
  572. + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time)
  573. + p->filter_jitter;
  574. }
  575. static void
  576. set_next(peer_t *p, unsigned t)
  577. {
  578. p->next_action_time = G.cur_time + t;
  579. }
  580. /*
  581. * Peer clock filter and its helpers
  582. */
  583. static void
  584. filter_datapoints(peer_t *p)
  585. {
  586. int i, idx;
  587. double sum, wavg;
  588. datapoint_t *fdp;
  589. /* Simulations have shown that use of *averaged* offset for p->filter_offset
  590. * is in fact worse than simply using last received one: with large poll intervals
  591. * (>= 2048) averaging code uses offset values which are outdated by hours,
  592. * and time/frequency correction goes totally wrong when fed essentially bogus offsets.
  593. */
  594. fdp = p->filter_datapoint;
  595. idx = p->datapoint_idx; /* most recent datapoint's index */
  596. /* filter_offset: simply use the most recent value */
  597. p->filter_offset = fdp[idx].d_offset;
  598. /* n-1
  599. * --- dispersion(i)
  600. * filter_dispersion = \ -------------
  601. * / (i+1)
  602. * --- 2
  603. * i=0
  604. */
  605. wavg = 0;
  606. sum = 0;
  607. for (i = 0; i < NUM_DATAPOINTS; i++) {
  608. sum += dispersion(&fdp[idx]) / (2 << i);
  609. wavg += fdp[idx].d_offset;
  610. idx = (idx - 1) & (NUM_DATAPOINTS - 1);
  611. }
  612. wavg /= NUM_DATAPOINTS;
  613. p->filter_dispersion = sum;
  614. /* +----- -----+ ^ 1/2
  615. * | n-1 |
  616. * | --- |
  617. * | 1 \ 2 |
  618. * filter_jitter = | --- * / (avg-offset_j) |
  619. * | n --- |
  620. * | j=0 |
  621. * +----- -----+
  622. * where n is the number of valid datapoints in the filter (n > 1);
  623. * if filter_jitter < precision then filter_jitter = precision
  624. */
  625. sum = 0;
  626. for (i = 0; i < NUM_DATAPOINTS; i++) {
  627. sum += SQUARE(wavg - fdp[i].d_offset);
  628. }
  629. sum = SQRT(sum / NUM_DATAPOINTS);
  630. p->filter_jitter = sum > G_precision_sec ? sum : G_precision_sec;
  631. VERB4 bb_error_msg("filter offset:%+f disp:%f jitter:%f",
  632. p->filter_offset,
  633. p->filter_dispersion,
  634. p->filter_jitter);
  635. }
  636. static void
  637. reset_peer_stats(peer_t *p, double offset)
  638. {
  639. int i;
  640. bool small_ofs = fabs(offset) < STEP_THRESHOLD;
  641. /* Used to set p->filter_datapoint[i].d_dispersion = MAXDISP
  642. * and clear reachable bits, but this proved to be too aggressive:
  643. * after step (tested with suspending laptop for ~30 secs),
  644. * this caused all previous data to be considered invalid,
  645. * making us needing to collect full ~8 datapoints per peer
  646. * after step in order to start trusting them.
  647. * In turn, this was making poll interval decrease even after
  648. * step was done. (Poll interval decreases already before step
  649. * in this scenario, because we see large offsets and end up with
  650. * no good peer to select).
  651. */
  652. for (i = 0; i < NUM_DATAPOINTS; i++) {
  653. if (small_ofs) {
  654. p->filter_datapoint[i].d_recv_time += offset;
  655. if (p->filter_datapoint[i].d_offset != 0) {
  656. p->filter_datapoint[i].d_offset -= offset;
  657. //bb_error_msg("p->filter_datapoint[%d].d_offset %f -> %f",
  658. // i,
  659. // p->filter_datapoint[i].d_offset + offset,
  660. // p->filter_datapoint[i].d_offset);
  661. }
  662. } else {
  663. p->filter_datapoint[i].d_recv_time = G.cur_time;
  664. p->filter_datapoint[i].d_offset = 0;
  665. /*p->filter_datapoint[i].d_dispersion = MAXDISP;*/
  666. }
  667. }
  668. if (small_ofs) {
  669. p->lastpkt_recv_time += offset;
  670. } else {
  671. /*p->reachable_bits = 0;*/
  672. p->lastpkt_recv_time = G.cur_time;
  673. }
  674. filter_datapoints(p); /* recalc p->filter_xxx */
  675. VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
  676. }
  677. #if ENABLE_FEATURE_NTPD_SERVER
  678. static uint32_t calculate_refid(len_and_sockaddr *lsa)
  679. {
  680. # if ENABLE_FEATURE_IPV6
  681. if (lsa->u.sa.sa_family == AF_INET6) {
  682. md5_ctx_t md5;
  683. uint32_t res[MD5_OUTSIZE / 4];
  684. md5_begin(&md5);
  685. md5_hash(&md5, &lsa->u.sin6.sin6_addr, sizeof(lsa->u.sin6.sin6_addr));
  686. md5_end(&md5, res);
  687. return res[0];
  688. }
  689. # endif
  690. return lsa->u.sin.sin_addr.s_addr;
  691. }
  692. #endif
  693. static len_and_sockaddr*
  694. resolve_peer_hostname(peer_t *p)
  695. {
  696. len_and_sockaddr *lsa = host2sockaddr(p->p_hostname, 123);
  697. if (lsa) {
  698. free(p->p_lsa);
  699. free(p->p_dotted);
  700. p->p_lsa = lsa;
  701. p->p_dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
  702. VERB1 if (strcmp(p->p_hostname, p->p_dotted) != 0)
  703. bb_error_msg("'%s' is %s", p->p_hostname, p->p_dotted);
  704. #if ENABLE_FEATURE_NTPD_SERVER
  705. p->p_refid = calculate_refid(p->p_lsa);
  706. #endif
  707. p->dns_errors = 0;
  708. return lsa;
  709. }
  710. p->dns_errors = ((p->dns_errors << 1) | 1) & DNS_ERRORS_CAP;
  711. return lsa;
  712. }
  713. #if !ENABLE_FEATURE_NTP_AUTH
  714. #define add_peers(s, key_entry) \
  715. add_peers(s)
  716. #endif
  717. static void
  718. add_peers(const char *s, key_entry_t *key_entry)
  719. {
  720. llist_t *item;
  721. peer_t *p;
  722. p = xzalloc(sizeof(*p) + strlen(s));
  723. strcpy(p->p_hostname, s);
  724. p->p_fd = -1;
  725. p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
  726. p->next_action_time = G.cur_time; /* = set_next(p, 0); */
  727. reset_peer_stats(p, STEP_THRESHOLD);
  728. /* Names like N.<country2chars>.pool.ntp.org are randomly resolved
  729. * to a pool of machines. Sometimes different N's resolve to the same IP.
  730. * It is not useful to have two peers with same IP. We skip duplicates.
  731. */
  732. if (resolve_peer_hostname(p)) {
  733. for (item = G.ntp_peers; item != NULL; item = item->link) {
  734. peer_t *pp = (peer_t *) item->data;
  735. if (pp->p_dotted && strcmp(p->p_dotted, pp->p_dotted) == 0) {
  736. bb_error_msg("duplicate peer %s (%s)", s, p->p_dotted);
  737. free(p->p_lsa);
  738. free(p->p_dotted);
  739. free(p);
  740. return;
  741. }
  742. }
  743. }
  744. IF_FEATURE_NTP_AUTH(p->key_entry = key_entry;)
  745. llist_add_to(&G.ntp_peers, p);
  746. G.peer_cnt++;
  747. }
  748. static int
  749. do_sendto(int fd,
  750. const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
  751. msg_t *msg, ssize_t len)
  752. {
  753. ssize_t ret;
  754. errno = 0;
  755. if (!from) {
  756. ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
  757. } else {
  758. ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
  759. }
  760. if (ret != len) {
  761. bb_simple_perror_msg("send failed");
  762. return -1;
  763. }
  764. return 0;
  765. }
  766. #if ENABLE_FEATURE_NTP_AUTH
  767. static void
  768. hash(key_entry_t *key_entry, const msg_t *msg, uint8_t *output)
  769. {
  770. union {
  771. md5_ctx_t m;
  772. sha1_ctx_t s;
  773. } ctx;
  774. unsigned hash_size = sizeof(*msg) - sizeof(msg->m_keyid) - sizeof(msg->m_digest);
  775. switch (key_entry->type) {
  776. case HASH_MD5:
  777. md5_begin(&ctx.m);
  778. md5_hash(&ctx.m, key_entry->key, key_entry->key_length);
  779. md5_hash(&ctx.m, msg, hash_size);
  780. md5_end(&ctx.m, output);
  781. break;
  782. default: /* it's HASH_SHA1 */
  783. sha1_begin(&ctx.s);
  784. sha1_hash(&ctx.s, key_entry->key, key_entry->key_length);
  785. sha1_hash(&ctx.s, msg, hash_size);
  786. sha1_end(&ctx.s, output);
  787. break;
  788. }
  789. }
  790. static void
  791. hash_peer(peer_t *p)
  792. {
  793. p->p_xmt_msg.m_keyid = htonl(p->key_entry->id);
  794. hash(p->key_entry, &p->p_xmt_msg, p->p_xmt_msg.m_digest);
  795. }
  796. static int
  797. hashes_differ(peer_t *p, const msg_t *msg)
  798. {
  799. uint8_t digest[NTP_SHA1_DIGESTSIZE];
  800. hash(p->key_entry, msg, digest);
  801. return memcmp(digest, msg->m_digest, p->key_entry->msg_size - NTP_MSGSIZE_NOAUTH - KEYID_SIZE);
  802. }
  803. #endif
  804. static void
  805. send_query_to_peer(peer_t *p)
  806. {
  807. if (!p->p_lsa)
  808. return;
  809. /* Why do we need to bind()?
  810. * See what happens when we don't bind:
  811. *
  812. * socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
  813. * setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
  814. * gettimeofday({1259071266, 327885}, NULL) = 0
  815. * sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
  816. * ^^^ we sent it from some source port picked by kernel.
  817. * time(NULL) = 1259071266
  818. * write(2, "ntpd: entering poll 15 secs\n", 28) = 28
  819. * poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
  820. * recv(3, "yyy", 68, MSG_DONTWAIT) = 48
  821. * ^^^ this recv will receive packets to any local port!
  822. *
  823. * Uncomment this and use strace to see it in action:
  824. */
  825. #define PROBE_LOCAL_ADDR /* { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); } */
  826. if (p->p_fd == -1) {
  827. int fd, family;
  828. len_and_sockaddr *local_lsa;
  829. family = p->p_lsa->u.sa.sa_family;
  830. p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
  831. /* local_lsa has "null" address and port 0 now.
  832. * bind() ensures we have a *particular port* selected by kernel
  833. * and remembered in p->p_fd, thus later recv(p->p_fd)
  834. * receives only packets sent to this port.
  835. */
  836. PROBE_LOCAL_ADDR
  837. xbind(fd, &local_lsa->u.sa, local_lsa->len);
  838. PROBE_LOCAL_ADDR
  839. #if ENABLE_FEATURE_IPV6
  840. if (family == AF_INET)
  841. #endif
  842. setsockopt_int(fd, IPPROTO_IP, IP_TOS, IPTOS_DSCP_AF21);
  843. free(local_lsa);
  844. }
  845. /* Emit message _before_ attempted send. Think of a very short
  846. * roundtrip networks: we need to go back to recv loop ASAP,
  847. * to reduce delay. Printing messages after send works against that.
  848. */
  849. VERB1 bb_error_msg("sending query to %s", p->p_dotted);
  850. /*
  851. * Send out a random 64-bit number as our transmit time. The NTP
  852. * server will copy said number into the originate field on the
  853. * response that it sends us. This is totally legal per the SNTP spec.
  854. *
  855. * The impact of this is two fold: we no longer send out the current
  856. * system time for the world to see (which may aid an attacker), and
  857. * it gives us a (not very secure) way of knowing that we're not
  858. * getting spoofed by an attacker that can't capture our traffic
  859. * but can spoof packets from the NTP server we're communicating with.
  860. *
  861. * Save the real transmit timestamp locally.
  862. */
  863. p->p_xmt_msg.m_xmttime.int_partl = rand();
  864. p->p_xmt_msg.m_xmttime.fractionl = rand();
  865. p->p_xmttime = gettime1900d();
  866. /* Were doing it only if sendto worked, but
  867. * loss of sync detection needs reachable_bits updated
  868. * even if sending fails *locally*:
  869. * "network is unreachable" because cable was pulled?
  870. * We still need to declare "unsync" if this condition persists.
  871. */
  872. p->reachable_bits <<= 1;
  873. #if ENABLE_FEATURE_NTP_AUTH
  874. if (p->key_entry)
  875. hash_peer(p);
  876. if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
  877. &p->p_xmt_msg, !p->key_entry ? NTP_MSGSIZE_NOAUTH : p->key_entry->msg_size) == -1
  878. )
  879. #else
  880. if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
  881. &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
  882. )
  883. #endif
  884. {
  885. close(p->p_fd);
  886. p->p_fd = -1;
  887. /*
  888. * We know that we sent nothing.
  889. * We can retry *soon* without fearing
  890. * that we are flooding the peer.
  891. */
  892. set_next(p, RETRY_INTERVAL);
  893. return;
  894. }
  895. set_next(p, RESPONSE_INTERVAL);
  896. }
  897. /* Note that there is no provision to prevent several run_scripts
  898. * to be started in quick succession. In fact, it happens rather often
  899. * if initial syncronization results in a step.
  900. * You will see "step" and then "stratum" script runs, sometimes
  901. * as close as only 0.002 seconds apart.
  902. * Script should be ready to deal with this.
  903. */
  904. static void run_script(const char *action, double offset)
  905. {
  906. char *argv[3];
  907. char *env1, *env2, *env3, *env4;
  908. G.last_script_run = G.cur_time;
  909. if (!G.script_name)
  910. return;
  911. argv[0] = (char*) G.script_name;
  912. argv[1] = (char*) action;
  913. argv[2] = NULL;
  914. VERB1 bb_error_msg("executing '%s %s'", G.script_name, action);
  915. env1 = xasprintf("%s=%u", "stratum", G.stratum);
  916. putenv(env1);
  917. env2 = xasprintf("%s=%ld", "freq_drift_ppm", G.kernel_freq_drift);
  918. putenv(env2);
  919. env3 = xasprintf("%s=%u", "poll_interval", 1 << G.poll_exp);
  920. putenv(env3);
  921. env4 = xasprintf("%s=%f", "offset", offset);
  922. putenv(env4);
  923. /* Other items of potential interest: selected peer,
  924. * rootdelay, reftime, rootdisp, refid, ntp_status,
  925. * last_update_offset, last_update_recv_time, discipline_jitter,
  926. * how many peers have reachable_bits = 0?
  927. */
  928. /* Don't want to wait: it may run hwclock --systohc, and that
  929. * may take some time (seconds): */
  930. /*spawn_and_wait(argv);*/
  931. spawn(argv);
  932. unsetenv("stratum");
  933. unsetenv("freq_drift_ppm");
  934. unsetenv("poll_interval");
  935. unsetenv("offset");
  936. free(env1);
  937. free(env2);
  938. free(env3);
  939. free(env4);
  940. }
  941. static NOINLINE void
  942. step_time(double offset)
  943. {
  944. llist_t *item;
  945. double dtime;
  946. struct timeval tvc, tvn;
  947. char buf[sizeof("yyyy-mm-dd hh:mm:ss") + /*paranoia:*/ 4];
  948. time_t tval;
  949. xgettimeofday(&tvc);
  950. dtime = tvc.tv_sec + (1.0e-6 * tvc.tv_usec) + offset;
  951. d_to_tv(&tvn, dtime);
  952. xsettimeofday(&tvn);
  953. VERB2 {
  954. tval = tvc.tv_sec;
  955. strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
  956. bb_error_msg("current time is %s.%06u", buf, (unsigned)tvc.tv_usec);
  957. }
  958. tval = tvn.tv_sec;
  959. strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
  960. bb_info_msg("setting time to %s.%06u (offset %+fs)", buf, (unsigned)tvn.tv_usec, offset);
  961. //maybe? G.FREQHOLD_cnt = 0;
  962. /* Correct various fields which contain time-relative values: */
  963. /* Globals: */
  964. G.cur_time += offset;
  965. G.last_update_recv_time += offset;
  966. G.last_script_run += offset;
  967. /* p->lastpkt_recv_time, p->next_action_time and such: */
  968. for (item = G.ntp_peers; item != NULL; item = item->link) {
  969. peer_t *pp = (peer_t *) item->data;
  970. reset_peer_stats(pp, offset);
  971. //bb_error_msg("offset:%+f pp->next_action_time:%f -> %f",
  972. // offset, pp->next_action_time, pp->next_action_time + offset);
  973. pp->next_action_time += offset;
  974. if (pp->p_fd >= 0) {
  975. /* We wait for reply from this peer too.
  976. * But due to step we are doing, reply's data is no longer
  977. * useful (in fact, it'll be bogus). Stop waiting for it.
  978. */
  979. close(pp->p_fd);
  980. pp->p_fd = -1;
  981. set_next(pp, RETRY_INTERVAL);
  982. }
  983. }
  984. }
  985. static void clamp_pollexp_and_set_MAXSTRAT(void)
  986. {
  987. if (G.poll_exp < MINPOLL)
  988. G.poll_exp = MINPOLL;
  989. if (G.poll_exp > BIGPOLL)
  990. G.poll_exp = BIGPOLL;
  991. G.polladj_count = 0;
  992. G.stratum = MAXSTRAT;
  993. }
  994. /*
  995. * Selection and clustering, and their helpers
  996. */
  997. typedef struct {
  998. peer_t *p;
  999. int type;
  1000. double edge;
  1001. double opt_rd; /* optimization */
  1002. } point_t;
  1003. static int
  1004. compare_point_edge(const void *aa, const void *bb)
  1005. {
  1006. const point_t *a = aa;
  1007. const point_t *b = bb;
  1008. if (a->edge < b->edge) {
  1009. return -1;
  1010. }
  1011. return (a->edge > b->edge);
  1012. }
  1013. typedef struct {
  1014. peer_t *p;
  1015. double metric;
  1016. } survivor_t;
  1017. static int
  1018. compare_survivor_metric(const void *aa, const void *bb)
  1019. {
  1020. const survivor_t *a = aa;
  1021. const survivor_t *b = bb;
  1022. if (a->metric < b->metric) {
  1023. return -1;
  1024. }
  1025. return (a->metric > b->metric);
  1026. }
  1027. static int
  1028. fit(peer_t *p, double rd)
  1029. {
  1030. if ((p->reachable_bits & (p->reachable_bits-1)) == 0) {
  1031. /* One or zero bits in reachable_bits */
  1032. VERB4 bb_error_msg("peer %s unfit for selection: "
  1033. "unreachable", p->p_dotted);
  1034. return 0;
  1035. }
  1036. #if 0 /* we filter out such packets earlier */
  1037. if ((p->lastpkt_status & LI_ALARM) == LI_ALARM
  1038. || p->lastpkt_stratum >= MAXSTRAT
  1039. ) {
  1040. VERB4 bb_error_msg("peer %s unfit for selection: "
  1041. "bad status/stratum", p->p_dotted);
  1042. return 0;
  1043. }
  1044. #endif
  1045. /* rd is root_distance(p) */
  1046. if (rd > MAXDIST + FREQ_TOLERANCE * (1 << G.poll_exp)) {
  1047. VERB3 bb_error_msg("peer %s unfit for selection: "
  1048. "root distance %f too high, jitter:%f",
  1049. p->p_dotted, rd, p->filter_jitter
  1050. );
  1051. return 0;
  1052. }
  1053. //TODO
  1054. // /* Do we have a loop? */
  1055. // if (p->refid == p->dstaddr || p->refid == s.refid)
  1056. // return 0;
  1057. return 1;
  1058. }
  1059. static NOINLINE peer_t*
  1060. select_and_cluster(void)
  1061. {
  1062. peer_t *p;
  1063. llist_t *item;
  1064. int i, j;
  1065. int size = 3 * G.peer_cnt;
  1066. /* for selection algorithm */
  1067. point_t point[size];
  1068. unsigned num_points, num_candidates;
  1069. double low, high;
  1070. unsigned num_falsetickers;
  1071. /* for cluster algorithm */
  1072. survivor_t survivor[size];
  1073. unsigned num_survivors;
  1074. /* Selection */
  1075. num_points = 0;
  1076. item = G.ntp_peers;
  1077. while (item != NULL) {
  1078. double rd, offset;
  1079. p = (peer_t *) item->data;
  1080. rd = root_distance(p);
  1081. offset = p->filter_offset;
  1082. if (!fit(p, rd)) {
  1083. item = item->link;
  1084. continue;
  1085. }
  1086. VERB5 bb_error_msg("interval: [%f %f %f] %s",
  1087. offset - rd,
  1088. offset,
  1089. offset + rd,
  1090. p->p_dotted
  1091. );
  1092. point[num_points].p = p;
  1093. point[num_points].type = -1;
  1094. point[num_points].edge = offset - rd;
  1095. point[num_points].opt_rd = rd;
  1096. num_points++;
  1097. point[num_points].p = p;
  1098. point[num_points].type = 0;
  1099. point[num_points].edge = offset;
  1100. point[num_points].opt_rd = rd;
  1101. num_points++;
  1102. point[num_points].p = p;
  1103. point[num_points].type = 1;
  1104. point[num_points].edge = offset + rd;
  1105. point[num_points].opt_rd = rd;
  1106. num_points++;
  1107. item = item->link;
  1108. }
  1109. num_candidates = num_points / 3;
  1110. if (num_candidates == 0) {
  1111. VERB3 bb_error_msg("no valid datapoints%s", ", no peer selected");
  1112. return NULL;
  1113. }
  1114. //TODO: sorting does not seem to be done in reference code
  1115. qsort(point, num_points, sizeof(point[0]), compare_point_edge);
  1116. /* Start with the assumption that there are no falsetickers.
  1117. * Attempt to find a nonempty intersection interval containing
  1118. * the midpoints of all truechimers.
  1119. * If a nonempty interval cannot be found, increase the number
  1120. * of assumed falsetickers by one and try again.
  1121. * If a nonempty interval is found and the number of falsetickers
  1122. * is less than the number of truechimers, a majority has been found
  1123. * and the midpoint of each truechimer represents
  1124. * the candidates available to the cluster algorithm.
  1125. */
  1126. num_falsetickers = 0;
  1127. while (1) {
  1128. int c;
  1129. unsigned num_midpoints = 0;
  1130. low = 1 << 9;
  1131. high = - (1 << 9);
  1132. c = 0;
  1133. for (i = 0; i < num_points; i++) {
  1134. /* We want to do:
  1135. * if (point[i].type == -1) c++;
  1136. * if (point[i].type == 1) c--;
  1137. * and it's simpler to do it this way:
  1138. */
  1139. c -= point[i].type;
  1140. if (c >= num_candidates - num_falsetickers) {
  1141. /* If it was c++ and it got big enough... */
  1142. low = point[i].edge;
  1143. break;
  1144. }
  1145. if (point[i].type == 0)
  1146. num_midpoints++;
  1147. }
  1148. c = 0;
  1149. for (i = num_points-1; i >= 0; i--) {
  1150. c += point[i].type;
  1151. if (c >= num_candidates - num_falsetickers) {
  1152. high = point[i].edge;
  1153. break;
  1154. }
  1155. if (point[i].type == 0)
  1156. num_midpoints++;
  1157. }
  1158. /* If the number of midpoints is greater than the number
  1159. * of allowed falsetickers, the intersection contains at
  1160. * least one truechimer with no midpoint - bad.
  1161. * Also, interval should be nonempty.
  1162. */
  1163. if (num_midpoints <= num_falsetickers && low < high)
  1164. break;
  1165. num_falsetickers++;
  1166. if (num_falsetickers * 2 >= num_candidates) {
  1167. VERB3 bb_error_msg("falsetickers:%d, candidates:%d%s",
  1168. num_falsetickers, num_candidates,
  1169. ", no peer selected");
  1170. return NULL;
  1171. }
  1172. }
  1173. VERB4 bb_error_msg("selected interval: [%f, %f]; candidates:%d falsetickers:%d",
  1174. low, high, num_candidates, num_falsetickers);
  1175. /* Clustering */
  1176. /* Construct a list of survivors (p, metric)
  1177. * from the chime list, where metric is dominated
  1178. * first by stratum and then by root distance.
  1179. * All other things being equal, this is the order of preference.
  1180. */
  1181. num_survivors = 0;
  1182. for (i = 0; i < num_points; i++) {
  1183. if (point[i].edge < low || point[i].edge > high)
  1184. continue;
  1185. p = point[i].p;
  1186. survivor[num_survivors].p = p;
  1187. /* x.opt_rd == root_distance(p); */
  1188. survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + point[i].opt_rd;
  1189. VERB5 bb_error_msg("survivor[%d] metric:%f peer:%s",
  1190. num_survivors, survivor[num_survivors].metric, p->p_dotted);
  1191. num_survivors++;
  1192. }
  1193. /* There must be at least MIN_SELECTED survivors to satisfy the
  1194. * correctness assertions. Ordinarily, the Byzantine criteria
  1195. * require four survivors, but for the demonstration here, one
  1196. * is acceptable.
  1197. */
  1198. if (num_survivors < MIN_SELECTED) {
  1199. VERB3 bb_error_msg("survivors:%d%s",
  1200. num_survivors,
  1201. ", no peer selected");
  1202. return NULL;
  1203. }
  1204. //looks like this is ONLY used by the fact that later we pick survivor[0].
  1205. //we can avoid sorting then, just find the minimum once!
  1206. qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric);
  1207. /* For each association p in turn, calculate the selection
  1208. * jitter p->sjitter as the square root of the sum of squares
  1209. * (p->offset - q->offset) over all q associations. The idea is
  1210. * to repeatedly discard the survivor with maximum selection
  1211. * jitter until a termination condition is met.
  1212. */
  1213. while (1) {
  1214. unsigned max_idx = max_idx;
  1215. double max_selection_jitter = max_selection_jitter;
  1216. double min_jitter = min_jitter;
  1217. if (num_survivors <= MIN_CLUSTERED) {
  1218. VERB4 bb_error_msg("num_survivors %d <= %d, not discarding more",
  1219. num_survivors, MIN_CLUSTERED);
  1220. break;
  1221. }
  1222. /* To make sure a few survivors are left
  1223. * for the clustering algorithm to chew on,
  1224. * we stop if the number of survivors
  1225. * is less than or equal to MIN_CLUSTERED (3).
  1226. */
  1227. for (i = 0; i < num_survivors; i++) {
  1228. double selection_jitter_sq;
  1229. p = survivor[i].p;
  1230. if (i == 0 || p->filter_jitter < min_jitter)
  1231. min_jitter = p->filter_jitter;
  1232. selection_jitter_sq = 0;
  1233. for (j = 0; j < num_survivors; j++) {
  1234. peer_t *q = survivor[j].p;
  1235. selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset);
  1236. }
  1237. if (i == 0 || selection_jitter_sq > max_selection_jitter) {
  1238. max_selection_jitter = selection_jitter_sq;
  1239. max_idx = i;
  1240. }
  1241. VERB6 bb_error_msg("survivor %d selection_jitter^2:%f",
  1242. i, selection_jitter_sq);
  1243. }
  1244. max_selection_jitter = SQRT(max_selection_jitter / num_survivors);
  1245. VERB5 bb_error_msg("max_selection_jitter (at %d):%f min_jitter:%f",
  1246. max_idx, max_selection_jitter, min_jitter);
  1247. /* If the maximum selection jitter is less than the
  1248. * minimum peer jitter, then tossing out more survivors
  1249. * will not lower the minimum peer jitter, so we might
  1250. * as well stop.
  1251. */
  1252. if (max_selection_jitter < min_jitter) {
  1253. VERB4 bb_error_msg("max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more",
  1254. max_selection_jitter, min_jitter, num_survivors);
  1255. break;
  1256. }
  1257. /* Delete survivor[max_idx] from the list
  1258. * and go around again.
  1259. */
  1260. VERB6 bb_error_msg("dropping survivor %d", max_idx);
  1261. num_survivors--;
  1262. while (max_idx < num_survivors) {
  1263. survivor[max_idx] = survivor[max_idx + 1];
  1264. max_idx++;
  1265. }
  1266. }
  1267. if (0) {
  1268. /* Combine the offsets of the clustering algorithm survivors
  1269. * using a weighted average with weight determined by the root
  1270. * distance. Compute the selection jitter as the weighted RMS
  1271. * difference between the first survivor and the remaining
  1272. * survivors. In some cases the inherent clock jitter can be
  1273. * reduced by not using this algorithm, especially when frequent
  1274. * clockhopping is involved. bbox: thus we don't do it.
  1275. */
  1276. double x, y, z, w;
  1277. y = z = w = 0;
  1278. for (i = 0; i < num_survivors; i++) {
  1279. p = survivor[i].p;
  1280. x = root_distance(p);
  1281. y += 1 / x;
  1282. z += p->filter_offset / x;
  1283. w += SQUARE(p->filter_offset - survivor[0].p->filter_offset) / x;
  1284. }
  1285. //G.cluster_offset = z / y;
  1286. //G.cluster_jitter = SQRT(w / y);
  1287. }
  1288. /* Pick the best clock. If the old system peer is on the list
  1289. * and at the same stratum as the first survivor on the list,
  1290. * then don't do a clock hop. Otherwise, select the first
  1291. * survivor on the list as the new system peer.
  1292. */
  1293. p = survivor[0].p;
  1294. if (G.last_update_peer
  1295. && G.last_update_peer->lastpkt_stratum <= p->lastpkt_stratum
  1296. ) {
  1297. /* Starting from 1 is ok here */
  1298. for (i = 1; i < num_survivors; i++) {
  1299. if (G.last_update_peer == survivor[i].p) {
  1300. VERB5 bb_simple_error_msg("keeping old synced peer");
  1301. p = G.last_update_peer;
  1302. goto keep_old;
  1303. }
  1304. }
  1305. }
  1306. G.last_update_peer = p;
  1307. keep_old:
  1308. VERB4 bb_error_msg("selected peer %s filter_offset:%+f age:%f",
  1309. p->p_dotted,
  1310. p->filter_offset,
  1311. G.cur_time - p->lastpkt_recv_time
  1312. );
  1313. return p;
  1314. }
  1315. /*
  1316. * Local clock discipline and its helpers
  1317. */
  1318. static void
  1319. set_new_values(double offset, double recv_time)
  1320. {
  1321. /* Enter new state and set state variables. Note we use the time
  1322. * of the last clock filter sample, which must be earlier than
  1323. * the current time.
  1324. */
  1325. VERB4 bb_error_msg("last update offset=%f recv_time=%f",
  1326. offset, recv_time);
  1327. G.last_update_offset = offset;
  1328. G.last_update_recv_time = recv_time;
  1329. }
  1330. /* Return: -1: decrease poll interval, 0: leave as is, 1: increase */
  1331. static NOINLINE int
  1332. update_local_clock(peer_t *p)
  1333. {
  1334. int rc;
  1335. struct timex tmx;
  1336. /* Note: can use G.cluster_offset instead: */
  1337. double offset = p->filter_offset;
  1338. double recv_time = p->lastpkt_recv_time;
  1339. double abs_offset;
  1340. #if !USING_KERNEL_PLL_LOOP
  1341. double freq_drift;
  1342. double since_last_update;
  1343. #endif
  1344. double etemp, dtemp;
  1345. abs_offset = fabs(offset);
  1346. #if 0
  1347. /* If needed, -S script can do it by looking at $offset
  1348. * env var and killing parent */
  1349. /* If the offset is too large, give up and go home */
  1350. if (abs_offset > PANIC_THRESHOLD) {
  1351. bb_error_msg_and_die("offset %f far too big, exiting", offset);
  1352. }
  1353. #endif
  1354. /* If this is an old update, for instance as the result
  1355. * of a system peer change, avoid it. We never use
  1356. * an old sample or the same sample twice.
  1357. */
  1358. if (recv_time <= G.last_update_recv_time) {
  1359. VERB3 bb_error_msg("update from %s: same or older datapoint, not using it",
  1360. p->p_dotted);
  1361. return 0; /* "leave poll interval as is" */
  1362. }
  1363. /* Clock state machine transition function. This is where the
  1364. * action is and defines how the system reacts to large time
  1365. * and frequency errors.
  1366. */
  1367. #if !USING_KERNEL_PLL_LOOP
  1368. since_last_update = recv_time - G.reftime;
  1369. freq_drift = 0;
  1370. #endif
  1371. /* There are two main regimes: when the
  1372. * offset exceeds the step threshold and when it does not.
  1373. */
  1374. if (abs_offset > STEP_THRESHOLD) {
  1375. /* Step the time and clamp down the poll interval.
  1376. *
  1377. * In NSET state an initial frequency correction is
  1378. * not available, usually because the frequency file has
  1379. * not yet been written. Since the time is outside the
  1380. * capture range, the clock is stepped. The frequency
  1381. * will be set directly following the stepout interval.
  1382. *
  1383. * In FSET state the initial frequency has been set
  1384. * from the frequency file. Since the time is outside
  1385. * the capture range, the clock is stepped immediately,
  1386. * rather than after the stepout interval. Guys get
  1387. * nervous if it takes 17 minutes to set the clock for
  1388. * the first time.
  1389. *
  1390. * In SPIK state the stepout threshold has expired and
  1391. * the phase is still above the step threshold. Note
  1392. * that a single spike greater than the step threshold
  1393. * is always suppressed, even at the longer poll
  1394. * intervals.
  1395. */
  1396. VERB4 bb_error_msg("stepping time by %+f; poll_exp=MINPOLL", offset);
  1397. step_time(offset);
  1398. if (option_mask32 & OPT_q) {
  1399. /* We were only asked to set time once. Done. */
  1400. exit(0);
  1401. }
  1402. clamp_pollexp_and_set_MAXSTRAT();
  1403. run_script("step", offset);
  1404. recv_time += offset;
  1405. abs_offset = offset = 0;
  1406. set_new_values(offset, recv_time);
  1407. } else { /* abs_offset <= STEP_THRESHOLD */
  1408. if (option_mask32 & OPT_q) {
  1409. /* We were only asked to set time once.
  1410. * The clock is precise enough, no need to step.
  1411. */
  1412. exit(0);
  1413. }
  1414. /* The ratio is calculated before jitter is updated to make
  1415. * poll adjust code more sensitive to large offsets.
  1416. */
  1417. G.offset_to_jitter_ratio = abs_offset / G.discipline_jitter;
  1418. /* Compute the clock jitter as the RMS of exponentially
  1419. * weighted offset differences. Used by the poll adjust code.
  1420. */
  1421. etemp = SQUARE(G.discipline_jitter);
  1422. dtemp = SQUARE(offset - G.last_update_offset);
  1423. G.discipline_jitter = SQRT(etemp + (dtemp - etemp) / AVG);
  1424. if (G.discipline_jitter < G_precision_sec)
  1425. G.discipline_jitter = G_precision_sec;
  1426. #if !USING_KERNEL_PLL_LOOP
  1427. /* Compute freq_drift due to PLL and FLL contributions.
  1428. *
  1429. * The FLL and PLL frequency gain constants
  1430. * depend on the poll interval and Allan
  1431. * intercept. The FLL is not used below one-half
  1432. * the Allan intercept. Above that the loop gain
  1433. * increases in steps to 1 / AVG.
  1434. */
  1435. if ((1 << G.poll_exp) > ALLAN / 2) {
  1436. etemp = FLL - G.poll_exp;
  1437. if (etemp < AVG)
  1438. etemp = AVG;
  1439. freq_drift += (offset - G.last_update_offset) / (MAXD(since_last_update, ALLAN) * etemp);
  1440. }
  1441. /* For the PLL the integration interval
  1442. * (numerator) is the minimum of the update
  1443. * interval and poll interval. This allows
  1444. * oversampling, but not undersampling.
  1445. */
  1446. etemp = MIND(since_last_update, (1 << G.poll_exp));
  1447. dtemp = (4 * PLL) << G.poll_exp;
  1448. freq_drift += offset * etemp / SQUARE(dtemp);
  1449. #endif
  1450. set_new_values(offset, recv_time);
  1451. if (G.stratum != p->lastpkt_stratum + 1) {
  1452. G.stratum = p->lastpkt_stratum + 1;
  1453. run_script("stratum", offset);
  1454. }
  1455. }
  1456. G.reftime = G.cur_time;
  1457. G.ntp_status = p->lastpkt_status;
  1458. #if ENABLE_FEATURE_NTPD_SERVER
  1459. /* Our current refid is the IPv4 (or md5-hashed IPv6) address of the peer we took time from: */
  1460. G.refid = p->p_refid;
  1461. #endif
  1462. G.rootdelay = p->lastpkt_rootdelay + p->lastpkt_delay;
  1463. dtemp = p->filter_jitter; // SQRT(SQUARE(p->filter_jitter) + SQUARE(G.cluster_jitter));
  1464. dtemp += MAXD(p->filter_dispersion + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time) + abs_offset, MINDISP);
  1465. G.rootdisp = p->lastpkt_rootdisp + dtemp;
  1466. VERB4 bb_error_msg("updating leap/refid/reftime/rootdisp from peer %s", p->p_dotted);
  1467. /* By this time, freq_drift and offset are set
  1468. * to values suitable for adjtimex.
  1469. */
  1470. #if !USING_KERNEL_PLL_LOOP
  1471. /* Calculate the new frequency drift and frequency stability (wander).
  1472. * Compute the clock wander as the RMS of exponentially weighted
  1473. * frequency differences. This is not used directly, but can,
  1474. * along with the jitter, be a highly useful monitoring and
  1475. * debugging tool.
  1476. */
  1477. dtemp = G.discipline_freq_drift + freq_drift;
  1478. G.discipline_freq_drift = MAXD(MIND(MAXDRIFT, dtemp), -MAXDRIFT);
  1479. etemp = SQUARE(G.discipline_wander);
  1480. dtemp = SQUARE(dtemp);
  1481. G.discipline_wander = SQRT(etemp + (dtemp - etemp) / AVG);
  1482. VERB4 bb_error_msg("discipline freq_drift=%.9f(int:%ld corr:%e) wander=%f",
  1483. G.discipline_freq_drift,
  1484. (long)(G.discipline_freq_drift * 65536e6),
  1485. freq_drift,
  1486. G.discipline_wander);
  1487. #endif
  1488. VERB4 {
  1489. memset(&tmx, 0, sizeof(tmx));
  1490. if (adjtimex(&tmx) < 0)
  1491. bb_simple_perror_msg_and_die("adjtimex");
  1492. bb_error_msg("p adjtimex freq:%ld offset:%+ld status:0x%x tc:%ld",
  1493. tmx.freq, tmx.offset, tmx.status, tmx.constant);
  1494. }
  1495. memset(&tmx, 0, sizeof(tmx));
  1496. #if 0
  1497. //doesn't work, offset remains 0 (!) in kernel:
  1498. //ntpd: set adjtimex freq:1786097 tmx.offset:77487
  1499. //ntpd: prev adjtimex freq:1786097 tmx.offset:0
  1500. //ntpd: cur adjtimex freq:1786097 tmx.offset:0
  1501. tmx.modes = ADJ_FREQUENCY | ADJ_OFFSET;
  1502. /* 65536 is one ppm */
  1503. tmx.freq = G.discipline_freq_drift * 65536e6;
  1504. #endif
  1505. tmx.modes = ADJ_OFFSET | ADJ_STATUS | ADJ_TIMECONST;// | ADJ_MAXERROR | ADJ_ESTERROR;
  1506. tmx.offset = (long)(offset * 1000000); /* usec */
  1507. if (SLEW_THRESHOLD < STEP_THRESHOLD) {
  1508. if (tmx.offset > (long)(SLEW_THRESHOLD * 1000000)) {
  1509. tmx.offset = (long)(SLEW_THRESHOLD * 1000000);
  1510. }
  1511. if (tmx.offset < -(long)(SLEW_THRESHOLD * 1000000)) {
  1512. tmx.offset = -(long)(SLEW_THRESHOLD * 1000000);
  1513. }
  1514. }
  1515. tmx.status = STA_PLL;
  1516. if (G.FREQHOLD_cnt != 0) {
  1517. /* man adjtimex on STA_FREQHOLD:
  1518. * "Normally adjustments made via ADJ_OFFSET result in dampened
  1519. * frequency adjustments also being made.
  1520. * This flag prevents the small frequency adjustment from being
  1521. * made when correcting for an ADJ_OFFSET value."
  1522. *
  1523. * Use this flag for a few first adjustments at the beginning
  1524. * of ntpd execution, otherwise even relatively small initial
  1525. * offset tend to cause largish changes to in-kernel tmx.freq.
  1526. * If ntpd was restarted due to e.g. switch to another network,
  1527. * this destroys already well-established tmx.freq value.
  1528. */
  1529. if (G.FREQHOLD_cnt < 0) {
  1530. /* Initialize it */
  1531. // Example: a laptop whose clock runs slower when hibernated,
  1532. // after wake up it still has good tmx.freq, but accumulated ~0.5 sec offset:
  1533. // Run with code where initial G.FREQHOLD_cnt was always 8:
  1534. //15:17:52.947 no valid datapoints, no peer selected
  1535. //15:17:56.515 update from:<IP> offset:+0.485133 delay:0.157762 jitter:0.209310 clock drift:-1.393ppm tc:4
  1536. //15:17:57.719 update from:<IP> offset:+0.483825 delay:0.158070 jitter:0.181159 clock drift:-1.393ppm tc:4
  1537. //15:17:59.925 update from:<IP> offset:+0.479504 delay:0.158147 jitter:0.156657 clock drift:-1.393ppm tc:4
  1538. //15:18:33.322 update from:<IP> offset:+0.428119 delay:0.158317 jitter:0.138071 clock drift:-1.393ppm tc:4
  1539. //15:19:06.718 update from:<IP> offset:+0.376932 delay:0.158276 jitter:0.122075 clock drift:-1.393ppm tc:4
  1540. //15:19:39.114 update from:<IP> offset:+0.327022 delay:0.158384 jitter:0.108538 clock drift:-1.393ppm tc:4
  1541. //15:20:12.715 update from:<IP> offset:+0.275596 delay:0.158297 jitter:0.097292 clock drift:-1.393ppm tc:4
  1542. //15:20:45.111 update from:<IP> offset:+0.225715 delay:0.158271 jitter:0.087841 clock drift:-1.393ppm tc:4
  1543. // If allowed to continue, it would start increasing tmx.freq now.
  1544. // Instead, it was ^Ced, and started anew:
  1545. //15:21:15.043 no valid datapoints, no peer selected
  1546. //15:21:17.408 update from:<IP> offset:+0.175910 delay:0.158314 jitter:0.076683 clock drift:-1.393ppm tc:4
  1547. //15:21:19.774 update from:<IP> offset:+0.171784 delay:0.158401 jitter:0.066436 clock drift:-1.393ppm tc:4
  1548. //15:21:22.140 update from:<IP> offset:+0.171660 delay:0.158592 jitter:0.057536 clock drift:-1.393ppm tc:4
  1549. //15:21:22.140 update from:<IP> offset:+0.167126 delay:0.158507 jitter:0.049792 clock drift:-1.393ppm tc:4
  1550. //15:21:55.696 update from:<IP> offset:+0.115223 delay:0.158277 jitter:0.050240 clock drift:-1.393ppm tc:4
  1551. //15:22:29.093 update from:<IP> offset:+0.068051 delay:0.158243 jitter:0.049405 clock drift:-1.393ppm tc:5
  1552. //15:23:02.490 update from:<IP> offset:+0.051632 delay:0.158215 jitter:0.043545 clock drift:-1.393ppm tc:5
  1553. //15:23:34.726 update from:<IP> offset:+0.039984 delay:0.158157 jitter:0.038106 clock drift:-1.393ppm tc:5
  1554. // STA_FREQHOLD no longer set, started increasing tmx.freq now:
  1555. //15:24:06.961 update from:<IP> offset:+0.030968 delay:0.158190 jitter:0.033306 clock drift:+2.387ppm tc:5
  1556. //15:24:40.357 update from:<IP> offset:+0.023648 delay:0.158211 jitter:0.029072 clock drift:+5.454ppm tc:5
  1557. //15:25:13.774 update from:<IP> offset:+0.018068 delay:0.157660 jitter:0.025288 clock drift:+7.728ppm tc:5
  1558. //15:26:19.173 update from:<IP> offset:+0.010057 delay:0.157969 jitter:0.022255 clock drift:+8.361ppm tc:6
  1559. //15:27:26.602 update from:<IP> offset:+0.006737 delay:0.158103 jitter:0.019316 clock drift:+8.792ppm tc:6
  1560. //15:28:33.030 update from:<IP> offset:+0.004513 delay:0.158294 jitter:0.016765 clock drift:+9.080ppm tc:6
  1561. //15:29:40.617 update from:<IP> offset:+0.002787 delay:0.157745 jitter:0.014543 clock drift:+9.258ppm tc:6
  1562. //15:30:47.045 update from:<IP> offset:+0.001324 delay:0.157709 jitter:0.012594 clock drift:+9.342ppm tc:6
  1563. //15:31:53.473 update from:<IP> offset:+0.000007 delay:0.158142 jitter:0.010922 clock drift:+9.343ppm tc:6
  1564. //15:32:58.902 update from:<IP> offset:-0.000728 delay:0.158222 jitter:0.009454 clock drift:+9.298ppm tc:6
  1565. /*
  1566. * This expression would choose MIN_FREQHOLD + 14 in the above example
  1567. * (off_032 is +1 for each 0.032768 seconds of offset).
  1568. */
  1569. unsigned off_032 = abs((int)(tmx.offset >> 15));
  1570. G.FREQHOLD_cnt = 1 + MIN_FREQHOLD + off_032;
  1571. }
  1572. G.FREQHOLD_cnt--;
  1573. tmx.status |= STA_FREQHOLD;
  1574. }
  1575. if (G.ntp_status & LI_PLUSSEC)
  1576. tmx.status |= STA_INS;
  1577. if (G.ntp_status & LI_MINUSSEC)
  1578. tmx.status |= STA_DEL;
  1579. tmx.constant = (int)G.poll_exp - 4;
  1580. /* EXPERIMENTAL.
  1581. * The below if statement should be unnecessary, but...
  1582. * It looks like Linux kernel's PLL is far too gentle in changing
  1583. * tmx.freq in response to clock offset. Offset keeps growing
  1584. * and eventually we fall back to smaller poll intervals.
  1585. * We can make correction more aggressive (about x2) by supplying
  1586. * PLL time constant which is one less than the real one.
  1587. * To be on a safe side, let's do it only if offset is significantly
  1588. * larger than jitter.
  1589. */
  1590. if (G.offset_to_jitter_ratio >= TIMECONST_HACK_GATE)
  1591. tmx.constant--;
  1592. if (tmx.constant < 0)
  1593. tmx.constant = 0;
  1594. //tmx.esterror = (uint32_t)(clock_jitter * 1e6);
  1595. //tmx.maxerror = (uint32_t)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
  1596. rc = adjtimex(&tmx);
  1597. if (rc < 0)
  1598. bb_simple_perror_msg_and_die("adjtimex");
  1599. /* NB: here kernel returns constant == G.poll_exp, not == G.poll_exp - 4.
  1600. * Not sure why. Perhaps it is normal.
  1601. */
  1602. VERB4 bb_error_msg("adjtimex:%d freq:%ld offset:%+ld status:0x%x",
  1603. rc, tmx.freq, tmx.offset, tmx.status);
  1604. G.kernel_freq_drift = tmx.freq / 65536;
  1605. VERB2 bb_error_msg("update from:%s offset:%+f delay:%f jitter:%f clock drift:%+.3fppm tc:%d",
  1606. p->p_dotted,
  1607. offset,
  1608. p->p_raw_delay,
  1609. G.discipline_jitter,
  1610. (double)tmx.freq / 65536,
  1611. (int)tmx.constant
  1612. );
  1613. return 1; /* "ok to increase poll interval" */
  1614. }
  1615. /*
  1616. * We've got a new reply packet from a peer, process it
  1617. * (helpers first)
  1618. */
  1619. static unsigned
  1620. poll_interval(int upper_bound)
  1621. {
  1622. unsigned interval, r, mask;
  1623. interval = 1 << G.poll_exp;
  1624. if (interval > upper_bound)
  1625. interval = upper_bound;
  1626. mask = ((interval-1) >> 4) | 1;
  1627. r = rand();
  1628. interval += r & mask; /* ~ random(0..1) * interval/16 */
  1629. VERB4 bb_error_msg("chose poll interval:%u (poll_exp:%d)", interval, G.poll_exp);
  1630. return interval;
  1631. }
  1632. static void
  1633. adjust_poll(int count)
  1634. {
  1635. G.polladj_count += count;
  1636. if (G.polladj_count > POLLADJ_LIMIT) {
  1637. G.polladj_count = 0;
  1638. if (G.poll_exp < MAXPOLL) {
  1639. G.poll_exp++;
  1640. VERB4 bb_error_msg("polladj: discipline_jitter:%f ++poll_exp=%d",
  1641. G.discipline_jitter, G.poll_exp);
  1642. }
  1643. } else if (G.polladj_count < -POLLADJ_LIMIT || (count < 0 && G.poll_exp > BIGPOLL)) {
  1644. G.polladj_count = 0;
  1645. if (G.poll_exp > MINPOLL) {
  1646. llist_t *item;
  1647. G.poll_exp--;
  1648. /* Correct p->next_action_time in each peer
  1649. * which waits for sending, so that they send earlier.
  1650. * Old pp->next_action_time are on the order
  1651. * of t + (1 << old_poll_exp) + small_random,
  1652. * we simply need to subtract ~half of that.
  1653. */
  1654. for (item = G.ntp_peers; item != NULL; item = item->link) {
  1655. peer_t *pp = (peer_t *) item->data;
  1656. if (pp->p_fd < 0)
  1657. pp->next_action_time -= (1 << G.poll_exp);
  1658. }
  1659. VERB4 bb_error_msg("polladj: discipline_jitter:%f --poll_exp=%d",
  1660. G.discipline_jitter, G.poll_exp);
  1661. }
  1662. } else {
  1663. VERB4 bb_error_msg("polladj: count:%d", G.polladj_count);
  1664. }
  1665. }
  1666. static NOINLINE void
  1667. recv_and_process_peer_pkt(peer_t *p)
  1668. {
  1669. int rc;
  1670. ssize_t size;
  1671. msg_t msg;
  1672. double T1, T2, T3, T4;
  1673. double offset;
  1674. double prev_delay, delay;
  1675. unsigned interval;
  1676. datapoint_t *datapoint;
  1677. peer_t *q;
  1678. offset = 0;
  1679. /* The below can happen as follows:
  1680. * = we receive two peer rsponses at once.
  1681. * = recv_and_process_peer_pkt(PEER1) -> update_local_clock()
  1682. * -> step_time() and it closes all other fds, sets all ->fd to -1.
  1683. * = recv_and_process_peer_pkt(PEER2) sees PEER2->fd == -1
  1684. */
  1685. if (p->p_fd < 0)
  1686. return;
  1687. /* We can recvfrom here and check from.IP, but some multihomed
  1688. * ntp servers reply from their *other IP*.
  1689. * TODO: maybe we should check at least what we can: from.port == 123?
  1690. */
  1691. recv_again:
  1692. size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
  1693. if (size < 0) {
  1694. if (errno == EINTR)
  1695. /* Signal caught */
  1696. goto recv_again;
  1697. if (errno == EAGAIN)
  1698. /* There was no packet after all
  1699. * (poll() returning POLLIN for a fd
  1700. * is not a ironclad guarantee that data is there)
  1701. */
  1702. return;
  1703. /*
  1704. * If you need a different handling for a specific
  1705. * errno, always explain it in comment.
  1706. */
  1707. bb_perror_msg_and_die("recv(%s) error", p->p_dotted);
  1708. }
  1709. #if ENABLE_FEATURE_NTP_AUTH
  1710. if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH && size != NTP_MSGSIZE_SHA1_AUTH) {
  1711. bb_error_msg("malformed packet received from %s: size %u", p->p_dotted, (int)size);
  1712. return;
  1713. }
  1714. if (p->key_entry && hashes_differ(p, &msg)) {
  1715. bb_error_msg("invalid cryptographic hash received from %s", p->p_dotted);
  1716. return;
  1717. }
  1718. #else
  1719. if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH) {
  1720. bb_error_msg("malformed packet received from %s: size %u", p->p_dotted, (int)size);
  1721. return;
  1722. }
  1723. #endif
  1724. if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
  1725. || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
  1726. ) {
  1727. /* Somebody else's packet */
  1728. return;
  1729. }
  1730. /* We do not expect any more packets from this peer for now.
  1731. * Closing the socket informs kernel about it.
  1732. * We open a new socket when we send a new query.
  1733. */
  1734. close(p->p_fd);
  1735. p->p_fd = -1;
  1736. if ((msg.m_status & LI_ALARM) == LI_ALARM
  1737. || msg.m_stratum == 0
  1738. || msg.m_stratum > NTP_MAXSTRATUM
  1739. ) {
  1740. bb_error_msg("reply from %s: peer is unsynced", p->p_dotted);
  1741. /*
  1742. * Stratum 0 responses may have commands in 32-bit m_refid field:
  1743. * "DENY", "RSTR" - peer does not like us at all,
  1744. * "RATE" - peer is overloaded, reduce polling freq.
  1745. * If poll interval is small, increase it.
  1746. */
  1747. if (G.poll_exp < BIGPOLL)
  1748. goto increase_interval;
  1749. goto pick_normal_interval;
  1750. }
  1751. // /* Verify valid root distance */
  1752. // if (msg.m_rootdelay / 2 + msg.m_rootdisp >= MAXDISP || p->lastpkt_reftime > msg.m_xmt)
  1753. // return; /* invalid header values */
  1754. /*
  1755. * From RFC 2030 (with a correction to the delay math):
  1756. *
  1757. * Timestamp Name ID When Generated
  1758. * ------------------------------------------------------------
  1759. * Originate Timestamp T1 time request sent by client
  1760. * Receive Timestamp T2 time request received by server
  1761. * Transmit Timestamp T3 time reply sent by server
  1762. * Destination Timestamp T4 time reply received by client
  1763. *
  1764. * The roundtrip delay and local clock offset are defined as
  1765. *
  1766. * delay = (T4 - T1) - (T3 - T2); offset = ((T2 - T1) + (T3 - T4)) / 2
  1767. */
  1768. T1 = p->p_xmttime;
  1769. T2 = lfp_to_d(msg.m_rectime);
  1770. T3 = lfp_to_d(msg.m_xmttime);
  1771. T4 = G.cur_time;
  1772. delay = (T4 - T1) - (T3 - T2);
  1773. /*
  1774. * If this packet's delay is much bigger than the last one,
  1775. * it's better to just ignore it than use its much less precise value.
  1776. */
  1777. prev_delay = p->p_raw_delay;
  1778. p->p_raw_delay = (delay < 0 ? 0.0 : delay);
  1779. if (p->reachable_bits
  1780. && delay > prev_delay * BAD_DELAY_GROWTH
  1781. && delay > 1.0 / (8 * 1024) /* larger than ~0.000122 */
  1782. ) {
  1783. bb_error_msg("reply from %s: delay %f is too high, ignoring", p->p_dotted, delay);
  1784. goto pick_normal_interval;
  1785. }
  1786. /* The delay calculation is a special case. In cases where the
  1787. * server and client clocks are running at different rates and
  1788. * with very fast networks, the delay can appear negative. In
  1789. * order to avoid violating the Principle of Least Astonishment,
  1790. * the delay is clamped not less than the system precision.
  1791. */
  1792. if (delay < G_precision_sec)
  1793. delay = G_precision_sec;
  1794. p->lastpkt_delay = delay;
  1795. p->lastpkt_recv_time = T4;
  1796. VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
  1797. p->lastpkt_status = msg.m_status;
  1798. p->lastpkt_stratum = msg.m_stratum;
  1799. p->lastpkt_rootdelay = sfp_to_d(msg.m_rootdelay);
  1800. p->lastpkt_rootdisp = sfp_to_d(msg.m_rootdisp);
  1801. p->lastpkt_refid = msg.m_refid;
  1802. p->datapoint_idx = p->reachable_bits ? (p->datapoint_idx + 1) % NUM_DATAPOINTS : 0;
  1803. datapoint = &p->filter_datapoint[p->datapoint_idx];
  1804. datapoint->d_recv_time = T4;
  1805. datapoint->d_offset = offset = ((T2 - T1) + (T3 - T4)) / 2;
  1806. datapoint->d_dispersion = LOG2D(msg.m_precision_exp) + G_precision_sec;
  1807. if (!p->reachable_bits) {
  1808. /* 1st datapoint ever - replicate offset in every element */
  1809. int i;
  1810. for (i = 0; i < NUM_DATAPOINTS; i++) {
  1811. p->filter_datapoint[i].d_offset = offset;
  1812. }
  1813. }
  1814. p->reachable_bits |= 1;
  1815. if ((MAX_VERBOSE && G.verbose) || (option_mask32 & OPT_w)) {
  1816. bb_info_msg("reply from %s: offset:%+f delay:%f status:0x%02x strat:%d refid:0x%08x rootdelay:%f reach:0x%02x",
  1817. p->p_dotted,
  1818. offset,
  1819. p->p_raw_delay,
  1820. p->lastpkt_status,
  1821. p->lastpkt_stratum,
  1822. p->lastpkt_refid,
  1823. p->lastpkt_rootdelay,
  1824. p->reachable_bits
  1825. /* not shown: m_ppoll, m_precision_exp, m_rootdisp,
  1826. * m_reftime, m_orgtime, m_rectime, m_xmttime
  1827. */
  1828. );
  1829. }
  1830. /* Muck with statictics and update the clock */
  1831. filter_datapoints(p);
  1832. q = select_and_cluster();
  1833. rc = 0;
  1834. if (q) {
  1835. if (!(option_mask32 & OPT_w)) {
  1836. rc = update_local_clock(q);
  1837. #if 0
  1838. //Disabled this because there is a case where largish offsets
  1839. //are unavoidable: if network round-trip delay is, say, ~0.6s,
  1840. //error in offset estimation would be ~delay/2 ~= 0.3s.
  1841. //Thus, offsets will be usually in -0.3...0.3s range.
  1842. //In this case, this code would keep poll interval small,
  1843. //but it won't be helping.
  1844. //BIGOFF check below deals with a case of seeing multi-second offsets.
  1845. /* If drift is dangerously large, immediately
  1846. * drop poll interval one step down.
  1847. */
  1848. if (fabs(q->filter_offset) >= POLLDOWN_OFFSET) {
  1849. VERB4 bb_error_msg("offset:%+f > POLLDOWN_OFFSET", q->filter_offset);
  1850. adjust_poll(-POLLADJ_LIMIT * 3);
  1851. rc = 0;
  1852. }
  1853. #endif
  1854. }
  1855. } else {
  1856. /* No peer selected.
  1857. * If poll interval is small, increase it.
  1858. */
  1859. if (G.poll_exp < BIGPOLL)
  1860. goto increase_interval;
  1861. }
  1862. if (rc != 0) {
  1863. /* Adjust the poll interval by comparing the current offset
  1864. * with the clock jitter. If the offset is less than
  1865. * the clock jitter times a constant, then the averaging interval
  1866. * is increased, otherwise it is decreased. A bit of hysteresis
  1867. * helps calm the dance. Works best using burst mode.
  1868. */
  1869. if (rc > 0 && G.offset_to_jitter_ratio <= POLLADJ_GATE) {
  1870. /* was += G.poll_exp but it is a bit
  1871. * too optimistic for my taste at high poll_exp's */
  1872. increase_interval:
  1873. adjust_poll(MINPOLL);
  1874. } else {
  1875. VERB3 if (rc > 0)
  1876. bb_error_msg("want smaller interval: offset/jitter = %u",
  1877. G.offset_to_jitter_ratio);
  1878. adjust_poll(-G.poll_exp * 2);
  1879. }
  1880. }
  1881. /* Decide when to send new query for this peer */
  1882. pick_normal_interval:
  1883. interval = poll_interval(INT_MAX);
  1884. if (fabs(offset) >= BIGOFF && interval > BIGOFF_INTERVAL) {
  1885. /* If we are synced, offsets are less than SLEW_THRESHOLD,
  1886. * or at the very least not much larger than it.
  1887. * Now we see a largish one.
  1888. * Either this peer is feeling bad, or packet got corrupted,
  1889. * or _our_ clock is wrong now and _all_ peers will show similar
  1890. * largish offsets too.
  1891. * I observed this with laptop suspend stopping clock.
  1892. * In any case, it makes sense to make next request soonish:
  1893. * cases 1 and 2: get a better datapoint,
  1894. * case 3: allows to resync faster.
  1895. */
  1896. interval = BIGOFF_INTERVAL;
  1897. }
  1898. set_next(p, interval);
  1899. }
  1900. #if ENABLE_FEATURE_NTPD_SERVER
  1901. static NOINLINE void
  1902. recv_and_process_client_pkt(void /*int fd*/)
  1903. {
  1904. ssize_t size;
  1905. //uint8_t version;
  1906. len_and_sockaddr *to;
  1907. struct sockaddr *from;
  1908. msg_t msg;
  1909. uint8_t query_status;
  1910. l_fixedpt_t query_xmttime;
  1911. to = get_sock_lsa(G_listen_fd);
  1912. from = xzalloc(to->len);
  1913. size = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
  1914. /* "ntpq -p" (4.2.8p13) sends a 12-byte NTPv2 request:
  1915. * m_status is 0x16: leap:0 version:2 mode:6(reserved1)
  1916. * https://docs.ntpsec.org/latest/mode6.html
  1917. * We don't support this.
  1918. */
  1919. # if ENABLE_FEATURE_NTP_AUTH
  1920. if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH && size != NTP_MSGSIZE_SHA1_AUTH)
  1921. # else
  1922. if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH)
  1923. # endif
  1924. {
  1925. char *addr;
  1926. if (size < 0) {
  1927. if (errno == EAGAIN)
  1928. goto bail;
  1929. bb_simple_perror_msg_and_die("recv");
  1930. }
  1931. addr = xmalloc_sockaddr2dotted_noport(from);
  1932. bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
  1933. free(addr);
  1934. goto bail;
  1935. }
  1936. /* Respond only to client and symmetric active packets */
  1937. if ((msg.m_status & MODE_MASK) != MODE_CLIENT
  1938. && (msg.m_status & MODE_MASK) != MODE_SYM_ACT
  1939. ) {
  1940. goto bail;
  1941. }
  1942. query_status = msg.m_status;
  1943. query_xmttime = msg.m_xmttime;
  1944. /* Build a reply packet */
  1945. memset(&msg, 0, sizeof(msg));
  1946. msg.m_status = G.stratum < MAXSTRAT ? (G.ntp_status & LI_MASK) : LI_ALARM;
  1947. msg.m_status |= (query_status & VERSION_MASK);
  1948. msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
  1949. MODE_SERVER : MODE_SYM_PAS;
  1950. msg.m_stratum = G.stratum;
  1951. msg.m_ppoll = G.poll_exp;
  1952. msg.m_precision_exp = G_precision_exp;
  1953. /* this time was obtained between poll() and recv() */
  1954. d_to_lfp(&msg.m_rectime, G.cur_time);
  1955. d_to_lfp(&msg.m_xmttime, gettime1900d()); /* this instant */
  1956. if (G.peer_cnt == 0) {
  1957. /* we have no peers: "stratum 1 server" mode. reftime = our own time */
  1958. G.reftime = G.cur_time;
  1959. }
  1960. d_to_lfp(&msg.m_reftime, G.reftime);
  1961. msg.m_orgtime = query_xmttime;
  1962. d_to_sfp(&msg.m_rootdelay, G.rootdelay);
  1963. //simple code does not do this, fix simple code!
  1964. d_to_sfp(&msg.m_rootdisp, G.rootdisp);
  1965. //version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
  1966. msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;
  1967. /* We reply from the local address packet was sent to,
  1968. * this makes to/from look swapped here: */
  1969. do_sendto(G_listen_fd,
  1970. /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
  1971. &msg, size);
  1972. VERB3 {
  1973. char *addr;
  1974. addr = xmalloc_sockaddr2dotted_noport(from);
  1975. bb_error_msg("responded to query from %s", addr);
  1976. free(addr);
  1977. }
  1978. bail:
  1979. free(to);
  1980. free(from);
  1981. }
  1982. #endif
  1983. /* Upstream ntpd's options:
  1984. *
  1985. * -4 Force DNS resolution of host names to the IPv4 namespace.
  1986. * -6 Force DNS resolution of host names to the IPv6 namespace.
  1987. * -a Require cryptographic authentication for broadcast client,
  1988. * multicast client and symmetric passive associations.
  1989. * This is the default.
  1990. * -A Do not require cryptographic authentication for broadcast client,
  1991. * multicast client and symmetric passive associations.
  1992. * This is almost never a good idea.
  1993. * -b Enable the client to synchronize to broadcast servers.
  1994. * -c conffile
  1995. * Specify the name and path of the configuration file,
  1996. * default /etc/ntp.conf
  1997. * -d Specify debugging mode. This option may occur more than once,
  1998. * with each occurrence indicating greater detail of display.
  1999. * -D level
  2000. * Specify debugging level directly.
  2001. * -f driftfile
  2002. * Specify the name and path of the frequency file.
  2003. * This is the same operation as the "driftfile FILE"
  2004. * configuration command.
  2005. * -g Normally, ntpd exits with a message to the system log
  2006. * if the offset exceeds the panic threshold, which is 1000 s
  2007. * by default. This option allows the time to be set to any value
  2008. * without restriction; however, this can happen only once.
  2009. * If the threshold is exceeded after that, ntpd will exit
  2010. * with a message to the system log. This option can be used
  2011. * with the -q and -x options. See the tinker command for other options.
  2012. * -i jaildir
  2013. * Chroot the server to the directory jaildir. This option also implies
  2014. * that the server attempts to drop root privileges at startup
  2015. * (otherwise, chroot gives very little additional security).
  2016. * You may need to also specify a -u option.
  2017. * -k keyfile
  2018. * Specify the name and path of the symmetric key file,
  2019. * default /etc/ntp/keys. This is the same operation
  2020. * as the "keys FILE" configuration command.
  2021. * -l logfile
  2022. * Specify the name and path of the log file. The default
  2023. * is the system log file. This is the same operation as
  2024. * the "logfile FILE" configuration command.
  2025. * -L Do not listen to virtual IPs. The default is to listen.
  2026. * -n Don't fork.
  2027. * -N To the extent permitted by the operating system,
  2028. * run the ntpd at the highest priority.
  2029. * -p pidfile
  2030. * Specify the name and path of the file used to record the ntpd
  2031. * process ID. This is the same operation as the "pidfile FILE"
  2032. * configuration command.
  2033. * -P priority
  2034. * To the extent permitted by the operating system,
  2035. * run the ntpd at the specified priority.
  2036. * -q Exit the ntpd just after the first time the clock is set.
  2037. * This behavior mimics that of the ntpdate program, which is
  2038. * to be retired. The -g and -x options can be used with this option.
  2039. * Note: The kernel time discipline is disabled with this option.
  2040. * -r broadcastdelay
  2041. * Specify the default propagation delay from the broadcast/multicast
  2042. * server to this client. This is necessary only if the delay
  2043. * cannot be computed automatically by the protocol.
  2044. * -s statsdir
  2045. * Specify the directory path for files created by the statistics
  2046. * facility. This is the same operation as the "statsdir DIR"
  2047. * configuration command.
  2048. * -t key
  2049. * Add a key number to the trusted key list. This option can occur
  2050. * more than once.
  2051. * -u user[:group]
  2052. * Specify a user, and optionally a group, to switch to.
  2053. * -v variable
  2054. * -V variable
  2055. * Add a system variable listed by default.
  2056. * -x Normally, the time is slewed if the offset is less than the step
  2057. * threshold, which is 128 ms by default, and stepped if above
  2058. * the threshold. This option sets the threshold to 600 s, which is
  2059. * well within the accuracy window to set the clock manually.
  2060. * Note: since the slew rate of typical Unix kernels is limited
  2061. * to 0.5 ms/s, each second of adjustment requires an amortization
  2062. * interval of 2000 s. Thus, an adjustment as much as 600 s
  2063. * will take almost 14 days to complete. This option can be used
  2064. * with the -g and -q options. See the tinker command for other options.
  2065. * Note: The kernel time discipline is disabled with this option.
  2066. */
  2067. #if ENABLE_FEATURE_NTP_AUTH
  2068. static key_entry_t *
  2069. find_key_entry(llist_t *key_entries, unsigned id)
  2070. {
  2071. while (key_entries) {
  2072. key_entry_t *cur = (key_entry_t*) key_entries->data;
  2073. if (cur->id == id)
  2074. return cur;
  2075. key_entries = key_entries->link;
  2076. }
  2077. bb_error_msg_and_die("key %u is not defined", id);
  2078. }
  2079. #endif
  2080. /* By doing init in a separate function we decrease stack usage
  2081. * in main loop.
  2082. */
  2083. static NOINLINE void ntp_init(char **argv)
  2084. {
  2085. unsigned opts;
  2086. llist_t *peers;
  2087. #if ENABLE_FEATURE_NTP_AUTH
  2088. llist_t *key_entries;
  2089. char *key_file_path;
  2090. #endif
  2091. srand(getpid());
  2092. /* Set some globals */
  2093. G.discipline_jitter = G_precision_sec;
  2094. G.stratum = MAXSTRAT;
  2095. if (BURSTPOLL != 0)
  2096. G.poll_exp = BURSTPOLL; /* speeds up initial sync */
  2097. G.last_script_run = G.reftime = G.last_update_recv_time = gettime1900d(); /* sets G.cur_time too */
  2098. G.FREQHOLD_cnt = -1;
  2099. /* Parse options */
  2100. peers = NULL;
  2101. IF_FEATURE_NTP_AUTH(key_entries = NULL;)
  2102. opts = getopt32(argv, "^"
  2103. "nqNx" /* compat */
  2104. IF_FEATURE_NTP_AUTH("k:") /* compat */
  2105. "wp:*S:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
  2106. IF_FEATURE_NTPD_SERVER("I:") /* compat */
  2107. "d" /* compat */
  2108. "46aAbgL" /* compat, ignored */
  2109. "\0"
  2110. "=0" /* should have no arguments */
  2111. ":dd:wn" /* -d: counter; -p: list; -w implies -n */
  2112. IF_FEATURE_NTPD_SERVER(":Il") /* -I implies -l */
  2113. IF_FEATURE_NTP_AUTH(, &key_file_path)
  2114. , &peers, &G.script_name
  2115. IF_FEATURE_NTPD_SERVER(, &G.if_name)
  2116. , &G.verbose
  2117. );
  2118. // if (opts & OPT_x) /* disable stepping, only slew is allowed */
  2119. // G.time_was_stepped = 1;
  2120. #if ENABLE_FEATURE_NTPD_SERVER
  2121. G_listen_fd = -1;
  2122. if (opts & OPT_l) {
  2123. G_listen_fd = create_and_bind_dgram_or_die(NULL, 123);
  2124. if (G.if_name) {
  2125. if (setsockopt_bindtodevice(G_listen_fd, G.if_name))
  2126. xfunc_die();
  2127. }
  2128. socket_want_pktinfo(G_listen_fd);
  2129. setsockopt_int(G_listen_fd, IPPROTO_IP, IP_TOS, IPTOS_DSCP_AF21);
  2130. }
  2131. #endif
  2132. /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
  2133. if (opts & OPT_N)
  2134. setpriority(PRIO_PROCESS, 0, -15);
  2135. if (!(opts & OPT_n)) {
  2136. bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
  2137. logmode = LOGMODE_NONE;
  2138. }
  2139. #if ENABLE_FEATURE_NTP_AUTH
  2140. if (opts & OPT_k) {
  2141. char *tokens[4];
  2142. parser_t *parser;
  2143. parser = config_open(key_file_path);
  2144. while (config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL | PARSE_MIN_DIE) == 3) {
  2145. key_entry_t *key_entry;
  2146. char buffer[40];
  2147. smalluint hash_type;
  2148. smalluint msg_size;
  2149. smalluint key_length;
  2150. char *key;
  2151. if ((tokens[1][0] | 0x20) == 'm')
  2152. /* supports 'M' and 'md5' formats */
  2153. hash_type = HASH_MD5;
  2154. else
  2155. if (strncasecmp(tokens[1], "sha", 3) == 0)
  2156. /* supports 'sha' and 'sha1' formats */
  2157. hash_type = HASH_SHA1;
  2158. else
  2159. bb_simple_error_msg_and_die("only MD5 and SHA1 keys supported");
  2160. /* man ntp.keys:
  2161. * MD5 The key is 1 to 16 printable characters terminated by an EOL,
  2162. * whitespace, or a # (which is the "start of comment" character).
  2163. * SHA
  2164. * SHA1
  2165. * RMD160 The key is a hex-encoded ASCII string of 40 characters, which
  2166. * is truncated as necessary.
  2167. */
  2168. key_length = strnlen(tokens[2], sizeof(buffer)+1);
  2169. if (key_length >= sizeof(buffer)+1) {
  2170. err:
  2171. bb_error_msg_and_die("malformed key at line %u", parser->lineno);
  2172. }
  2173. if (hash_type == HASH_MD5) {
  2174. key = tokens[2];
  2175. msg_size = NTP_MSGSIZE_MD5_AUTH;
  2176. } else /* it's hash_type == HASH_SHA1 */
  2177. if (!(key_length & 1)) {
  2178. key_length >>= 1;
  2179. if (!hex2bin(buffer, tokens[2], key_length))
  2180. goto err;
  2181. key = buffer;
  2182. msg_size = NTP_MSGSIZE_SHA1_AUTH;
  2183. } else {
  2184. goto err;
  2185. }
  2186. key_entry = xzalloc(sizeof(*key_entry) + key_length);
  2187. key_entry->type = hash_type;
  2188. key_entry->msg_size = msg_size;
  2189. key_entry->key_length = key_length;
  2190. memcpy(key_entry->key, key, key_length);
  2191. key_entry->id = xatou_range(tokens[0], 1, MAX_KEY_NUMBER);
  2192. llist_add_to(&key_entries, key_entry);
  2193. }
  2194. config_close(parser);
  2195. }
  2196. #endif
  2197. if (peers) {
  2198. #if ENABLE_FEATURE_NTP_AUTH
  2199. while (peers) {
  2200. char *peer = llist_pop(&peers);
  2201. key_entry_t *key_entry = NULL;
  2202. if (strncmp(peer, "keyno:", 6) == 0) {
  2203. char *end;
  2204. int key_id;
  2205. peer += 6;
  2206. end = strchr(peer, ':');
  2207. if (!end) bb_show_usage();
  2208. *end = '\0';
  2209. key_id = xatou_range(peer, 1, MAX_KEY_NUMBER);
  2210. *end = ':';
  2211. key_entry = find_key_entry(key_entries, key_id);
  2212. peer = end + 1;
  2213. }
  2214. add_peers(peer, key_entry);
  2215. }
  2216. #else
  2217. while (peers)
  2218. add_peers(llist_pop(&peers), NULL);
  2219. #endif
  2220. }
  2221. #if ENABLE_FEATURE_NTPD_CONF
  2222. else {
  2223. parser_t *parser;
  2224. char *token[3 + 2*ENABLE_FEATURE_NTP_AUTH];
  2225. parser = config_open("/etc/ntp.conf");
  2226. while (config_read(parser, token, 3 + 2*ENABLE_FEATURE_NTP_AUTH, 1, "# \t", PARSE_NORMAL)) {
  2227. if (strcmp(token[0], "server") == 0 && token[1]) {
  2228. # if ENABLE_FEATURE_NTP_AUTH
  2229. key_entry_t *key_entry = NULL;
  2230. if (token[2] && token[3] && strcmp(token[2], "key") == 0) {
  2231. unsigned key_id = xatou_range(token[3], 1, MAX_KEY_NUMBER);
  2232. key_entry = find_key_entry(key_entries, key_id);
  2233. }
  2234. add_peers(token[1], key_entry);
  2235. # else
  2236. add_peers(token[1], NULL);
  2237. # endif
  2238. continue;
  2239. }
  2240. bb_error_msg("skipping %s:%u: unimplemented command '%s'",
  2241. "/etc/ntp.conf", parser->lineno, token[0]
  2242. );
  2243. }
  2244. config_close(parser);
  2245. }
  2246. #endif
  2247. if (G.peer_cnt == 0) {
  2248. if (!(opts & OPT_l))
  2249. bb_show_usage();
  2250. /* -l but no peers: "stratum 1 server" mode */
  2251. G.stratum = 1;
  2252. }
  2253. if (!(opts & OPT_n)) /* only if backgrounded: */
  2254. write_pidfile_std_path_and_ext("ntpd");
  2255. /* If network is up, syncronization occurs in ~10 seconds.
  2256. * We give "ntpd -q" 10 seconds to get first reply,
  2257. * then another 50 seconds to finish syncing.
  2258. *
  2259. * I tested ntpd 4.2.6p1 and apparently it never exits
  2260. * (will try forever), but it does not feel right.
  2261. * The goal of -q is to act like ntpdate: set time
  2262. * after a reasonably small period of polling, or fail.
  2263. */
  2264. if (opts & OPT_q) {
  2265. option_mask32 |= OPT_qq;
  2266. alarm(10);
  2267. }
  2268. bb_signals(0
  2269. | (1 << SIGTERM)
  2270. | (1 << SIGINT)
  2271. | (1 << SIGALRM)
  2272. , record_signo
  2273. );
  2274. bb_signals(0
  2275. | (1 << SIGPIPE)
  2276. | (1 << SIGCHLD)
  2277. , SIG_IGN
  2278. );
  2279. //TODO: free unused elements of key_entries?
  2280. }
  2281. int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
  2282. int ntpd_main(int argc UNUSED_PARAM, char **argv)
  2283. {
  2284. #undef G
  2285. struct globals G;
  2286. struct pollfd *pfd;
  2287. peer_t **idx2peer;
  2288. unsigned cnt;
  2289. memset(&G, 0, sizeof(G));
  2290. SET_PTR_TO_GLOBALS(&G);
  2291. ntp_init(argv);
  2292. /* If ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
  2293. cnt = G.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
  2294. idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
  2295. pfd = xzalloc(sizeof(pfd[0]) * cnt);
  2296. /* Countdown: we never sync before we sent INITIAL_SAMPLES+1
  2297. * packets to each peer.
  2298. * NB: if some peer is not responding, we may end up sending
  2299. * fewer packets to it and more to other peers.
  2300. * NB2: sync usually happens using INITIAL_SAMPLES packets,
  2301. * since last reply does not come back instantaneously.
  2302. */
  2303. cnt = G.peer_cnt * (INITIAL_SAMPLES + 1);
  2304. while (!bb_got_signal) {
  2305. llist_t *item;
  2306. unsigned i, j;
  2307. int nfds, timeout;
  2308. double nextaction;
  2309. /* Nothing between here and poll() blocks for any significant time */
  2310. nextaction = G.last_script_run + (11*60);
  2311. if (nextaction < G.cur_time + 1)
  2312. nextaction = G.cur_time + 1;
  2313. i = 0;
  2314. #if ENABLE_FEATURE_NTPD_SERVER
  2315. if (G_listen_fd != -1) {
  2316. pfd[0].fd = G_listen_fd;
  2317. pfd[0].events = POLLIN;
  2318. i++;
  2319. }
  2320. #endif
  2321. /* Pass over peer list, send requests, time out on receives */
  2322. for (item = G.ntp_peers; item != NULL; item = item->link) {
  2323. peer_t *p = (peer_t *) item->data;
  2324. if (p->next_action_time <= G.cur_time) {
  2325. if (p->p_fd == -1) {
  2326. /* Time to send new req */
  2327. if (--cnt == 0) {
  2328. VERB4 bb_simple_error_msg("disabling burst mode");
  2329. G.polladj_count = 0;
  2330. G.poll_exp = MINPOLL;
  2331. }
  2332. send_query_to_peer(p);
  2333. } else {
  2334. /* Timed out waiting for reply */
  2335. close(p->p_fd);
  2336. p->p_fd = -1;
  2337. /* If poll interval is small, increase it */
  2338. if (G.poll_exp < BIGPOLL)
  2339. adjust_poll(MINPOLL);
  2340. timeout = poll_interval(NOREPLY_INTERVAL);
  2341. bb_error_msg("timed out waiting for %s, reach 0x%02x, next query in %us",
  2342. p->p_dotted, p->reachable_bits, timeout);
  2343. /* What if don't see it because it changed its IP? */
  2344. if (p->reachable_bits == 0)
  2345. resolve_peer_hostname(p);
  2346. set_next(p, timeout);
  2347. }
  2348. }
  2349. if (p->next_action_time < nextaction)
  2350. nextaction = p->next_action_time;
  2351. if (p->p_fd >= 0) {
  2352. /* Wait for reply from this peer */
  2353. pfd[i].fd = p->p_fd;
  2354. pfd[i].events = POLLIN;
  2355. idx2peer[i] = p;
  2356. i++;
  2357. }
  2358. }
  2359. timeout = nextaction - G.cur_time;
  2360. if (timeout < 0)
  2361. timeout = 0;
  2362. timeout++; /* (nextaction - G.cur_time) rounds down, compensating */
  2363. /* Here we may block */
  2364. VERB3 {
  2365. if (i > (ENABLE_FEATURE_NTPD_SERVER && G_listen_fd != -1)) {
  2366. /* We wait for at least one reply.
  2367. * Poll for it, without wasting time for message.
  2368. * Since replies often come under 1 second, this also
  2369. * reduces clutter in logs.
  2370. */
  2371. nfds = poll(pfd, i, 1000);
  2372. if (nfds != 0)
  2373. goto did_poll;
  2374. if (--timeout <= 0)
  2375. goto did_poll;
  2376. }
  2377. bb_error_msg("poll:%us sockets:%u interval:%us", timeout, i, 1 << G.poll_exp);
  2378. }
  2379. nfds = poll(pfd, i, timeout * 1000);
  2380. did_poll:
  2381. gettime1900d(); /* sets G.cur_time */
  2382. if (nfds <= 0) {
  2383. double ct;
  2384. int dns_error;
  2385. if (bb_got_signal)
  2386. break; /* poll was interrupted by a signal */
  2387. if (G.cur_time - G.last_script_run > 11*60) {
  2388. /* Useful for updating battery-backed RTC and such */
  2389. run_script("periodic", G.last_update_offset);
  2390. gettime1900d(); /* sets G.cur_time */
  2391. }
  2392. /* Resolve peer names to IPs, if not resolved yet.
  2393. * We do it only when poll timed out:
  2394. * this way, we almost never overlap DNS resolution with
  2395. * "request-reply" packet round trip.
  2396. */
  2397. dns_error = 0;
  2398. ct = G.cur_time;
  2399. for (item = G.ntp_peers; item != NULL; item = item->link) {
  2400. peer_t *p = (peer_t *) item->data;
  2401. if (p->next_action_time <= ct && !p->p_lsa) {
  2402. /* This can take up to ~10 sec per each DNS query */
  2403. dns_error |= (!resolve_peer_hostname(p));
  2404. }
  2405. }
  2406. if (!dns_error)
  2407. goto check_unsync;
  2408. /* Set next time for those which are still not resolved */
  2409. gettime1900d(); /* sets G.cur_time (needed for set_next()) */
  2410. for (item = G.ntp_peers; item != NULL; item = item->link) {
  2411. peer_t *p = (peer_t *) item->data;
  2412. if (p->next_action_time <= ct && !p->p_lsa) {
  2413. set_next(p, HOSTNAME_INTERVAL * p->dns_errors);
  2414. }
  2415. }
  2416. goto check_unsync;
  2417. }
  2418. /* Process any received packets */
  2419. j = 0;
  2420. #if ENABLE_FEATURE_NTPD_SERVER
  2421. if (G.listen_fd != -1) {
  2422. if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
  2423. nfds--;
  2424. recv_and_process_client_pkt(/*G.listen_fd*/);
  2425. gettime1900d(); /* sets G.cur_time */
  2426. }
  2427. j = 1;
  2428. }
  2429. #endif
  2430. for (; nfds != 0 && j < i; j++) {
  2431. if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
  2432. /*
  2433. * At init, alarm was set to 10 sec.
  2434. * Now we did get a reply.
  2435. * Increase timeout to 50 seconds to finish syncing.
  2436. */
  2437. if (option_mask32 & OPT_qq) {
  2438. option_mask32 &= ~OPT_qq;
  2439. alarm(50);
  2440. }
  2441. nfds--;
  2442. recv_and_process_peer_pkt(idx2peer[j]);
  2443. gettime1900d(); /* sets G.cur_time */
  2444. }
  2445. }
  2446. check_unsync:
  2447. if (G.ntp_peers && G.stratum != MAXSTRAT) {
  2448. for (item = G.ntp_peers; item != NULL; item = item->link) {
  2449. peer_t *p = (peer_t *) item->data;
  2450. if (p->reachable_bits)
  2451. goto have_reachable_peer;
  2452. }
  2453. /* No peer responded for last 8 packets, panic */
  2454. clamp_pollexp_and_set_MAXSTRAT();
  2455. run_script("unsync", 0.0);
  2456. have_reachable_peer: ;
  2457. }
  2458. } /* while (!bb_got_signal) */
  2459. remove_pidfile_std_path_and_ext("ntpd");
  2460. kill_myself_with_sig(bb_got_signal);
  2461. }
  2462. /*** openntpd-4.6 uses only adjtime, not adjtimex ***/
  2463. /*** ntp-4.2.6/ntpd/ntp_loopfilter.c - adjtimex usage ***/
  2464. #if 0
  2465. static double
  2466. direct_freq(double fp_offset)
  2467. {
  2468. #ifdef KERNEL_PLL
  2469. /*
  2470. * If the kernel is enabled, we need the residual offset to
  2471. * calculate the frequency correction.
  2472. */
  2473. if (pll_control && kern_enable) {
  2474. memset(&ntv, 0, sizeof(ntv));
  2475. ntp_adjtime(&ntv);
  2476. #ifdef STA_NANO
  2477. clock_offset = ntv.offset / 1e9;
  2478. #else /* STA_NANO */
  2479. clock_offset = ntv.offset / 1e6;
  2480. #endif /* STA_NANO */
  2481. drift_comp = FREQTOD(ntv.freq);
  2482. }
  2483. #endif /* KERNEL_PLL */
  2484. set_freq((fp_offset - clock_offset) / (current_time - clock_epoch) + drift_comp);
  2485. wander_resid = 0;
  2486. return drift_comp;
  2487. }
  2488. static void
  2489. set_freq(double freq) /* frequency update */
  2490. {
  2491. char tbuf[80];
  2492. drift_comp = freq;
  2493. #ifdef KERNEL_PLL
  2494. /*
  2495. * If the kernel is enabled, update the kernel frequency.
  2496. */
  2497. if (pll_control && kern_enable) {
  2498. memset(&ntv, 0, sizeof(ntv));
  2499. ntv.modes = MOD_FREQUENCY;
  2500. ntv.freq = DTOFREQ(drift_comp);
  2501. ntp_adjtime(&ntv);
  2502. snprintf(tbuf, sizeof(tbuf), "kernel %.3f PPM", drift_comp * 1e6);
  2503. report_event(EVNT_FSET, NULL, tbuf);
  2504. } else {
  2505. snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
  2506. report_event(EVNT_FSET, NULL, tbuf);
  2507. }
  2508. #else /* KERNEL_PLL */
  2509. snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
  2510. report_event(EVNT_FSET, NULL, tbuf);
  2511. #endif /* KERNEL_PLL */
  2512. }
  2513. ...
  2514. ...
  2515. ...
  2516. #ifdef KERNEL_PLL
  2517. /*
  2518. * This code segment works when clock adjustments are made using
  2519. * precision time kernel support and the ntp_adjtime() system
  2520. * call. This support is available in Solaris 2.6 and later,
  2521. * Digital Unix 4.0 and later, FreeBSD, Linux and specially
  2522. * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
  2523. * DECstation 5000/240 and Alpha AXP, additional kernel
  2524. * modifications provide a true microsecond clock and nanosecond
  2525. * clock, respectively.
  2526. *
  2527. * Important note: The kernel discipline is used only if the
  2528. * step threshold is less than 0.5 s, as anything higher can
  2529. * lead to overflow problems. This might occur if some misguided
  2530. * lad set the step threshold to something ridiculous.
  2531. */
  2532. if (pll_control && kern_enable) {
  2533. #define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | MOD_STATUS | MOD_TIMECONST)
  2534. /*
  2535. * We initialize the structure for the ntp_adjtime()
  2536. * system call. We have to convert everything to
  2537. * microseconds or nanoseconds first. Do not update the
  2538. * system variables if the ext_enable flag is set. In
  2539. * this case, the external clock driver will update the
  2540. * variables, which will be read later by the local
  2541. * clock driver. Afterwards, remember the time and
  2542. * frequency offsets for jitter and stability values and
  2543. * to update the frequency file.
  2544. */
  2545. memset(&ntv, 0, sizeof(ntv));
  2546. if (ext_enable) {
  2547. ntv.modes = MOD_STATUS;
  2548. } else {
  2549. #ifdef STA_NANO
  2550. ntv.modes = MOD_BITS | MOD_NANO;
  2551. #else /* STA_NANO */
  2552. ntv.modes = MOD_BITS;
  2553. #endif /* STA_NANO */
  2554. if (clock_offset < 0)
  2555. dtemp = -.5;
  2556. else
  2557. dtemp = .5;
  2558. #ifdef STA_NANO
  2559. ntv.offset = (int32)(clock_offset * 1e9 + dtemp);
  2560. ntv.constant = sys_poll;
  2561. #else /* STA_NANO */
  2562. ntv.offset = (int32)(clock_offset * 1e6 + dtemp);
  2563. ntv.constant = sys_poll - 4;
  2564. #endif /* STA_NANO */
  2565. ntv.esterror = (u_int32)(clock_jitter * 1e6);
  2566. ntv.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
  2567. ntv.status = STA_PLL;
  2568. /*
  2569. * Enable/disable the PPS if requested.
  2570. */
  2571. if (pps_enable) {
  2572. if (!(pll_status & STA_PPSTIME))
  2573. report_event(EVNT_KERN,
  2574. NULL, "PPS enabled");
  2575. ntv.status |= STA_PPSTIME | STA_PPSFREQ;
  2576. } else {
  2577. if (pll_status & STA_PPSTIME)
  2578. report_event(EVNT_KERN,
  2579. NULL, "PPS disabled");
  2580. ntv.status &= ~(STA_PPSTIME | STA_PPSFREQ);
  2581. }
  2582. if (sys_leap == LEAP_ADDSECOND)
  2583. ntv.status |= STA_INS;
  2584. else if (sys_leap == LEAP_DELSECOND)
  2585. ntv.status |= STA_DEL;
  2586. }
  2587. /*
  2588. * Pass the stuff to the kernel. If it squeals, turn off
  2589. * the pps. In any case, fetch the kernel offset,
  2590. * frequency and jitter.
  2591. */
  2592. if (ntp_adjtime(&ntv) == TIME_ERROR) {
  2593. if (!(ntv.status & STA_PPSSIGNAL))
  2594. report_event(EVNT_KERN, NULL,
  2595. "PPS no signal");
  2596. }
  2597. pll_status = ntv.status;
  2598. #ifdef STA_NANO
  2599. clock_offset = ntv.offset / 1e9;
  2600. #else /* STA_NANO */
  2601. clock_offset = ntv.offset / 1e6;
  2602. #endif /* STA_NANO */
  2603. clock_frequency = FREQTOD(ntv.freq);
  2604. /*
  2605. * If the kernel PPS is lit, monitor its performance.
  2606. */
  2607. if (ntv.status & STA_PPSTIME) {
  2608. #ifdef STA_NANO
  2609. clock_jitter = ntv.jitter / 1e9;
  2610. #else /* STA_NANO */
  2611. clock_jitter = ntv.jitter / 1e6;
  2612. #endif /* STA_NANO */
  2613. }
  2614. #if defined(STA_NANO) && NTP_API == 4
  2615. /*
  2616. * If the TAI changes, update the kernel TAI.
  2617. */
  2618. if (loop_tai != sys_tai) {
  2619. loop_tai = sys_tai;
  2620. ntv.modes = MOD_TAI;
  2621. ntv.constant = sys_tai;
  2622. ntp_adjtime(&ntv);
  2623. }
  2624. #endif /* STA_NANO */
  2625. }
  2626. #endif /* KERNEL_PLL */
  2627. #endif