Debian Codegraph @

apps/apputil.cpp

raw
1 /*
2 * SRT - Secure, Reliable, Transport
3 * Copyright (c) 2018 Haivision Systems Inc.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 *
9 */
10
11 #include <cstring>
12 #include <chrono>
13 #include <iostream>
14 #include <iomanip>
15 #include <sstream>
16 #include <utility>
17 #include <memory>
18
19 #include "srt.h" // Required for SRT_SYNC_CLOCK_* definitions.
20 #include "apputil.hpp"
21 #include "netinet_any.h"
22 #include "srt_compat.h"
23
24 using namespace std;
25 using namespace srt;
26
27
28 // NOTE: MINGW currently does not include support for inet_pton(). See
29 // http://mingw.5.n7.nabble.com/Win32API-request-for-new-functions-td22029.html
30 // Even if it did support inet_pton(), it is only available on Windows Vista
31 // and later. Since we need to support WindowsXP and later in ORTHRUS. Many
32 // customers still use it, we will need to implement using something like
33 // WSAStringToAddress() which is available on Windows95 and later.
34 // Support for IPv6 was added on WindowsXP SP1.
35 // Header: winsock2.h
36 // Implementation: ws2_32.dll
37 // See:
38 // https://msdn.microsoft.com/en-us/library/windows/desktop/ms742214(v=vs.85).aspx
39 // http://www.winsocketdotnetworkprogramming.com/winsock2programming/winsock2advancedInternet3b.html
40 #if defined(_WIN32) && !defined(HAVE_INET_PTON)
41 namespace // Prevent conflict in case when still defined
42 {
43 int inet_pton(int af, const char * src, void * dst)
44 {
45 struct sockaddr_storage ss;
46 int ssSize = sizeof(ss);
47 char srcCopy[INET6_ADDRSTRLEN + 1];
48
49 ZeroMemory(&ss, sizeof(ss));
50
51 // work around non-const API
52 #ifdef _MSC_VER
53 strncpy_s(srcCopy, INET6_ADDRSTRLEN + 1, src, _TRUNCATE);
54 #else
55 strncpy(srcCopy, src, INET6_ADDRSTRLEN);
56 srcCopy[INET6_ADDRSTRLEN] = '\0';
57 #endif
58 if (WSAStringToAddress(
59 srcCopy, af, NULL, (struct sockaddr *)&ss, &ssSize) != 0)
60 {
61 return 0;
62 }
63
64 switch (af)
65 {
66 case AF_INET :
67 {
68 *(struct in_addr *)dst = ((struct sockaddr_in *)&ss)->sin_addr;
69 return 1;
70 }
71 case AF_INET6 :
72 {
73 *(struct in6_addr *)dst = ((struct sockaddr_in6 *)&ss)->sin6_addr;
74 return 1;
75 }
76 default :
77 {
78 // No-Op
79 }
80 }
81
82 return 0;
83 }
84 }
85 #endif // _WIN32 && !HAVE_INET_PTON
86
87 sockaddr_any CreateAddr(const string& name, unsigned short port, int pref_family)
88 {
89 // Handle empty name.
90 // If family is specified, empty string resolves to ANY of that family.
91 // If not, it resolves to IPv4 ANY (to specify IPv6 any, use [::]).
92 if (name == "")
93 {
94 sockaddr_any result(pref_family == AF_INET6 ? pref_family : AF_INET);
95 result.hport(port);
96 return result;
97 }
98
99 bool first6 = pref_family != AF_INET;
100 int families[2] = {AF_INET6, AF_INET};
101 if (!first6)
102 {
103 families[0] = AF_INET;
104 families[1] = AF_INET6;
105 }
106
107 for (int i = 0; i < 2; ++i)
108 {
109 int family = families[i];
110 sockaddr_any result (family);
111
112 // Try to resolve the name by pton first
113 if (inet_pton(family, name.c_str(), result.get_addr()) == 1)
114 {
115 result.hport(port); // same addr location in ipv4 and ipv6
116 return result;
117 }
118 }
119
120 // If not, try to resolve by getaddrinfo
121 // This time, use the exact value of pref_family
122
123 sockaddr_any result;
124 addrinfo fo = {
125 0,
126 pref_family,
127 0, 0,
128 0, 0,
129 NULL, NULL
130 };
131
132 addrinfo* val = nullptr;
133 int erc = getaddrinfo(name.c_str(), nullptr, &fo, &val);
134 if (erc == 0)
135 {
136 result.set(val->ai_addr);
137 result.len = result.size();
138 result.hport(port); // same addr location in ipv4 and ipv6
139 }
140 freeaddrinfo(val);
141
142 return result;
143 }
144
145 string Join(const vector<string>& in, string sep)
146 {
147 if ( in.empty() )
148 return "";
149
150 ostringstream os;
151
152 os << in[0];
153 for (auto i = in.begin()+1; i != in.end(); ++i)
154 os << sep << *i;
155 return os.str();
156 }
157
158 // OPTION LIBRARY
159
160 OptionScheme::Args OptionName::DetermineTypeFromHelpText(const std::string& helptext)
161 {
162 if (helptext.empty())
163 return OptionScheme::ARG_NONE;
164
165 if (helptext[0] == '<')
166 {
167 // If the argument is <one-argument>, then it's ARG_NONE.
168 // If it's <multiple-arguments...>, then it's ARG_VAR.
169 // When closing angle bracket isn't found, fallback to ARG_ONE.
170 size_t pos = helptext.find('>');
171 if (pos == std::string::npos)
172 return OptionScheme::ARG_ONE; // mistake, but acceptable
173
174 if (pos >= 4 && helptext.substr(pos-3, 4) == "...>")
175 return OptionScheme::ARG_VAR;
176
177 // We have < and > without ..., simply one argument
178 return OptionScheme::ARG_ONE;
179 }
180
181 if (helptext[0] == '[')
182 {
183 // Argument in [] means it is optional; in this case
184 // you should state that the argument can be given or not.
185 return OptionScheme::ARG_VAR;
186 }
187
188 // Also as fallback
189 return OptionScheme::ARG_NONE;
190 }
191
192 options_t ProcessOptions(char* const* argv, int argc, std::vector<OptionScheme> scheme)
193 {
194 using namespace std;
195
196 string current_key;
197 string extra_arg;
198 size_t vals = 0;
199 OptionScheme::Args type = OptionScheme::ARG_VAR; // This is for no-option-yet or consumed
200 map<string, vector<string>> params;
201 bool moreoptions = true;
202
203 for (char* const* p = argv+1; p != argv+argc; ++p)
204 {
205 const char* a = *p;
206 // cout << "*D ARG: '" << a << "'\n";
207 bool isoption = false;
208 if (a[0] == '-')
209 {
210 isoption = true;
211 // If a[0] isn't NUL - because it is dash - then
212 // we can safely check a[1].
213 // An expression starting with a dash is not
214 // an option marker if it is a single dash or
215 // a negative number.
216 if (!a[1] || isdigit(a[1]))
217 isoption = false;
218 }
219
220 if (moreoptions && isoption)
221 {
222 bool arg_specified = false;
223 size_t seppos; // (see goto, it would jump over initialization)
224 current_key = a+1;
225 if ( current_key == "-" )
226 {
227 // The -- argument terminates the options.
228 // The default key is restored to empty so that
229 // it collects now all arguments under the empty key
230 // (not-option-assigned argument).
231 moreoptions = false;
232 goto EndOfArgs;
233 }
234
235 // Maintain the backward compatibility with argument specified after :
236 // or with one string separated by space inside.
237 seppos = current_key.find(':');
238 if (seppos == string::npos)
239 seppos = current_key.find(' ');
240 if (seppos != string::npos)
241 {
242 // Old option specification.
243 extra_arg = current_key.substr(seppos + 1);
244 current_key = current_key.substr(0, 0 + seppos);
245 arg_specified = true; // Prevent eating args from option list
246 }
247
248 params[current_key].clear();
249 vals = 0;
250
251 if (extra_arg != "")
252 {
253 params[current_key].push_back(extra_arg);
254 ++vals;
255 extra_arg.clear();
256 }
257
258 // Find the key in the scheme. If not found, treat it as ARG_NONE.
259 for (const auto& s: scheme)
260 {
261 if (s.names().count(current_key))
262 {
263 // cout << "*D found '" << current_key << "' in scheme type=" << int(s.type) << endl;
264 // If argument was specified using the old way, like
265 // -v:0 or "-v 0", then consider the argument specified and
266 // treat further arguments as either no-option arguments or
267 // new options.
268 if (s.type == OptionScheme::ARG_NONE || arg_specified)
269 {
270 // Anyway, consider it already processed.
271 break;
272 }
273 type = s.type;
274
275 if ( vals == 1 && type == OptionScheme::ARG_ONE )
276 {
277 // Argument for one-arg option already consumed,
278 // so set to free args.
279 goto EndOfArgs;
280 }
281 goto Found;
282 }
283
284 }
285 // Not found: set ARG_NONE.
286 // cout << "*D KEY '" << current_key << "' assumed type NONE\n";
287 EndOfArgs:
288 type = OptionScheme::ARG_VAR;
289 current_key = "";
290 Found:
291 continue;
292 }
293
294 // Collected a value - check if full
295 // cout << "*D COLLECTING '" << a << "' for key '" << current_key << "' (" << vals << " so far)\n";
296 params[current_key].push_back(a);
297 ++vals;
298 if ( vals == 1 && type == OptionScheme::ARG_ONE )
299 {
300 // cout << "*D KEY TYPE ONE - resetting to empty key\n";
301 // Reset the key to "default one".
302 current_key = "";
303 vals = 0;
304 type = OptionScheme::ARG_VAR;
305 }
306 else
307 {
308 // cout << "*D KEY type VAR - still collecting until the end of options or next option.\n";
309 }
310 }
311
312 return params;
313 }
314
315 string OptionHelpItem(const OptionName& o)
316 {
317 string out = "\t-" + o.main_name;
318 string hlp = o.helptext;
319 string prefix;
320
321 if (hlp == "")
322 {
323 hlp = " (Undocumented)";
324 }
325 else if (hlp[0] != ' ')
326 {
327 size_t end = string::npos;
328 if (hlp[0] == '<')
329 {
330 end = hlp.find('>');
331 }
332 else if (hlp[0] == '[')
333 {
334 end = hlp.find(']');
335 }
336
337 if (end != string::npos)
338 {
339 ++end;
340 }
341 else
342 {
343 end = hlp.find(' ');
344 }
345
346 if (end != string::npos)
347 {
348 prefix = hlp.substr(0, end);
349 //while (hlp[end] == ' ')
350 // ++end;
351 hlp = hlp.substr(end);
352 out += " " + prefix;
353 }
354 }
355
356 out += " -" + hlp;
357 return out;
358 }
359
360 const char* SRTClockTypeStr()
361 {
362 const int clock_type = srt_clock_type();
363
364 switch (clock_type)
365 {
366 case SRT_SYNC_CLOCK_STDCXX_STEADY:
367 return "CXX11_STEADY";
368 case SRT_SYNC_CLOCK_GETTIME_MONOTONIC:
369 return "GETTIME_MONOTONIC";
370 case SRT_SYNC_CLOCK_WINQPC:
371 return "WIN_QPC";
372 case SRT_SYNC_CLOCK_MACH_ABSTIME:
373 return "MACH_ABSTIME";
374 case SRT_SYNC_CLOCK_POSIX_GETTIMEOFDAY:
375 return "POSIX_GETTIMEOFDAY";
376 default:
377 break;
378 }
379
380 return "UNKNOWN VALUE";
381 }
382
383 void PrintLibVersion()
384 {
385 cerr << "Built with SRT Library version: " << SRT_VERSION << endl;
386 const uint32_t srtver = srt_getversion();
387 const int major = srtver / 0x10000;
388 const int minor = (srtver / 0x100) % 0x100;
389 const int patch = srtver % 0x100;
390 cerr << "SRT Library version: " << major << "." << minor << "." << patch << ", clock type: " << SRTClockTypeStr() << endl;
391 }