1 // Copyright 2019 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "cast/common/certificate/types.h"
6
7 #include "util/osp_logging.h"
8
9 namespace openscreen {
10 namespace cast {
11
operator <(const DateTime & a,const DateTime & b)12 bool operator<(const DateTime& a, const DateTime& b) {
13 if (a.year < b.year) {
14 return true;
15 } else if (a.year > b.year) {
16 return false;
17 }
18 if (a.month < b.month) {
19 return true;
20 } else if (a.month > b.month) {
21 return false;
22 }
23 if (a.day < b.day) {
24 return true;
25 } else if (a.day > b.day) {
26 return false;
27 }
28 if (a.hour < b.hour) {
29 return true;
30 } else if (a.hour > b.hour) {
31 return false;
32 }
33 if (a.minute < b.minute) {
34 return true;
35 } else if (a.minute > b.minute) {
36 return false;
37 }
38 if (a.second < b.second) {
39 return true;
40 } else if (a.second > b.second) {
41 return false;
42 }
43 return false;
44 }
45
operator >(const DateTime & a,const DateTime & b)46 bool operator>(const DateTime& a, const DateTime& b) {
47 return (b < a);
48 }
49
DateTimeFromSeconds(uint64_t seconds,DateTime * time)50 bool DateTimeFromSeconds(uint64_t seconds, DateTime* time) {
51 struct tm tm = {};
52 time_t sec = static_cast<time_t>(seconds);
53 OSP_DCHECK_GE(sec, 0);
54 OSP_DCHECK_EQ(static_cast<uint64_t>(sec), seconds);
55 #if defined(_WIN32)
56 // NOTE: This is for compiling in Chromium and is not validated in any direct
57 // libcast Windows build.
58 if (!gmtime_s(&tm, &sec)) {
59 return false;
60 }
61 #else
62 if (!gmtime_r(&sec, &tm)) {
63 return false;
64 }
65 #endif
66
67 time->second = tm.tm_sec;
68 time->minute = tm.tm_min;
69 time->hour = tm.tm_hour;
70 time->day = tm.tm_mday;
71 time->month = tm.tm_mon + 1;
72 time->year = tm.tm_year + 1900;
73
74 return true;
75 }
76
77 static_assert(sizeof(time_t) >= 4, "Can't avoid overflow with < 32-bits");
78
DateTimeToSeconds(const DateTime & time)79 std::chrono::seconds DateTimeToSeconds(const DateTime& time) {
80 OSP_DCHECK_GE(time.month, 1);
81 OSP_DCHECK_GE(time.year, 1900);
82 // NOTE: Guard against overflow if time_t is 32-bit.
83 OSP_DCHECK(sizeof(time_t) >= 8 || time.year < 2038) << time.year;
84 struct tm tm = {};
85 tm.tm_sec = time.second;
86 tm.tm_min = time.minute;
87 tm.tm_hour = time.hour;
88 tm.tm_mday = time.day;
89 tm.tm_mon = time.month - 1;
90 tm.tm_year = time.year - 1900;
91 time_t sec;
92 #if defined(_WIN32)
93 sec = _mkgmtime(&tm);
94 #else
95 sec = timegm(&tm);
96 #endif
97 return std::chrono::seconds(sec);
98 }
99
100 } // namespace cast
101 } // namespace openscreen
102