ntpd.c 90 KB

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