ntpd.c 96 KB

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