ntpd.c 95 KB

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