ntpd.c 95 KB

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