-
Notifications
You must be signed in to change notification settings - Fork 36
/
main.c
999 lines (838 loc) · 26 KB
/
main.c
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
#include <sys/param.h>
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <strings.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef WIN32
#include <sys/wait.h>
#endif
#include "chaosvpn.h"
static bool r_sigterm = false;
static bool r_sigint = false;
static bool r_sighup = false;
static struct daemon_info di_tincd;
static pid_t pid_tincd_handler;
static int fd_tincd_handler;
static time_t nextupdate = 0;
static struct string HTTP_USER_AGENT;
static bool main_check_root(void);
static bool main_create_backup(struct config*);
static bool main_cleanup_hosts_subdir(struct config*);
static int main_fetch_and_apply_config(struct config* config, struct string* oldconfig);
static void main_free_parsed_info(struct config*);
static bool main_load_previous_config(struct config*, struct string*);
static bool main_parse_config(struct config*, struct string*);
static void main_parse_opts(struct config*, int, char**);
static int main_request_config(struct config*, struct string*);
static void main_tempsave_fetched_config(struct config*, struct string*);
static void main_terminate_old_tincd(struct config*);
static void main_unlink_pidfile(struct config*);
static void main_updated(struct config*);
static void usage(void);
static void main_warn_about_old_tincd(struct config* config);
static void p_sigchild(int);
static void p_sigint(int);
static void p_sigterm(int);
static void p_sighup(int);
/* slave process handler functions */
static pid_t fire_up_tincd_handler(struct config* config);
static void handler_start_tincd(void);
static void handler_restart_tincd(void);
static void handler_stop(void);
static void handler_signal_old_tincd(void);
/* functions only used by slave process */
static void sigchild(int);
static void sigterm(int);
int
main (int argc,char *argv[])
{
struct config *config;
int err;
struct string oldconfig;
#ifdef WIN32
struct WSAData wsa_state;
if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
log_err("WSAStartup failed (%d)", GetLastError());
return 1;
}
#endif
string_init(&HTTP_USER_AGENT, 64, 16);
string_concat_sprintf(&HTTP_USER_AGENT, "ChaosVPN/%s", VERSION);
log_init(&argc, &argv, LOG_PID, LOG_DAEMON);
log_info("ChaosVPN client v%s starting.", VERSION);
crypto_warn_openssl_version_changed();
config = config_alloc();
if (config == NULL) {
log_err("config malloc error\n");
exit(EXIT_FAILURE);
}
main_parse_opts(config, argc, argv);
if (!main_check_root()) {
log_err("Error - wrong user - please start as root user\n");
return 1;
}
if (!tun_check_or_create()) {
log_err("Error - unable to create tun device\n");
return 1;
}
err = !config_init(config);
if (err) return err;
if (config->daemonmode) {
if (!daemonize()) {
log_err("daemonizing into the background failed - aborting\n");
exit(1);
}
}
/* At this point, we've read and parsed our config file */
/* Create pid file if requested */
/* Note that (for now) we do not care about removing this file again */
if (str_is_nonempty(config->pidfile)) {
if (!pidfile_create_pidfile(config->pidfile)) {
log_err("creation of pid file '%s' failed: %s", config->pidfile, strerror(errno));
exit(1);
}
}
/* Fire up the tincd handler which needs root privileges */
pid_tincd_handler = fire_up_tincd_handler(config);
#ifndef WIN32
/* Permanently surrender root privileges */
if (setgid(config->tincd_gid) ||
setuid(config->tincd_uid)) {
log_err("setuid failed.");
exit(1);
}
(void)signal(SIGINT, p_sigint);
(void)signal(SIGTERM, p_sigterm);
(void)signal(SIGHUP, p_sighup);
#endif
string_init(&oldconfig, 4096, 4096);
main_fetch_and_apply_config(config, &oldconfig);
main_warn_about_old_tincd(config);
main_updated(config);
log_info("signalling worker <%d> to kill old tincd.", pid_tincd_handler);
handler_signal_old_tincd();
log_info("signalling worker <%d> to start tincd.", pid_tincd_handler);
handler_start_tincd();
if (!config->oneshot) {
do {
main_updated(config);
while (1) {
(void)sleep(60);
if (r_sighup) {
/* re-init sighup flag and update config */
r_sighup = false;
break;
}
if (nextupdate < time(NULL)) {
break;
}
if (r_sigterm || r_sigint) {
goto bail_out;
}
}
switch (main_fetch_and_apply_config(config, &oldconfig)) {
case -1:
log_err("Error while updating config. Not terminating tincd.");
break;
case 0:
log_info("No update needed.");
break;
default:
log_info("Restarting tincd.");
handler_restart_tincd();
break;
}
} while (!r_sigterm && !r_sigint);
bail_out:
log_info("Terminating tincd.");
handler_stop();
}
string_free(&oldconfig);
config_free(config);
config = NULL;
string_free(&HTTP_USER_AGENT);
return 0;
}
static void
main_updated(struct config *config)
{
nextupdate = time(NULL) + config->update_interval;
}
static int
main_fetch_and_apply_config(struct config* config, struct string* oldconfig)
/*
* Returns:
* -1: Error
* 0: Not changed
* 1: Everything ok
*/
{
int err;
struct string http_response;
log_debug("Fetching information.");
string_init(&http_response, 4096, 512);
err = main_request_config(config, &http_response);
if (err < 1) {
/* errors and "not modified" response */
string_free(&http_response);
if (err < 0) {
/* only warn for errors */
log_warn("Warning: Unable to fetch config; using last stored config.");
}
if (!main_load_previous_config(config, &http_response)) {
string_free(&http_response);
return -1;
}
}
if (string_equals(&http_response, oldconfig)) {
string_free(&http_response);
return 0;
}
err = !main_parse_config(config, &http_response);
if (err) {
string_free(&http_response);
return -1;
}
// tempsave new config
main_tempsave_fetched_config(config, &http_response);
string_free(oldconfig);
string_move(&http_response, oldconfig);
log_debug("Backing up old configs.");
if (!main_create_backup(config)) {
log_warn("Unable to complete config backup copy from %s to %s.old - ignored.", config->base_path, config->base_path);
}
log_debug("Cleanup previous host entries.");
if (!main_cleanup_hosts_subdir(config)) {
log_err("Unable to remove previous host subconfigs from %s/hosts/", config->base_path);
return -1;
}
if (!tinc_write_config(config)) return -1;
if (!tinc_write_hosts(config)) return -1;
if (!tinc_write_updown(config, true)) return -1;
if (!tinc_write_updown(config, false)) return -1;
if (!tinc_write_subnetupdown(config, true)) return -1;
if (!tinc_write_subnetupdown(config, false)) return -1;
main_free_parsed_info(config);
return 1;
}
static void
main_terminate_old_tincd(struct config *config)
{
#ifndef WIN32
pid_t pid;
pid = tinc_get_pid(config);
if (pid == 0)
return;
log_info("Notice: sending SIGTERM to old tincd instance (%d).", pid);
(void)kill(pid, SIGTERM);
(void)sleep(2);
if (kill(pid, SIGKILL) == 0) {
log_warn("Warning: tincd needed SIGKILL; unlinking its pidfile.\n");
// SIGKILL succeeded; hence, we must manually unlink the old pidfile.
main_unlink_pidfile(config);
}
#endif
}
static void
main_parse_opts(struct config *config, int argc, char** argv)
{
int c;
opterr = 0;
while ((c = getopt(argc, argv, "c:p:aofrd")) != -1) {
switch (c) {
case 'c':
free(config->configfile);
config->configfile = strdup(optarg);
break;
case 'p':
free(config->pidfile);
config->pidfile = strdup(optarg);
break;
case 'a': /* legacy */
case 'o':
config->daemonmode = false;
config->oneshot = true;
break;
case 'f': /* legacy */
case 'r':
config->daemonmode = false;
config->oneshot = false;
break;
case 'd':
config->daemonmode = true;
config->oneshot = false;
break;
default:
usage();
}
}
}
static void
usage(void)
{
fprintf(stderr, "chaosvpn - connect to the chaos vpn.\n"
"Usage: chaosvpn [OPTION...]\n\n"
" -c FILE use this user configuration file\n"
" example: -c " TINCDIR "/chaosvpn.conf\n"
" -p FILE create .pid file with specified name\n"
" example: -p /var/run/chaosvpn.pid\n"
" -o oneshot config update and tincd restart, then exit\n"
" -r keep running, controlling tincd (default)\n"
" -d daemon mode, fork into background and keep running\n"
"\n");
exit(EXIT_FAILURE);
}
static void
main_warn_about_old_tincd(struct config* config)
{
if (config->tincd_version &&
(strnatcmp(config->tincd_version, "1.0.12") <= 0)) {
log_warn("Warning: Old tinc version '%s' detected, consider upgrading!\n", config->tincd_version);
}
}
static bool
main_check_root(void)
{
#ifndef WIN32
return getuid() == 0;
#else
return true;
#endif
}
static int
main_request_config(struct config *config, struct string *http_response)
/*
return -1: error
return 0: not modified, 304
return 1: success
*/
{
int retval = -1;
int httpretval;
int httpres;
struct string httpurl;
struct string archive;
struct string chaosvpn_version;
struct string signature;
struct string compressed;
struct string encrypted;
struct string rsa_decrypted;
struct string aes_key;
struct string aes_iv;
char *buf;
time_t startfetchtime;
startfetchtime = time(NULL);
/* fetch main configfile */
crypto_init();
/* basic string inits first, makes for way easier error-cleanup */
string_init(&httpurl, 512, 128);
string_init(&archive, 8192, 8192);
string_lazyinit(&chaosvpn_version, 16);
string_lazyinit(&signature, 1024);
string_lazyinit(&compressed, 8192);
string_lazyinit(&encrypted, 8192);
string_lazyinit(&rsa_decrypted, 1024);
string_lazyinit(&aes_key, 64);
string_lazyinit(&aes_iv, 64);
string_concat_sprintf(&httpurl, "%s?id=%s",
config->master_url, config->peerid);
if ((httpretval = http_get(&httpurl, &archive, config->ifmodifiedsince, &HTTP_USER_AGENT, &httpres, NULL))) {
if (httpretval == HTTP_ESRVERR) {
if (httpres == 304) {
log_info("Not updating from %s - got HTTP %d - not modified\n", string_get(&httpurl), httpres);
retval = 0;
} else {
log_info("Unable to fetch %s - got HTTP %d\n", string_get(&httpurl), httpres);
}
} else if (httpretval == HTTP_EINVURL) {
log_err("\x1B[41;37;1mInvalid URL %s. Only http:// is supported.\x1B[0m\n", string_get(&httpurl));
exit(1);
} else {
log_warn("Unable to fetch %s - maybe server is down. Error code %d.\n", string_get(&httpurl), httpretval);
}
goto bail_out;
}
config->ifmodifiedsince = startfetchtime;
/* check if we received a new-style ar archive */
if (!ar_is_ar_file(&archive)) {
/* if we do not expect a signature than we can still use it
as the raw config (for debugging) */
if (str_is_empty(config->masterdata_signkey)) {
/* move whole received data to http_response */
/* free old contents from http_response first */
string_free(http_response);
string_move(&archive, http_response);
retval = 1; /* no error */
} else {
log_err("Invalid data format received from %s\n", config->master_url);
}
goto bail_out;
}
/* check chaosvpn-version in received ar archive */
if (!ar_extract(&archive, "chaosvpn-version", &chaosvpn_version)) {
string_free(&chaosvpn_version);
log_err("chaosvpn-version missing - can't work with this config\n");
goto bail_out;
}
string_ensurez(&chaosvpn_version);
if (strcmp(string_get(&chaosvpn_version), "3") != 0) {
string_free(&chaosvpn_version);
log_err("unusable data-version from backend, we only support version 3!\n");
goto bail_out;
}
string_free(&chaosvpn_version);
if (str_is_empty(config->masterdata_signkey)) {
/* no public key defined, nothing to verify against or to decrypt with */
/* expect cleartext part */
if (!ar_extract(&archive, "cleartext", http_response)) {
log_err("cleartext part missing - can't work with this config\n");
goto bail_out;
}
/* return success */
retval = 1;
goto bail_out;
}
/* get and decrypt rsa data block */
if (!ar_extract(&archive, "rsa", &encrypted)) {
log_err("rsa part in data from %s missing\n", config->master_url);
goto bail_out;
}
if (!crypto_rsa_decrypt(&encrypted, string_get(&config->privkey), &rsa_decrypted)) {
log_err("rsa decrypt failed\n");
goto bail_out;
}
string_free(&encrypted);
/* check and copy data decrypted from rsa block */
/* structure:
1 byte length aes key
1 byte length aes iv
x bytes aes key
y bytes aes iv
*/
if (string_length(&rsa_decrypted) < 2) {
log_err("rsa decrypt result too short\n");
goto bail_out;
}
buf = string_get(&rsa_decrypted);
if (buf[0] != 32) {
log_err("invalid aes keysize - expected 32, received %d\n", buf[0]);
goto bail_out;
}
if (buf[1] != 16) {
log_err("invalid aes ivsize - expected 16, received %d\n", buf[1]);
goto bail_out;
}
if (string_length(&rsa_decrypted) < buf[0]+buf[1]+2) {
log_err("rsa decrypt result too short\n");
goto bail_out;
}
string_concatb(&aes_key, buf+2, buf[0]);
string_concatb(&aes_iv, buf+2+buf[0], buf[1]);
/* get, decrypt and uncompress config data */
if (!ar_extract(&archive, "encrypted", &encrypted)) {
log_err("encrypted data part in data from %s missing\n", config->master_url);
goto bail_out;
}
if (!crypto_aes_decrypt(&encrypted, &aes_key, &aes_iv, &compressed)) {
log_err("data decrypt failed\n");
goto bail_out;
}
string_free(&encrypted);
if (!uncompress_inflate(&compressed, http_response)) {
log_err("data uncompress failed\n");
goto bail_out;
}
string_free(&compressed);
/* get and decrypt signature */
if (!ar_extract(&archive, "signature", &encrypted)) {
log_err("signature part in data from %s missing\n", config->master_url);
goto bail_out;
}
if (!crypto_aes_decrypt(&encrypted, &aes_key, &aes_iv, &signature)) {
log_err("signature decrypt failed\n");
goto bail_out;
}
string_free(&encrypted);
/* verify signature */
if (crypto_rsa_verify_signature(http_response, &signature, config->masterdata_signkey)) {
retval = 1;
} else {
retval = -1;
}
bail_out:
/* free all strings, even if we may already freed them above */
/* double string_free() is ok, and the error cleanup this way is easier */
string_free(&httpurl);
string_free(&archive);
string_free(&chaosvpn_version);
string_free(&signature);
string_free(&compressed);
string_free(&encrypted);
string_free(&rsa_decrypted);
string_free(&aes_key);
string_free(&aes_iv);
// make sure result is null-terminated
// ar_extract() and crypto_*_decrypt() do not guarantee this!
string_ensurez(http_response);
crypto_finish();
return retval;
}
static bool
main_parse_config(struct config *config, struct string *http_response)
{
struct list_head *p = NULL;
if (!parser_parse_config(string_get(http_response), &config->peer_config)) {
log_err("\nUnable to parse config\n");
return false;
}
list_for_each(p, &config->peer_config) {
struct peer_config_list *i = container_of(p,
struct peer_config_list, list);
if (strcmp(i->peer_config->name, config->peerid) == 0) {
config->my_peer = i->peer_config;
}
}
if (config->my_peer == NULL) {
log_err("Unable to find %s in config.\n", config->peerid);
return false;
}
return true;
}
static void
main_free_parsed_info(struct config* config)
{
parser_free_config(&config->peer_config);
}
static void
main_tempsave_fetched_config(struct config *config, struct string* cnf)
{
static bool NOTMPFILEWARNED = false;
if (str_is_empty(config->tmpconffile)) {
if (NOTMPFILEWARNED) return;
log_debug("Info: not tempsaving fetched config. Set $tmpconffile in chaosvpn.conf to enable.");
NOTMPFILEWARNED = true;
return;
}
string_ensurez(cnf);
if (!fs_writecontents(config->tmpconffile, string_get(cnf), string_length(cnf), 0600)) {
(void)unlink(config->tmpconffile);
log_debug("Error writing $tmpconffile: %s", strerror(errno));
}
}
static bool
main_load_previous_config(struct config *config, struct string* cnf)
{
bool retval = false;
if (str_is_empty(config->tmpconffile)) return false;
if (!fs_read_file(cnf, config->tmpconffile)) {
log_err("Error: unable to read stored config file: %s", strerror(errno));
string_clear(cnf);
goto bail_out;
}
retval = true;
bail_out:
string_ensurez(cnf);
return retval;
}
static bool
main_create_backup(struct config *config)
{
int retval = false;
struct string base_backup_fn;
if (!string_init(&base_backup_fn, 512, 512)) return false; /* don't goto bail_out here */
if (!string_concat(&base_backup_fn, config->base_path)) goto bail_out;
if (!string_concat(&base_backup_fn, ".old")) goto bail_out;
string_ensurez(&base_backup_fn);
retval = fs_cp_r(config->base_path, string_get(&base_backup_fn));
/* fall through */
bail_out:
string_free(&base_backup_fn);
return retval;
}
static bool
main_cleanup_hosts_subdir(struct config *config)
{
bool retval = false;
struct string hosts_dir;
if (!string_init(&hosts_dir, 512, 512)) return false; /* don't goto bail_out here */
if (!string_concat(&hosts_dir, config->base_path)) goto bail_out;
if (!string_concat(&hosts_dir, "/hosts")) goto bail_out;
retval = fs_empty_dir(string_get(&hosts_dir));
/* fall through */
bail_out:
string_free(&hosts_dir);
return retval;
}
static void
main_unlink_pidfile(struct config *config)
{
if (str_is_empty(config->tincd_pidfile))
return;
(void)unlink(config->tincd_pidfile);
}
static void
p_sigint(int sig /*__unused*/)
{
r_sigint = true;
}
static void
p_sigterm(int sig /*__unused*/)
{
r_sigterm = true;
}
static void
p_sighup(int sig /*__unused*/)
{
r_sighup = true;
}
/* ------------------------------------------------------------ */
/* Slave functions. */
static pid_t
fire_up_tincd_handler(struct config* config)
{
#ifndef WIN32
pid_t child;
int pipefds[2];
int pipe2fds[2];
char foo;
char tincd_debugparam[32];
int nfds;
fd_set readfdset;
char stderr_buffer[1024] = "";
if (pipe(pipefds) || pipe(pipe2fds)) {
log_err("Can't create pipe");
exit(1);
}
fd_tincd_handler = pipe2fds[1];
child = fork();
if (child == -1) {
log_err("Can't fire up tincd_handler");
exit(1);
}
if (child) {
/* We are the parent */
(void)close(pipefds[1]);
(void)close(pipe2fds[0]);
(void)signal(SIGCHLD, p_sigchild);
/* Wait for the child to signal its readiness */
if(read(pipefds[0], &foo, 1) != 1) exit(1);
return child;
}
/* We are the child */
(void)close(pipefds[0]);
(void)close(pipe2fds[1]);
(void)signal(SIGINT, SIG_IGN);
snprintf(tincd_debugparam, sizeof(tincd_debugparam), "--debug=%u", config->tincd_debuglevel);
daemon_init(&di_tincd, config->tincd_bin, config->tincd_bin, "-n", config->networkname, tincd_debugparam, NULL);
if (!config->oneshot) {
daemon_addparam(&di_tincd, "-D");
}
if (config->tincd_user) {
daemon_addparam(&di_tincd, "--user");
daemon_addparam(&di_tincd, config->tincd_user);
}
(void)signal(SIGTERM, sigterm);
(void)signal(SIGINT, sigterm);
(void)signal(SIGPIPE, SIG_IGN); /* we ignore SIGPIPE which might be triggered by send() */
(void)signal(SIGCHLD, sigchild);
(void)signal(SIGHUP, SIG_IGN);
/* tell the parent we've started up */
if(write(pipefds[1], &foo, 1) != 1) exit(1);
fcntl(pipefds[1], F_SETFL, O_NONBLOCK);
fcntl(pipe2fds[0], F_SETFL, O_NONBLOCK);
/* sleep forever */
for(;;) {
FD_ZERO(&readfdset);
FD_SET(pipe2fds[0], &readfdset);
nfds = pipe2fds[0];
if (di_tincd.di_stderr) {
if (fileno(di_tincd.di_stderr) > nfds)
nfds = fileno(di_tincd.di_stderr);
FD_SET(fileno(di_tincd.di_stderr), &readfdset);
}
if (select(nfds+1, &readfdset, NULL, NULL, NULL) < 1) {
log_err("select failed: %s", strerror(errno));
sleep(1);
continue;
}
if (FD_ISSET(pipe2fds[0], &readfdset)) {
if(read(pipe2fds[0], &foo, 1) != 1) sigterm(SIGTERM);
switch(foo) {
case HANDLER_START_TINCD:
if (!daemon_start(&di_tincd)) {
log_err("error: unable to run tincd.");
exit(1);
}
if (config->oneshot) exit(0);
break;
case HANDLER_RESTART_TINCD:
daemon_stop(&di_tincd, 5);
tinc_invoke_ifdown(config);
break;
case HANDLER_STOP:
(void)signal(SIGCHLD, SIG_IGN);
tinc_invoke_ifdown(config);
daemon_stop(&di_tincd, 5);
exit(0);
case HANDLER_SIGNAL_OLD_TINCD:
main_terminate_old_tincd(config);
break;
}
}
if (di_tincd.di_stderr && FD_ISSET(fileno(di_tincd.di_stderr), &readfdset)) {
char *end;
size_t len;
size_t tocopy;
char *ret;
len = strlen(stderr_buffer); /* leftovers */
ret = fgets(stderr_buffer + len, sizeof(stderr_buffer) - len - 1, di_tincd.di_stderr);
if (ret == NULL)
continue;
len = strlen(stderr_buffer); /* after read */
while ((end = strchr(stderr_buffer, '\n'))) {
tocopy = len - (end - stderr_buffer);
end[0] = 0;
log_info("tinc.%s[%d] %s", config->networkname, di_tincd.di_pid, stderr_buffer);
if (tocopy > 0)
memmove(stderr_buffer, end+1, tocopy);
else
stderr_buffer[0] = 0;
}
}
}
#endif
}
#ifdef WIN32
static const char *identname = "tinc.chaos";
static const char *description = "Virtual Private Network daemon";
#endif
static void
handler_start_tincd(void)
{
#ifndef WIN32
char buf = HANDLER_START_TINCD;
if(write(fd_tincd_handler, &buf, 1) != 1) exit(1);
#else
SC_HANDLE manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if(!manager) {
log_err("Could not open service manager (%d)", GetLastError());
return;
}
SC_HANDLE service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
if(!service) {
char command[4096];
struct config *config = config_get();
snprintf(command, sizeof command, "%s -n %s -c \"%s\" --debug=%d --logfile=\"%s/tinc.log\%", config->tincd_bin, config->networkname, config->base_path, config->tincd_debuglevel, config->base_path);
service = CreateService(manager, identname, identname, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, command, NULL, NULL, NULL, NULL, NULL);
if(!service) {
log_err("Could not create service %s (%d)", identname, GetLastError());
return;
}
ChangeServiceConfig2(service, SERVICE_CONFIG_DESCRIPTION, &description);
log_info("%s service installed", identname);
}
if(!StartService(service, 0, NULL))
log_err("Could not start %s service (%d)", identname, GetLastError());
else
log_info("%s service started", identname);
#endif
}
static void
handler_restart_tincd(void)
{
#ifndef WIN32
char buf = HANDLER_RESTART_TINCD;
if(write(fd_tincd_handler, &buf, 1) != 1) exit(1);
#else
handler_stop();
handler_start_tincd();
#endif
}
static void
handler_stop(void)
{
#ifndef WIN32
char buf = HANDLER_STOP;
if(write(fd_tincd_handler, &buf, 1) != 1) exit(1);
#else
SC_HANDLE manager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
SC_HANDLE service = OpenService(manager, identname, SERVICE_ALL_ACCESS);
SERVICE_STATUS status = {0};
if(!service) {
log_err("could not find %s service (%d)", identname, GetLastError());
return;
}
if(!ControlService(service, SERVICE_CONTROL_STOP, &status))
log_err("could not stop %s service (%d)", identname, GetLastError());
else
log_info("%s service stopped", identname);
#endif
}
static void
handler_signal_old_tincd(void)
{
#ifndef WIN32
char buf = HANDLER_SIGNAL_OLD_TINCD;
if(write(fd_tincd_handler, &buf, 1) != 1) exit(1);
#else
handler_stop();
#endif
}
#ifndef WIN32
static void
p_sigchild(int sig/*__unused*/)
{
int status;
waitpid(pid_tincd_handler, &status, 0);
log_err("tincd manager slave has died with returncode %d, status %d.", WEXITSTATUS(status), status);
exit(status>>8);
}
#endif
#ifndef WIN32
static void
sigchild(int sig /*__unused*/)
{
struct config *config = config_get();
pid_t pid;
int status;
pid = waitpid(-1, &status, 0);
if ((pid == 0) || (pid == -1 && errno == ECHILD)) {
/* ignore */
} else if (pid == -1) {
log_err("some child has terminated, but waitpid() returned error: %s", strerror(errno));
} else if (pid == di_tincd.di_pid) {
tinc_invoke_ifdown(config);
if (WIFEXITED(status) && (WEXITSTATUS(status) == 1)) {
log_err("tincd reported a fatal error and can't continue, chaosvpn will die now. (pid %d, returncode %d)", pid, WEXITSTATUS(status));
exit(1);
}
log_err("tincd terminated. Restarting in %d seconds. (pid %d, returncode %d)", config->tincd_restart_delay, pid, WEXITSTATUS(status));
if (config->tincd_restart_delay != 0) {
(void)sleep(config->tincd_restart_delay);
}
if (!daemon_start(&di_tincd)) {
log_err("unable to restart tincd. Terminating.");
exit(1);
}
} else {
log_err("some child (pid %d, returncode %d) has terminated; reaping.", pid, WEXITSTATUS(status));
}
}
#endif
static void
sigterm(int sig /*__unused*/)
{
#ifndef WIN32
(void)signal(SIGCHLD, SIG_IGN);
daemon_stop(&di_tincd, 5);
exit(1);
#endif
}