-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
567 lines (437 loc) · 14.3 KB
/
main.cpp
File metadata and controls
567 lines (437 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// Author: Sinipelto (c) 2019
// Dynamic IP address updater against domain API.
// Reads and parses configuration parameters from configuration file.
#include "ip.hh"
#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <map>
#include <fstream>
#include <chrono>
#include <ctime>
#include <locale>
#include <curl/curl.h>
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Option.hpp>
#include <curlpp/Options.hpp>
#include <curlpp/Form.hpp>
using namespace std;
enum IpSource {external, router};
string &ProcessPath(string &path);
map<string, string> *ReadConfiguration(const string * const path);
const updater::ip *ReadIpFromFile(const string * const path);
const updater::ip *QueryIpFromUrl(const string &url, const IpSource &source);
void UpdateIp(const updater::ip * const ip, const string &url, const string &apikey, const string &apisecret);
void SaveIpToFile(const updater::ip * const ip, const string * const path);
std::pair<string, string> ParseLine(const string &line);
void RemoveSpaces(string &input);
bool ParseBool(const string &input);
std::vector<string> ParseList(string input, const string &delimiter);
void WriteChangeLog(const string * const path, const updater::ip *oldIp, const updater::ip *newIp);
void WriteLog(const string &message, const bool &use_cerr=false);
int Terminate(const int &code);
// Separating line for logging
#define WRITE_EXIT WriteLog("---------------------------------------------------------")
#if __WIN32
const char DELIM = '\\';
static string LogPath = "logs\\";
#else
const char DELIM = '/';
static string LogPath = "logs/";
#endif
const string configFile = "updater.conf";
const string lastipFile = "lastip";
const string recordFile = "record.log";
int main(int argc, char **argv)
{
if (argc <= 0)
{
WriteLog("ERROR: No path argument given. Aborting.", true);
return Terminate(1);
}
string basePath = argv[0];
#if __WIN32
basePath = ProcessPath(ProcessPath(basePath));
#else
basePath = ProcessPath(basePath);
#endif
LogPath = basePath + LogPath;
map<string, string> *config;
const string * const configPath = new string(basePath + configFile);
try {
config = ReadConfiguration(configPath);
} catch (const exception& e) {
string msg = "";
msg.append("ERROR: Failed to read configuration: ");
msg.append(e.what());
WriteLog(msg, true);
WRITE_EXIT;
throw;
}
delete configPath;
// Read variables from configuration
const string domain = config->at("domain");
const string api_key = config->at("api_key");
const string api_secret = config->at("api_secret");
const vector<string> record_list = ParseList(config->at("record_list"), ",");
const string ip_url = config->at("ip_url");
const string api_url_base = config->at("api_url");
const bool use_router_info = ParseBool(config->at("use_router_info"));
const string router_url = config->at("router_url");
const string router_username = config->at("router_username");
const string router_password = config->at("router_password");
const string router_keyword = config->at("router_keyword");
// Free configuration map memory
delete config;
// Check that there are domain records to process
if (record_list.size() <= 0)
{
WriteLog("WARNING: No records to process. Exiting.", true);
// Is a warning so terminate normally, status 0
return Terminate(0);
}
// Load last ip from record file
const string * const lastIpPath = new string(basePath + lastipFile);
const updater::ip *local_ip = ReadIpFromFile(lastIpPath);
// Query current ip
const updater::ip *remote_ip;
if (!use_router_info)
{
WriteLog("Using external service for fetching ip address..");
remote_ip = QueryIpFromUrl(ip_url, IpSource::external);
}
else {
WriteLog("Using local router as external ip source..");
remote_ip = QueryIpFromUrl(router_url, IpSource::router);
}
// Compare IPs
if (*local_ip == *remote_ip) {
WriteLog("IP not changed, exiting without changes.");
delete lastIpPath;
delete local_ip;
delete remote_ip;
return Terminate(0);
}
WriteLog("IP address changed from last record, updating the new ip..");
WriteLog("Old IP: " + local_ip->toString());
WriteLog("New IP: " + remote_ip->toString());
// Write the record change to a special record log file
const string * const recordPath = new string(basePath + recordFile);
WriteChangeLog(recordPath, local_ip, remote_ip);
delete recordPath;
delete local_ip;
for (const string& type : record_list)
{
// Create api url
const string &api_url = api_url_base + "/" + domain + "/records/A/" + type;
// If changed, update to server with new ip
UpdateIp(remote_ip, api_url, api_key, api_secret);
WriteLog(type + " record updated successfully.");
}
WriteLog("IP records updated to server successfully.");
// Write down new ip to file
SaveIpToFile(remote_ip, lastIpPath);
delete remote_ip;
delete lastIpPath;
WriteLog("Local IP record updated successfully.");
// Terminate curlpp and exit
return Terminate(0);
}
string &ProcessPath(string &path)
{
auto it = path.rbegin();
// Remove the first slash
if (*it == DELIM)
{
path.pop_back();
it++;
}
// Keep popping until next slash appears
while (*it != DELIM)
{
path.pop_back();
it++;
}
return path;
}
bool ParseBool(const string &input)
{
string parsed = "";
for (char c : input) {
if (c == ' ' || c == '\n' || c == '\t' || c == '\r') continue;
parsed += std::tolower(c, *new locale());
}
if (parsed == "")
{
WriteLog("ERROR: Could not parse boolean value for: " + input + "in configuration.", true);
throw new exception;
}
if (parsed == "yes" || parsed == "y" || parsed == "true") return true;
return false;
}
vector<string> ParseList(string input, const string &delimiter)
{
vector<string> options = {};
size_t pos = 0;
while ((pos = input.find(delimiter)) != std::string::npos)
{
string token = input.substr(0, pos);
input.erase(0, pos + delimiter.length());
if (token == "") continue;
options.push_back(token);
}
if (input != "") options.push_back(input);
return options;
}
int Terminate(const int &code)
{
curlpp::terminate();
WRITE_EXIT;
return code;
}
void WriteLog(const string &message, const bool &use_cerr)
{
// Set time parse format string
const char *fileFormat = "%Y-%m-%d";
const char *stampFormat = "[%Y-%m-%d %H:%M:%S] ";
// Get current time
time_t now = time(nullptr);
ostringstream ostring;
ostring << std::put_time(std::localtime(&now), fileFormat);
string logFileName;
logFileName.append(LogPath);
logFileName.append(ostring.str());
logFileName.append(".log");
ostring.seekp(0);
ofstream logFile;
logFile.open(logFileName, ios::app);
if (logFile.fail())
{
// Using cout insted of cerr because new file is created nightly
cout << "WARNING: Failed to open log file. Trying to create new one.." << endl;
logFile.open(logFileName);
if (logFile.fail())
{
cerr << "ERROR: Failed to create log file, aborting." << endl;
throw new exception;
}
}
ostring << put_time(localtime(&now), stampFormat) << message;
logFile << ostring.str() << endl;
logFile.close();
if (use_cerr) {
cerr << put_time(localtime(&now), stampFormat) << message << endl;
return;
}
cout << put_time(localtime(&now), stampFormat) << message << endl;
}
void WriteChangeLog(const string * const path, const updater::ip *oldIp, const updater::ip *newIp)
{
// Set time parse format string
const char *stampFormat = "[%Y-%m-%d %H:%M:%S] ";
// Get current time
time_t now = time(nullptr);
ostringstream ostring;
ofstream logFile;
logFile.open(*path, ios::app);
if (logFile.fail())
{
WriteLog("WARNING: Failed to open record file. Trying to create new one..", true);
logFile.open(*path);
if (logFile.fail())
{
WriteLog("ERROR: Failed to create record file, aborting..", true);
throw new exception;
}
}
ostring << put_time(localtime(&now), stampFormat) << "IP Record changed: from " << oldIp->toString() << " to " << newIp->toString();
logFile << ostring.str() << endl;
logFile.close();
}
std::pair<string, string> ParseLine(const string &line)
{
pair<string, string> keyvalue;
// line -> key=value
for (unsigned i = 0; i < line.size(); i++)
{
if (line[i] == '=')
{
keyvalue.first = line.substr(0, i); // [sdfjsd=], = excluded
if ( line[ line.size() - 1 ] == '\n' ) {
keyvalue.second = line.substr(i+1, line.size()-1); // [sdfsahdds\n], \n excluded
}
else {
keyvalue.second = line.substr(i+1, line.size()); // [sdfsahdds]
}
break; // Only first '=' is parsed
}
}
return keyvalue;
}
map<string, string> *ReadConfiguration(const string * const path)
{
map<string, string> *settings = new map<string, string>();
ifstream file;
file.open(*path);
if (file.fail())
{
WriteLog("ERROR: Could not open configuration file: " + configFile, true);
delete path;
WRITE_EXIT;
throw new exception;
}
string line;
while (getline(file, line))
{
if (line[0] == '#') continue;
else if (line.size() < 3) continue; // Format: 'a=b' is minimum of 3
RemoveSpaces(line); // Remove any whitespace from the config line
auto parsed = ParseLine(line);
settings->operator[](parsed.first) = parsed.second;
}
file.close();
return settings;
}
const updater::ip *ReadIpFromFile(const string * const path)
{
ifstream file;
file.open(*path);
if (file.fail())
{
WriteLog("WARNING: Failed to open IP record file. Trying to create new one with zero record..", true);
ofstream out;
out.open(*path);
if (out.fail()) {
WriteLog("ERROR: Failed to create ip record. Cannot continue.", true);
delete path;
WRITE_EXIT;
throw new exception;
}
out << "0.0.0.0";
out.close();
WriteLog("New IP record file written, returning with zero record.");
return new updater::ip(0, 0, 0, 0);
}
string line;
getline(file, line);
file.close();
updater::ip *addr;
try {
addr = new updater::ip(line);
} catch (const exception &e) {
string msg = "";
msg.append("ERROR: Error while parsing last ip from file: ");
msg.append(e.what());
WriteLog(msg, true);
WRITE_EXIT;
throw;
}
return addr;
}
void UpdateIp(const updater::ip * const ip, const string &url, const string &apikey, const string &apisecret)
{
curlpp::Easy handle;
std::stringstream buffer;
auto authOpt = curlpp::options::HttpHeader({"Content-Type: application/json", "Authorization: sso-key " + apikey + ":" + apisecret});
auto dataOpt = curlpp::Options::PostFields("[{\"data\":\"" + ip->toString() + "\"}]");
handle.setOpt(curlpp::Options::Url(url));
handle.setOpt(curlpp::Options::CustomRequest("PUT"));
handle.setOpt(authOpt);
handle.setOpt(dataOpt);
handle.setOpt(curlpp::Options::SslVerifyHost(false));
handle.setOpt(curlpp::Options::SslVerifyPeer(false));
handle.setOpt(curlpp::Options::WriteStream(&buffer));
handle.setOpt(curlpp::Options::FailOnError(true));
try {
handle.perform();
} catch (curlpp::RuntimeError &e) {
string msg = "";
msg.append("Error while sending update request: ");
msg.append(e.what());
WriteLog(msg, true);
WRITE_EXIT;
throw;
}
string resp;
string strBuf;
// Reading response from buffer
while (buffer >> strBuf) {
resp += strBuf + " ";
}
// Long response indicates a problem
if (resp.length() > 10)
{
WriteLog("Error in update: " + resp, true);
delete ip;
WRITE_EXIT;
throw new exception;
}
}
const updater::ip *QueryIpFromUrl(const string &url, const IpSource &source)
{
if (source == IpSource::router)
{
WriteLog("ERROR: Router ip fetching not yet implemented. Please use clean source for fetching ip address. Set use_router to false.", true);
WRITE_EXIT;
throw new exception;
}
curlpp::Easy handle;
std::stringstream buffer;
handle.setOpt(curlpp::Options::Url(url));
handle.setOpt(curlpp::Options::HttpGet(true));
handle.setOpt(curlpp::Options::SslVerifyHost(false));
handle.setOpt(curlpp::Options::SslVerifyPeer(false));
handle.setOpt(curlpp::Options::WriteStream(&buffer));
handle.setOpt(curlpp::Options::FailOnError(true));
try {
handle.perform();
} catch (curlpp::RuntimeError &e) {
string msg = "";
msg.append("Error while sending ip get request: ");
msg.append(e.what());
WriteLog(msg, true);
WRITE_EXIT;
throw;
}
string resp;
buffer >> resp;
updater::ip *addr;
try {
addr = new updater::ip(resp);
} catch (const std::exception &e) {
string msg = "";
msg.append("ERROR: Error while parsing current remote ip: ");
msg.append(e.what());
WriteLog(msg, true);
WRITE_EXIT;
throw;
}
return addr;
}
void SaveIpToFile(const updater::ip * const ip, const string * const path)
{
ofstream file;
file.open(*path, ios::out);
if (file.fail()) {
WriteLog("ERROR: Failed to open ip record file. Ensure necessary resources and permissions are available for operation.", true);
delete path;
WRITE_EXIT;
throw new exception;
}
file << ip->toString();
file.close();
}
void RemoveSpaces(string &input)
{
if (input == "") return;
auto it = input.begin();
while (it != input.end())
{
if (*it == ' ' || *it == '\t' || *it == '\n' || *it == '\r') {
input.erase(it);
}
it++;
}
}