• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "sntp_client.h"
17 #include "ntp_trusted_time.h"
18 
19 #include <netdb.h>
20 #include <securec.h>
21 #include <sstream>
22 #include <sys/time.h>
23 
24 #include "time_sysevent.h"
25 
26 namespace OHOS {
27 namespace MiscServices {
28 namespace {
29 constexpr uint64_t SECONDS_SINCE_FIRST_EPOCH = 2208988800; // Seconds from 1/1/1900 00.00 to 1/1/1970 00.00;
30 constexpr uint64_t MILLISECOND_TO_SECOND = 1000;
31 constexpr uint64_t FRACTION_TO_SECOND = 0x100000000;
32 constexpr uint64_t UINT32_MASK = 0xFFFFFFFF;
33 constexpr int VERSION_MASK = 0x38;
34 constexpr int MODE_MASK = 0x7;
35 constexpr int32_t INDEX_ZERO = 0;
36 constexpr int32_t INDEX_ONE = 1;
37 constexpr int32_t INDEX_TWO = 2;
38 constexpr int32_t INDEX_THREE = 3;
39 constexpr int32_t INDEX_FOUR = 4;
40 constexpr int32_t TIME_OUT = 5;
41 constexpr unsigned char MODE_THREE = 3;
42 constexpr unsigned char VERSION_THREE = 3;
43 constexpr double TEN_TO_MINUS_SIX_POWER = 1.0e-6;
44 constexpr const char* NTP_PORT = "123";
45 constexpr int32_t NTP_MSG_OFFSET_ROOT_DELAY = 4;
46 constexpr int32_t NTP_MSG_OFFSET_ROOT_DISPERSION = 8;
47 constexpr int32_t NTP_MSG_OFFSET_REFERENCE_IDENTIFIER = 12;
48 constexpr int32_t REFERENCE_TIMESTAMP_OFFSET = 16;
49 constexpr int32_t ORIGINATE_TIMESTAMP_OFFSET = 24;
50 constexpr int32_t RECEIVE_TIMESTAMP_OFFSET = 32;
51 constexpr int32_t TRANSMIT_TIMESTAMP_OFFSET = 40;
52 constexpr int32_t NTP_PACKAGE_SIZE = 48;
53 constexpr int32_t SNTP_MSG_OFFSET_SIX = 6;
54 constexpr int32_t SNTP_MSG_OFFSET_THREE = 3;
55 } // namespace
56 
RequestTime(const std::string & host)57 bool SNTPClient::RequestTime(const std::string &host)
58 {
59     int bufLen = NTP_PACKAGE_SIZE;
60     struct addrinfo hints = { 0 }, *addrs;
61     hints.ai_family = AF_INET;
62     hints.ai_socktype = SOCK_DGRAM;
63     hints.ai_protocol = IPPROTO_UDP;
64     int error = getaddrinfo(host.c_str(), NTP_PORT, &hints, &addrs);
65     if (error != 0) {
66         TIME_HILOGE(TIME_MODULE_SERVICE, "getaddrinfo failed error %{public}d", error);
67         return false;
68     }
69 
70     // Create a socket for sending data
71     int sendSocket = socket(addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol);
72     if (sendSocket < 0) {
73         TIME_HILOGE(TIME_MODULE_SERVICE,
74                     "create socket failed: %{public}s family: %{public}d socktype: %{public}d protocol: %{public}d",
75                     strerror(errno), addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol);
76         return false;
77     }
78 
79     // Set send and recv function timeout
80     struct timeval timeout = { TIME_OUT, 0 };
81     setsockopt(sendSocket, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(struct timeval));
82     setsockopt(sendSocket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(struct timeval));
83     if (connect(sendSocket, addrs->ai_addr, addrs->ai_addrlen) < 0) {
84         TIME_HILOGE(TIME_MODULE_SERVICE, "socket connect failed: %{public}s", strerror(errno));
85         close(sendSocket);
86         return false;
87     }
88 
89     // Create the NTP tx timestamp and fill the fields in the msg to be tx
90     char sendBuf[NTP_PACKAGE_SIZE] = { 0 };
91     CreateMessage(sendBuf);
92     if (send(sendSocket, sendBuf, bufLen, 0) < 0) {
93         TIME_HILOGE(TIME_MODULE_SERVICE, "Send socket message failed: %{public}s, Host: %{public}s",
94                     strerror(errno), host.c_str());
95         close(sendSocket);
96         return false;
97     }
98 
99     char bufferRx[NTP_PACKAGE_SIZE] = { 0 };
100     // Receive until the peer closes the connection
101     if (recv(sendSocket, bufferRx, NTP_PACKAGE_SIZE, 0) < 0) {
102         TIME_HILOGE(TIME_MODULE_SERVICE, "Receive socket message failed: %{public}s, Host: %{public}s",
103                     strerror(errno), host.c_str());
104         close(sendSocket);
105         return false;
106     }
107     close(sendSocket);
108     if (!ReceivedMessage(bufferRx)) {
109         TIME_HILOGE(TIME_MODULE_SERVICE, "ReceivedMessage failed: Host: %{public}s", host.c_str());
110         return false;
111     }
112     return true;
113 }
114 
SetClockOffset(int clockOffset)115 void SNTPClient::SetClockOffset(int clockOffset)
116 {
117     m_clockOffset = clockOffset;
118 }
119 
GetNtpTimestamp64(int offset,const char * buffer)120 uint64_t SNTPClient::GetNtpTimestamp64(int offset, const char *buffer)
121 {
122     TIME_HILOGD(TIME_MODULE_SERVICE, "start");
123     const int _len = sizeof(uint64_t);
124     char valueRx[_len];
125     errno_t ret = memset_s(valueRx, sizeof(uint64_t), 0, sizeof(uint64_t));
126     if (ret != EOK) {
127         TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %{public}d", ret);
128         return false;
129     }
130     int numOfBit = sizeof(uint64_t) - 1;
131     for (int loop = offset; loop < offset + _len; loop++) {
132         valueRx[numOfBit] = buffer[loop];
133         numOfBit--;
134     }
135 
136     uint64_t milliseconds;
137     ret = memcpy_s(&milliseconds, sizeof(uint64_t), valueRx, sizeof(uint64_t));
138     if (ret != EOK) {
139         TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %{public}d", ret);
140         return false;
141     }
142     return le64toh(milliseconds);
143 }
144 
ConvertUnixToNtp(struct ntp_timestamp * ntpTs,struct timeval * unixTs)145 void SNTPClient::ConvertUnixToNtp(struct ntp_timestamp *ntpTs, struct timeval *unixTs)
146 {
147     TIME_HILOGD(TIME_MODULE_SERVICE, "start");
148     // 0x83AA7E80; the seconds from Jan 1, 1900 to Jan 1, 1970
149     ntpTs->second = unixTs->tv_sec + SECONDS_SINCE_FIRST_EPOCH; // 0x83AA7E80;
150     ntpTs->fraction =
151         static_cast<uint64_t>((unixTs->tv_usec + 1) * (1LL << RECEIVE_TIMESTAMP_OFFSET) * TEN_TO_MINUS_SIX_POWER);
152     TIME_HILOGD(TIME_MODULE_SERVICE, "end");
153 }
154 
155 /*
156   *	/// SNTP Timestamp Format (as described in RFC 2030)
157   *                         1                   2                   3
158   *   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
159   *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
160   *   |                           Seconds                             |
161   *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
162   *   |                  Seconds Fraction (0-padded)                  |
163   *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
164   */
ConvertNtpToStamp(uint64_t _ntpTs)165 int64_t SNTPClient::ConvertNtpToStamp(uint64_t _ntpTs)
166 {
167     auto second = static_cast<uint32_t>((_ntpTs >> RECEIVE_TIMESTAMP_OFFSET) & UINT32_MASK);
168     auto fraction = static_cast<uint32_t>(_ntpTs & UINT32_MASK);
169     if (second == 0 && fraction == 0) {
170         return 0;
171     }
172     if (second < SECONDS_SINCE_FIRST_EPOCH) {
173         return 0;
174     }
175     // convert sntp timestamp to seconds
176     return ((second - SECONDS_SINCE_FIRST_EPOCH) * MILLISECOND_TO_SECOND) +
177            ((fraction * MILLISECOND_TO_SECOND) / FRACTION_TO_SECOND);
178 }
179 
CreateMessage(char * buffer)180 void SNTPClient::CreateMessage(char *buffer)
181 {
182     TIME_HILOGD(TIME_MODULE_SERVICE, "start");
183     struct ntp_timestamp ntp{};
184     struct timeval unix;
185 
186     gettimeofday(&unix, nullptr);
187     // convert unix time to ntp time
188     ConvertUnixToNtp(&ntp, &unix);
189     uint64_t _ntpTs = ntp.second;
190     _ntpTs = (_ntpTs << RECEIVE_TIMESTAMP_OFFSET) | ntp.fraction;
191     errno_t ret = TimeUtils::GetBootTimeMs(m_originateTimestamp);
192     if (ret != E_TIME_OK) {
193         return;
194     }
195 
196     SNTPMessage _sntpMsg{};
197     // Important, if you don't set the version/mode, the server will ignore you.
198     _sntpMsg.clear();
199     _sntpMsg._leapIndicator = 0;
200     _sntpMsg._versionNumber = VERSION_THREE;
201     _sntpMsg._mode = MODE_THREE;
202     // optional (?)
203     _sntpMsg._originateTimestamp = _ntpTs;
204     char value[sizeof(uint64_t)];
205     ret = memcpy_s(value, sizeof(uint64_t), &_sntpMsg._originateTimestamp, sizeof(uint64_t));
206     if (ret != EOK) {
207         TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %{public}d", ret);
208         return;
209     }
210     int numOfBit = sizeof(uint64_t) - 1;
211     int offsetEnd = ORIGINATE_TIMESTAMP_OFFSET + sizeof(uint64_t);
212     for (int loop = ORIGINATE_TIMESTAMP_OFFSET; loop < offsetEnd; loop++) {
213         buffer[loop] = value[numOfBit];
214         numOfBit--;
215     }
216     // create the 1-byte info in one go... the result should be 27 :)
217     buffer[INDEX_ZERO] = (_sntpMsg._leapIndicator << SNTP_MSG_OFFSET_SIX) |
218                          (_sntpMsg._versionNumber << SNTP_MSG_OFFSET_THREE) | _sntpMsg._mode;
219     TIME_HILOGD(TIME_MODULE_SERVICE, "end");
220 }
221 
ReceivedMessage(char * buffer)222 bool SNTPClient::ReceivedMessage(char *buffer)
223 {
224     int64_t receiveBootTime = 0;
225     errno_t ret = TimeUtils::GetBootTimeMs(receiveBootTime);
226     if (ret != E_TIME_OK) {
227         return false;
228     }
229     SNTPMessage _sntpMsg;
230     _sntpMsg.clear();
231     _sntpMsg._leapIndicator = buffer[INDEX_ZERO] >> SNTP_MSG_OFFSET_SIX;
232     _sntpMsg._versionNumber = (buffer[INDEX_ZERO] & VERSION_MASK) >> SNTP_MSG_OFFSET_THREE;
233     _sntpMsg._mode = (buffer[INDEX_ZERO] & MODE_MASK);
234     _sntpMsg._stratum = buffer[INDEX_ONE];
235     _sntpMsg._pollInterval = buffer[INDEX_TWO];
236     _sntpMsg._precision = buffer[INDEX_THREE];
237     _sntpMsg._rootDelay = GetNtpField32(NTP_MSG_OFFSET_ROOT_DELAY, buffer);
238     _sntpMsg._rootDispersion = GetNtpField32(NTP_MSG_OFFSET_ROOT_DISPERSION, buffer);
239     int _refId[INDEX_FOUR];
240     GetReferenceId(NTP_MSG_OFFSET_REFERENCE_IDENTIFIER, buffer, _refId);
241     _sntpMsg._referenceIdentifier[INDEX_ZERO] = _refId[INDEX_ZERO];
242     _sntpMsg._referenceIdentifier[INDEX_ONE] = _refId[INDEX_ONE];
243     _sntpMsg._referenceIdentifier[INDEX_TWO] = _refId[INDEX_TWO];
244     _sntpMsg._referenceIdentifier[INDEX_THREE] = _refId[INDEX_THREE];
245     _sntpMsg._referenceTimestamp = GetNtpTimestamp64(REFERENCE_TIMESTAMP_OFFSET, buffer);
246     _sntpMsg._originateTimestamp = GetNtpTimestamp64(ORIGINATE_TIMESTAMP_OFFSET, buffer);
247     _sntpMsg._receiveTimestamp = GetNtpTimestamp64(RECEIVE_TIMESTAMP_OFFSET, buffer);
248     _sntpMsg._transmitTimestamp = GetNtpTimestamp64(TRANSMIT_TIMESTAMP_OFFSET, buffer);
249     int64_t _originClient = m_originateTimestamp;
250     int64_t _receiveServer = ConvertNtpToStamp(_sntpMsg._receiveTimestamp);
251     int64_t _transmitServer = ConvertNtpToStamp(_sntpMsg._transmitTimestamp);
252     if (_transmitServer == 0 || _receiveServer == 0) {
253         return false;
254     }
255     int64_t _receiveClient = receiveBootTime;
256     int64_t _clockOffset = (((_receiveServer - _originClient) + (_transmitServer - _receiveClient)) / INDEX_TWO);
257     int64_t _roundTripDelay = (_receiveClient - _originClient) - (_transmitServer - _receiveServer);
258     mRoundTripTime = _roundTripDelay;
259     mNtpTime = receiveBootTime + _clockOffset;
260     mNtpTimeReference = std::chrono::duration_cast<std::chrono::milliseconds>(
261         NtpTrustedTime::GetInstance().GetBootTimeNs().time_since_epoch()).count();
262     SetClockOffset(_clockOffset);
263     TIME_HILOGI(TIME_MODULE_SERVICE, "_originClient:%{public}s, _receiveServer:%{public}s, _transmitServer:%{public}s,"
264                 "_receiveClient:%{public}s", std::to_string(_originClient).c_str(),
265                 std::to_string(_receiveServer).c_str(), std::to_string(_transmitServer).c_str(),
266                 std::to_string(_receiveClient).c_str());
267     TimeBehaviorReport(ReportEventCode::NTP_REFRESH,
268         std::to_string(_originClient) + "|" + std::to_string(_receiveClient),
269         std::to_string(_transmitServer) + "|" + std::to_string(_receiveServer), mNtpTime);
270     return true;
271 }
272 
GetNtpField32(int offset,const char * buffer)273 unsigned int SNTPClient::GetNtpField32(int offset, const char *buffer)
274 {
275     TIME_HILOGD(TIME_MODULE_SERVICE, "start");
276     const int _len = sizeof(int);
277     char valueRx[_len];
278     errno_t ret = memset_s(valueRx, _len, 0, _len);
279     if (ret != EOK) {
280         TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %{public}d", ret);
281         return false;
282     }
283     int numOfBit = sizeof(int) - 1;
284     for (int loop = offset; loop < offset + _len; loop++) {
285         valueRx[numOfBit] = buffer[loop];
286         numOfBit--;
287     }
288 
289     unsigned int milliseconds;
290     errno_t retValue = memcpy_s(&milliseconds, sizeof(int), valueRx, sizeof(int));
291     if (retValue != EOK) {
292         TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %{public}d", retValue);
293         return false;
294     }
295     TIME_HILOGD(TIME_MODULE_SERVICE, "end");
296     return milliseconds;
297 }
298 
GetReferenceId(int offset,char * buffer,int * _outArray)299 void SNTPClient::GetReferenceId(int offset, char *buffer, int *_outArray)
300 {
301     TIME_HILOGD(TIME_MODULE_SERVICE, "start");
302     const int _len = sizeof(int);
303     int num = 0;
304     for (int loop = offset; loop < offset + _len; loop++) {
305         _outArray[num] = buffer[loop];
306         num++;
307     }
308     TIME_HILOGD(TIME_MODULE_SERVICE, "end");
309 }
310 
clear()311 void SNTPClient::SNTPMessage::clear()
312 {
313     TIME_HILOGD(TIME_MODULE_SERVICE, "start");
314     errno_t ret = memset_s(this, sizeof(*this), 0, sizeof(*this));
315     if (ret != EOK) {
316         TIME_HILOGE(TIME_MODULE_SERVICE, "memcpy_s failed, err = %{public}d", ret);
317     }
318 }
319 
getNtpTime()320 int64_t SNTPClient::getNtpTime()
321 {
322     return mNtpTime;
323 }
324 
getNtpTimeReference()325 int64_t SNTPClient::getNtpTimeReference()
326 {
327     return mNtpTimeReference;
328 }
329 
getRoundTripTime()330 int64_t SNTPClient::getRoundTripTime()
331 {
332     return mRoundTripTime;
333 }
334 } // namespace MiscServices
335 } // namespace OHOS