]> git.meshlink.io Git - meshlink/blob - src/protocol_auth.c
Remove files not used by MeshLink.
[meshlink] / src / protocol_auth.c
1 /*
2     protocol_auth.c -- handle the meta-protocol, authentication
3     Copyright (C) 1999-2005 Ivo Timmermans,
4                   2000-2014 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include "conf.h"
24 #include "connection.h"
25 #include "control.h"
26 #include "control_common.h"
27 #include "cipher.h"
28 #include "crypto.h"
29 #include "digest.h"
30 #include "ecdsa.h"
31 #include "edge.h"
32 #include "graph.h"
33 #include "logger.h"
34 #include "meta.h"
35 #include "names.h"
36 #include "net.h"
37 #include "netutl.h"
38 #include "node.h"
39 #include "prf.h"
40 #include "protocol.h"
41 #include "rsa.h"
42 #include "script.h"
43 #include "sptps.h"
44 #include "utils.h"
45 #include "xalloc.h"
46
47 ecdsa_t *invitation_key = NULL;
48
49 static bool send_proxyrequest(connection_t *c) {
50         switch(proxytype) {
51                 case PROXY_HTTP: {
52                         char *host;
53                         char *port;
54
55                         sockaddr2str(&c->address, &host, &port);
56                         send_request(c, "CONNECT %s:%s HTTP/1.1\r\n\r", host, port);
57                         free(host);
58                         free(port);
59                         return true;
60                 }
61                 case PROXY_SOCKS4: {
62                         if(c->address.sa.sa_family != AF_INET) {
63                                 logger(DEBUG_ALWAYS, LOG_ERR, "Cannot connect to an IPv6 host through a SOCKS 4 proxy!");
64                                 return false;
65                         }
66                         char s4req[9 + (proxyuser ? strlen(proxyuser) : 0)];
67                         s4req[0] = 4;
68                         s4req[1] = 1;
69                         memcpy(s4req + 2, &c->address.in.sin_port, 2);
70                         memcpy(s4req + 4, &c->address.in.sin_addr, 4);
71                         if(proxyuser)
72                                 memcpy(s4req + 8, proxyuser, strlen(proxyuser));
73                         s4req[sizeof s4req - 1] = 0;
74                         c->tcplen = 8;
75                         return send_meta(c, s4req, sizeof s4req);
76                 }
77                 case PROXY_SOCKS5: {
78                         int len = 3 + 6 + (c->address.sa.sa_family == AF_INET ? 4 : 16);
79                         c->tcplen = 2;
80                         if(proxypass)
81                                 len += 3 + strlen(proxyuser) + strlen(proxypass);
82                         char s5req[len];
83                         int i = 0;
84                         s5req[i++] = 5;
85                         s5req[i++] = 1;
86                         if(proxypass) {
87                                 s5req[i++] = 2;
88                                 s5req[i++] = 1;
89                                 s5req[i++] = strlen(proxyuser);
90                                 memcpy(s5req + i, proxyuser, strlen(proxyuser));
91                                 i += strlen(proxyuser);
92                                 s5req[i++] = strlen(proxypass);
93                                 memcpy(s5req + i, proxypass, strlen(proxypass));
94                                 i += strlen(proxypass);
95                                 c->tcplen += 2;
96                         } else {
97                                 s5req[i++] = 0;
98                         }
99                         s5req[i++] = 5;
100                         s5req[i++] = 1;
101                         s5req[i++] = 0;
102                         if(c->address.sa.sa_family == AF_INET) {
103                                 s5req[i++] = 1;
104                                 memcpy(s5req + i, &c->address.in.sin_addr, 4);
105                                 i += 4;
106                                 memcpy(s5req + i, &c->address.in.sin_port, 2);
107                                 i += 2;
108                                 c->tcplen += 10;
109                         } else if(c->address.sa.sa_family == AF_INET6) {
110                                 s5req[i++] = 3;
111                                 memcpy(s5req + i, &c->address.in6.sin6_addr, 16);
112                                 i += 16;
113                                 memcpy(s5req + i, &c->address.in6.sin6_port, 2);
114                                 i += 2;
115                                 c->tcplen += 22;
116                         } else {
117                                 logger(DEBUG_ALWAYS, LOG_ERR, "Address family %hx not supported for SOCKS 5 proxies!", c->address.sa.sa_family);
118                                 return false;
119                         }
120                         if(i > len)
121                                 abort();
122                         return send_meta(c, s5req, sizeof s5req);
123                 }
124                 case PROXY_SOCKS4A:
125                         logger(DEBUG_ALWAYS, LOG_ERR, "Proxy type not implemented yet");
126                         return false;
127                 case PROXY_EXEC:
128                         return true;
129                 default:
130                         logger(DEBUG_ALWAYS, LOG_ERR, "Unknown proxy type");
131                         return false;
132         }
133 }
134
135 bool send_id(connection_t *c) {
136         gettimeofday(&c->start, NULL);
137
138         int minor = 0;
139
140         if(experimental) {
141                 if(c->outgoing && !read_ecdsa_public_key(c))
142                         minor = 1;
143                 else
144                         minor = myself->connection->protocol_minor;
145         }
146
147         if(proxytype && c->outgoing)
148                 if(!send_proxyrequest(c))
149                         return false;
150
151         return send_request(c, "%d %s %d.%d", ID, myself->connection->name, myself->connection->protocol_major, minor);
152 }
153
154 static bool finalize_invitation(connection_t *c, const char *data, uint16_t len) {
155         if(strchr(data, '\n')) {
156                 logger(DEBUG_ALWAYS, LOG_ERR, "Received invalid key from invited node %s (%s)!\n", c->name, c->hostname);
157                 return false;
158         }
159
160         // Create a new host config file
161         char filename[PATH_MAX];
162         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", confbase, c->name);
163         if(!access(filename, F_OK)) {
164                 logger(DEBUG_ALWAYS, LOG_ERR, "Host config file for %s (%s) already exists!\n", c->name, c->hostname);
165                 return false;
166         }
167
168         FILE *f = fopen(filename, "w");
169         if(!f) {
170                 logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to create %s: %s\n", filename, strerror(errno));
171                 return false;
172         }
173
174         fprintf(f, "ECDSAPublicKey = %s\n", data);
175         fclose(f);
176
177         logger(DEBUG_CONNECTIONS, LOG_INFO, "Key succesfully received from %s (%s)", c->name, c->hostname);
178
179         // Call invitation-accepted script
180         char *envp[7] = {NULL};
181         char *address, *port;
182
183         xasprintf(&envp[0], "NETNAME=%s", netname ? : "");
184         xasprintf(&envp[3], "NODE=%s", c->name);
185         sockaddr2str(&c->address, &address, &port);
186         xasprintf(&envp[4], "REMOTEADDRESS=%s", address);
187         xasprintf(&envp[5], "NAME=%s", myself->name);
188
189         execute_script("invitation-accepted", envp);
190
191         for(int i = 0; envp[i] && i < 7; i++)
192                 free(envp[i]);
193
194         sptps_send_record(&c->sptps, 2, data, 0);
195         return true;
196 }
197
198 static bool receive_invitation_sptps(void *handle, uint8_t type, const char *data, uint16_t len) {
199         connection_t *c = handle;
200
201         if(type == 128)
202                 return true;
203
204         if(type == 1 && c->status.invitation_used)
205                 return finalize_invitation(c, data, len);
206
207         if(type != 0 || len != 18 || c->status.invitation_used)
208                 return false;
209
210         // Recover the filename from the cookie and the key
211         digest_t *digest = digest_open_by_name("sha256", 18);
212         if(!digest)
213                 abort();
214         char *fingerprint = ecdsa_get_base64_public_key(invitation_key);
215         char hashbuf[18 + strlen(fingerprint)];
216         char cookie[25];
217         memcpy(hashbuf, data, 18);
218         memcpy(hashbuf + 18, fingerprint, sizeof hashbuf - 18);
219         digest_create(digest, hashbuf, sizeof hashbuf, cookie);
220         b64encode_urlsafe(cookie, cookie, 18);
221         digest_close(digest);
222         free(fingerprint);
223
224         char filename[PATH_MAX], usedname[PATH_MAX];
225         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", confbase, cookie);
226         snprintf(usedname, sizeof usedname, "%s" SLASH "invitations" SLASH "%s.used", confbase, cookie);
227
228         // Atomically rename the invitation file
229         if(rename(filename, usedname)) {
230                 if(errno == ENOENT)
231                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s tried to use non-existing invitation %s\n", c->hostname, cookie);
232                 else
233                         logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to rename invitation %s\n", cookie);
234                 return false;
235         }
236
237         // Open the renamed file
238         FILE *f = fopen(usedname, "r");
239         if(!f) {
240                 logger(DEBUG_ALWAYS, LOG_ERR, "Error trying to open invitation %s\n", cookie);
241                 return false;
242         }
243
244         // Read the new node's Name from the file
245         char buf[1024];
246         fgets(buf, sizeof buf, f);
247         if(*buf)
248                 buf[strlen(buf) - 1] = 0;
249
250         len = strcspn(buf, " \t=");
251         char *name = buf + len;
252         name += strspn(name, " \t");
253         if(*name == '=') {
254                 name++;
255                 name += strspn(name, " \t");
256         }
257         buf[len] = 0;
258
259         if(!*buf || !*name || strcasecmp(buf, "Name") || !check_id(name)) {
260                 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid invitation file %s\n", cookie);
261                 fclose(f);
262                 return false;
263         }
264
265         free(c->name);
266         c->name = xstrdup(name);
267
268         // Send the node the contents of the invitation file
269         rewind(f);
270         size_t result;
271         while((result = fread(buf, 1, sizeof buf, f)))
272                 sptps_send_record(&c->sptps, 0, buf, result);
273         sptps_send_record(&c->sptps, 1, buf, 0);
274         fclose(f);
275         unlink(usedname);
276
277         c->status.invitation_used = true;
278
279         logger(DEBUG_CONNECTIONS, LOG_INFO, "Invitation %s succesfully sent to %s (%s)", cookie, c->name, c->hostname);
280         return true;
281 }
282
283 bool id_h(connection_t *c, const char *request) {
284         char name[MAX_STRING_SIZE];
285
286         if(sscanf(request, "%*d " MAX_STRING " %d.%d", name, &c->protocol_major, &c->protocol_minor) < 2) {
287                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
288                            c->hostname);
289                 return false;
290         }
291
292         /* Check if this is a control connection */
293
294         if(name[0] == '^' && !strcmp(name + 1, controlcookie)) {
295                 c->status.control = true;
296                 c->allow_request = CONTROL;
297                 c->last_ping_time = now.tv_sec + 3600;
298
299                 free(c->name);
300                 c->name = xstrdup("<control>");
301
302                 return send_request(c, "%d %d %d", ACK, TINC_CTL_VERSION_CURRENT, getpid());
303         }
304
305         if(name[0] == '?') {
306                 if(!invitation_key) {
307                         logger(DEBUG_ALWAYS, LOG_ERR, "Got invitation from %s but we don't have an invitation key", c->hostname);
308                         return false;
309                 }
310
311                 c->ecdsa = ecdsa_set_base64_public_key(name + 1);
312                 if(!c->ecdsa) {
313                         logger(DEBUG_ALWAYS, LOG_ERR, "Got bad invitation from %s", c->hostname);
314                         return false;
315                 }
316
317                 c->status.invitation = true;
318                 char *mykey = ecdsa_get_base64_public_key(invitation_key);
319                 if(!mykey)
320                         return false;
321                 if(!send_request(c, "%d %s", ACK, mykey))
322                         return false;
323                 free(mykey);
324
325                 c->protocol_minor = 2;
326
327                 return sptps_start(&c->sptps, c, false, false, invitation_key, c->ecdsa, "tinc invitation", 15, send_meta_sptps, receive_invitation_sptps);
328         }
329
330         /* Check if identity is a valid name */
331
332         if(!check_id(name)) {
333                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
334                            c->hostname, "invalid name");
335                 return false;
336         }
337
338         /* If this is an outgoing connection, make sure we are connected to the right host */
339
340         if(c->outgoing) {
341                 if(strcmp(c->name, name)) {
342                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
343                                    c->name);
344                         return false;
345                 }
346         } else {
347                 if(c->name)
348                         free(c->name);
349                 c->name = xstrdup(name);
350         }
351
352         /* Check if version matches */
353
354         if(c->protocol_major != myself->connection->protocol_major) {
355                 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) uses incompatible version %d.%d",
356                         c->name, c->hostname, c->protocol_major, c->protocol_minor);
357                 return false;
358         }
359
360         if(bypass_security) {
361                 if(!c->config_tree)
362                         init_configuration(&c->config_tree);
363                 c->allow_request = ACK;
364                 return send_ack(c);
365         }
366
367         if(!experimental)
368                 c->protocol_minor = 0;
369
370         if(!c->config_tree) {
371                 init_configuration(&c->config_tree);
372
373                 if(!read_host_config(c->config_tree, c->name)) {
374                         logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname, c->name);
375                         return false;
376                 }
377
378                 if(experimental)
379                         read_ecdsa_public_key(c);
380         } else {
381                 if(c->protocol_minor && !ecdsa_active(c->ecdsa))
382                         c->protocol_minor = 1;
383         }
384
385         /* Forbid version rollback for nodes whose ECDSA key we know */
386
387         if(ecdsa_active(c->ecdsa) && c->protocol_minor < 2) {
388                 logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) tries to roll back protocol version to %d.%d",
389                         c->name, c->hostname, c->protocol_major, c->protocol_minor);
390                 return false;
391         }
392
393         c->allow_request = METAKEY;
394
395         if(c->protocol_minor >= 2) {
396                 c->allow_request = ACK;
397                 char label[25 + strlen(myself->name) + strlen(c->name)];
398
399                 if(c->outgoing)
400                         snprintf(label, sizeof label, "tinc TCP key expansion %s %s", myself->name, c->name);
401                 else
402                         snprintf(label, sizeof label, "tinc TCP key expansion %s %s", c->name, myself->name);
403
404                 return sptps_start(&c->sptps, c, c->outgoing, false, myself->connection->ecdsa, c->ecdsa, label, sizeof label, send_meta_sptps, receive_meta_sptps);
405         } else {
406                 return send_metakey(c);
407         }
408 }
409
410 bool send_metakey(connection_t *c) {
411         if(!read_rsa_public_key(c))
412                 return false;
413
414         if(!(c->outcipher = cipher_open_blowfish_ofb()))
415                 return false;
416
417         if(!(c->outdigest = digest_open_sha1(-1)))
418                 return false;
419
420         size_t len = rsa_size(c->rsa);
421         char key[len];
422         char enckey[len];
423         char hexkey[2 * len + 1];
424
425         /* Create a random key */
426
427         randomize(key, len);
428
429         /* The message we send must be smaller than the modulus of the RSA key.
430            By definition, for a key of k bits, the following formula holds:
431
432            2^(k-1) <= modulus < 2^(k)
433
434            Where ^ means "to the power of", not "xor".
435            This means that to be sure, we must choose our message < 2^(k-1).
436            This can be done by setting the most significant bit to zero.
437          */
438
439         key[0] &= 0x7F;
440
441         if(!cipher_set_key_from_rsa(c->outcipher, key, len, true))
442                 return false;
443
444         if(debug_level >= DEBUG_SCARY_THINGS) {
445                 bin2hex(key, hexkey, len);
446                 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Generated random meta key (unencrypted): %s", hexkey);
447         }
448
449         /* Encrypt the random data
450
451            We do not use one of the PKCS padding schemes here.
452            This is allowed, because we encrypt a totally random string
453            with a length equal to that of the modulus of the RSA key.
454          */
455
456         if(!rsa_public_encrypt(c->rsa, key, len, enckey)) {
457                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during encryption of meta key for %s (%s)", c->name, c->hostname);
458                 return false;
459         }
460
461         /* Convert the encrypted random data to a hexadecimal formatted string */
462
463         bin2hex(enckey, hexkey, len);
464
465         /* Send the meta key */
466
467         bool result = send_request(c, "%d %d %d %d %d %s", METAKEY,
468                          cipher_get_nid(c->outcipher),
469                          digest_get_nid(c->outdigest), c->outmaclength,
470                          c->outcompression, hexkey);
471
472         c->status.encryptout = true;
473         return result;
474 }
475
476 bool metakey_h(connection_t *c, const char *request) {
477         char hexkey[MAX_STRING_SIZE];
478         int cipher, digest, maclength, compression;
479         size_t len = rsa_size(myself->connection->rsa);
480         char enckey[len];
481         char key[len];
482
483         if(sscanf(request, "%*d %d %d %d %d " MAX_STRING, &cipher, &digest, &maclength, &compression, hexkey) != 5) {
484                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "METAKEY", c->name, c->hostname);
485                 return false;
486         }
487
488         /* Convert the challenge from hexadecimal back to binary */
489
490         int inlen = hex2bin(hexkey, enckey, sizeof enckey);
491
492         /* Check if the length of the meta key is all right */
493
494         if(inlen != len) {
495                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong keylength");
496                 return false;
497         }
498
499         /* Decrypt the meta key */
500
501         if(!rsa_private_decrypt(myself->connection->rsa, enckey, len, key)) {
502                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during decryption of meta key for %s (%s)", c->name, c->hostname);
503                 return false;
504         }
505
506         if(debug_level >= DEBUG_SCARY_THINGS) {
507                 bin2hex(key, hexkey, len);
508                 logger(DEBUG_SCARY_THINGS, LOG_DEBUG, "Received random meta key (unencrypted): %s", hexkey);
509         }
510
511         /* Check and lookup cipher and digest algorithms */
512
513         if(!(c->incipher = cipher_open_by_nid(cipher)) || !cipher_set_key_from_rsa(c->incipher, key, len, false)) {
514                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during initialisation of cipher from %s (%s)", c->name, c->hostname);
515                 return false;
516         }
517
518         if(!(c->indigest = digest_open_by_nid(digest, -1))) {
519                 logger(DEBUG_ALWAYS, LOG_ERR, "Error during initialisation of digest from %s (%s)", c->name, c->hostname);
520                 return false;
521         }
522
523         c->status.decryptin = true;
524
525         c->allow_request = CHALLENGE;
526
527         return send_challenge(c);
528 }
529
530 bool send_challenge(connection_t *c) {
531         size_t len = rsa_size(c->rsa);
532         char buffer[len * 2 + 1];
533
534         if(!c->hischallenge)
535                 c->hischallenge = xrealloc(c->hischallenge, len);
536
537         /* Copy random data to the buffer */
538
539         randomize(c->hischallenge, len);
540
541         /* Convert to hex */
542
543         bin2hex(c->hischallenge, buffer, len);
544
545         /* Send the challenge */
546
547         return send_request(c, "%d %s", CHALLENGE, buffer);
548 }
549
550 bool challenge_h(connection_t *c, const char *request) {
551         char buffer[MAX_STRING_SIZE];
552         size_t len = rsa_size(myself->connection->rsa);
553         size_t digestlen = digest_length(c->indigest);
554         char digest[digestlen];
555
556         if(sscanf(request, "%*d " MAX_STRING, buffer) != 1) {
557                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "CHALLENGE", c->name, c->hostname);
558                 return false;
559         }
560
561         /* Convert the challenge from hexadecimal back to binary */
562
563         int inlen = hex2bin(buffer, buffer, sizeof buffer);
564
565         /* Check if the length of the challenge is all right */
566
567         if(inlen != len) {
568                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge length");
569                 return false;
570         }
571
572         /* Calculate the hash from the challenge we received */
573
574         if(!digest_create(c->indigest, buffer, len, digest))
575                 return false;
576
577         /* Convert the hash to a hexadecimal formatted string */
578
579         bin2hex(digest, buffer, digestlen);
580
581         /* Send the reply */
582
583         c->allow_request = CHAL_REPLY;
584
585         return send_request(c, "%d %s", CHAL_REPLY, buffer);
586 }
587
588 bool chal_reply_h(connection_t *c, const char *request) {
589         char hishash[MAX_STRING_SIZE];
590
591         if(sscanf(request, "%*d " MAX_STRING, hishash) != 1) {
592                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "CHAL_REPLY", c->name,
593                            c->hostname);
594                 return false;
595         }
596
597         /* Convert the hash to binary format */
598
599         int inlen = hex2bin(hishash, hishash, sizeof hishash);
600
601         /* Check if the length of the hash is all right */
602
603         if(inlen != digest_length(c->outdigest)) {
604                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply length");
605                 return false;
606         }
607
608
609         /* Verify the hash */
610
611         if(!digest_verify(c->outdigest, c->hischallenge, rsa_size(c->rsa), hishash)) {
612                 logger(DEBUG_ALWAYS, LOG_ERR, "Possible intruder %s (%s): %s", c->name, c->hostname, "wrong challenge reply");
613                 return false;
614         }
615
616         /* Identity has now been positively verified.
617            Send an acknowledgement with the rest of the information needed.
618          */
619
620         free(c->hischallenge);
621         c->hischallenge = NULL;
622         c->allow_request = ACK;
623
624         return send_ack(c);
625 }
626
627 static bool send_upgrade(connection_t *c) {
628         /* Special case when protocol_minor is 1: the other end is ECDSA capable,
629          * but doesn't know our key yet. So send it now. */
630
631         char *pubkey = ecdsa_get_base64_public_key(myself->connection->ecdsa);
632
633         if(!pubkey)
634                 return false;
635
636         bool result = send_request(c, "%d %s", ACK, pubkey);
637         free(pubkey);
638         return result;
639 }
640
641 bool send_ack(connection_t *c) {
642         if(c->protocol_minor == 1)
643                 return send_upgrade(c);
644
645         /* ACK message contains rest of the information the other end needs
646            to create node_t and edge_t structures. */
647
648         struct timeval now;
649         bool choice;
650
651         /* Estimate weight */
652
653         gettimeofday(&now, NULL);
654         c->estimated_weight = (now.tv_sec - c->start.tv_sec) * 1000 + (now.tv_usec - c->start.tv_usec) / 1000;
655
656         /* Check some options */
657
658         if((get_config_bool(lookup_config(c->config_tree, "IndirectData"), &choice) && choice) || myself->options & OPTION_INDIRECT)
659                 c->options |= OPTION_INDIRECT;
660
661         if((get_config_bool(lookup_config(c->config_tree, "TCPOnly"), &choice) && choice) || myself->options & OPTION_TCPONLY)
662                 c->options |= OPTION_TCPONLY | OPTION_INDIRECT;
663
664         if(myself->options & OPTION_PMTU_DISCOVERY)
665                 c->options |= OPTION_PMTU_DISCOVERY;
666
667         choice = myself->options & OPTION_CLAMP_MSS;
668         get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice);
669         if(choice)
670                 c->options |= OPTION_CLAMP_MSS;
671
672         if(!get_config_int(lookup_config(c->config_tree, "Weight"), &c->estimated_weight))
673                 get_config_int(lookup_config(config_tree, "Weight"), &c->estimated_weight);
674
675         return send_request(c, "%d %s %d %x", ACK, myport, c->estimated_weight, (c->options & 0xffffff) | (experimental ? (PROT_MINOR << 24) : 0));
676 }
677
678 static void send_everything(connection_t *c) {
679         /* Send all known subnets and edges */
680
681         if(disablebuggypeers) {
682                 static struct {
683                         vpn_packet_t pkt;
684                         char pad[MAXBUFSIZE - MAXSIZE];
685                 } zeropkt;
686
687                 memset(&zeropkt, 0, sizeof zeropkt);
688                 zeropkt.pkt.len = MAXBUFSIZE;
689                 send_tcppacket(c, &zeropkt.pkt);
690         }
691
692         if(tunnelserver) {
693                 for splay_each(subnet_t, s, myself->subnet_tree)
694                         send_add_subnet(c, s);
695
696                 return;
697         }
698
699         for splay_each(node_t, n, node_tree) {
700                 for splay_each(subnet_t, s, n->subnet_tree)
701                         send_add_subnet(c, s);
702
703                 for splay_each(edge_t, e, n->edge_tree)
704                         send_add_edge(c, e);
705         }
706 }
707
708 static bool upgrade_h(connection_t *c, const char *request) {
709         char pubkey[MAX_STRING_SIZE];
710
711         if(sscanf(request, "%*d " MAX_STRING, pubkey) != 1) {
712                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name, c->hostname);
713                 return false;
714         }
715
716         if(ecdsa_active(c->ecdsa) || read_ecdsa_public_key(c)) {
717                 logger(DEBUG_ALWAYS, LOG_INFO, "Already have ECDSA public key from %s (%s), not upgrading.", c->name, c->hostname);
718                 return false;
719         }
720
721         logger(DEBUG_ALWAYS, LOG_INFO, "Got ECDSA public key from %s (%s), upgrading!", c->name, c->hostname);
722         append_config_file(c->name, "ECDSAPublicKey", pubkey);
723         c->allow_request = TERMREQ;
724         return send_termreq(c);
725 }
726
727 bool ack_h(connection_t *c, const char *request) {
728         if(c->protocol_minor == 1)
729                 return upgrade_h(c, request);
730
731         char hisport[MAX_STRING_SIZE];
732         char *hisaddress;
733         int weight, mtu;
734         uint32_t options;
735         node_t *n;
736         bool choice;
737
738         if(sscanf(request, "%*d " MAX_STRING " %d %x", hisport, &weight, &options) != 3) {
739                 logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ACK", c->name,
740                            c->hostname);
741                 return false;
742         }
743
744         /* Check if we already have a node_t for him */
745
746         n = lookup_node(c->name);
747
748         if(!n) {
749                 n = new_node();
750                 n->name = xstrdup(c->name);
751                 node_add(n);
752         } else {
753                 if(n->connection) {
754                         /* Oh dear, we already have a connection to this node. */
755                         logger(DEBUG_CONNECTIONS, LOG_DEBUG, "Established a second connection with %s (%s), closing old connection", n->connection->name, n->connection->hostname);
756
757                         if(n->connection->outgoing) {
758                                 if(c->outgoing)
759                                         logger(DEBUG_ALWAYS, LOG_WARNING, "Two outgoing connections to the same node!");
760                                 else
761                                         c->outgoing = n->connection->outgoing;
762
763                                 n->connection->outgoing = NULL;
764                         }
765
766                         terminate_connection(n->connection, false);
767                         /* Run graph algorithm to purge key and make sure up/down scripts are rerun with new IP addresses and stuff */
768                         graph();
769                 }
770         }
771
772         n->connection = c;
773         c->node = n;
774         if(!(c->options & options & OPTION_PMTU_DISCOVERY)) {
775                 c->options &= ~OPTION_PMTU_DISCOVERY;
776                 options &= ~OPTION_PMTU_DISCOVERY;
777         }
778         c->options |= options;
779
780         if(get_config_int(lookup_config(c->config_tree, "PMTU"), &mtu) && mtu < n->mtu)
781                 n->mtu = mtu;
782
783         if(get_config_int(lookup_config(config_tree, "PMTU"), &mtu) && mtu < n->mtu)
784                 n->mtu = mtu;
785
786         if(get_config_bool(lookup_config(c->config_tree, "ClampMSS"), &choice)) {
787                 if(choice)
788                         c->options |= OPTION_CLAMP_MSS;
789                 else
790                         c->options &= ~OPTION_CLAMP_MSS;
791         }
792
793         /* Activate this connection */
794
795         c->allow_request = ALL;
796         c->status.active = true;
797
798         logger(DEBUG_CONNECTIONS, LOG_NOTICE, "Connection with %s (%s) activated", c->name,
799                            c->hostname);
800
801         /* Send him everything we know */
802
803         send_everything(c);
804
805         /* Create an edge_t for this connection */
806
807         c->edge = new_edge();
808         c->edge->from = myself;
809         c->edge->to = n;
810         sockaddr2str(&c->address, &hisaddress, NULL);
811         c->edge->address = str2sockaddr(hisaddress, hisport);
812         free(hisaddress);
813         c->edge->weight = (weight + c->estimated_weight) / 2;
814         c->edge->connection = c;
815         c->edge->options = c->options;
816
817         edge_add(c->edge);
818
819         /* Notify everyone of the new edge */
820
821         if(tunnelserver)
822                 send_add_edge(c, c->edge);
823         else
824                 send_add_edge(everyone, c->edge);
825
826         /* Run MST and SSSP algorithms */
827
828         graph();
829
830         return true;
831 }