-
Notifications
You must be signed in to change notification settings - Fork 52
/
l2tp_client.c
1555 lines (1338 loc) · 45.1 KB
/
l2tp_client.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
1000
/*
* Client for our custom L2TPv3 brokerage protocol.
*
* Copyright (C) 2012-2014 by Jernej Kos <jernej@kos.mx>
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <syslog.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
#include <netdb.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netlink/netlink.h>
#include <netlink/genl/genl.h>
#include <netlink/genl/mngt.h>
#include <netlink/genl/ctrl.h>
#include <netlink/utils.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <linux/genetlink.h>
#include <linux/l2tp.h>
#ifdef USE_SHARED_LIBASYNCNS
#include <asyncns.h>
#else
#include "libasyncns/asyncns.h"
#endif
// Maximum number of unacknowledged reliable messages.
#define MAX_PENDING_MESSAGES 30
// If this is not defined, build fails on OpenWrt.
#define IP_PMTUDISC_PROBE 3
#define L2TP_CONTROL_SIZE 6
// Overhead of IP and UDP headers for measuring PMTU.
#define IPV4_HDR_OVERHEAD 28
// L2TP data header overhead for calculating tunnel MTU; takes
// the following headers into account:
//
// 20 bytes (IP header)
// 8 bytes (UDP header)
// 4 bytes (L2TPv3 Session ID)
// 4 bytes (L2TPv3 Cookie)
// 4 bytes (L2TPv3 Pseudowire CE)
// 14 bytes (Ethernet)
//
#define L2TP_TUN_OVERHEAD 54
/* Offset of type field in control messages.
* 0 means first byte off our payload in l2tp ctrl message */
#define OFFSET_CONTROL_TYPE 4
enum l2tp_ctrl_type {
// Unreliable messages (0x00 - 0x7F).
CONTROL_TYPE_COOKIE = 0x01,
CONTROL_TYPE_PREPARE = 0x02,
CONTROL_TYPE_ERROR = 0x03,
CONTROL_TYPE_TUNNEL = 0x04,
CONTROL_TYPE_KEEPALIVE = 0x05,
CONTROL_TYPE_PMTUD = 0x06,
CONTROL_TYPE_PMTUD_ACK = 0x07,
CONTROL_TYPE_REL_ACK = 0x08,
CONTROL_TYPE_PMTU_NTFY = 0x09,
CONTROL_TYPE_USAGE = 0x0A,
// Reliable messages (0x80 - 0xFF).
CONTROL_TYPE_LIMIT = 0x80,
};
enum l2tp_error_type {
ERROR_REASON_OTHER_REQUEST = 0x00,
ERROR_REASON_SHUTDOWN = 0x01,
ERROR_REASON_TIMEOUT = 0x02,
ERROR_REASON_FAILURE = 0x03,
};
enum l2tp_error_direction {
ERROR_DIRECTION_SERVER = 0x00,
ERROR_DIRECTION_CLIENT = 0x10,
};
enum l2tp_limit_type {
LIMIT_TYPE_BANDWIDTH_DOWN = 0x01
};
/* The state machine looks as follows:
STATE_REINIT (initial state)
When the FD is successfully initialized:
-> STATE_RESOLVING
When DNS resolving succeeds:
-> STATE_GET_USAGE (sending a usage and a cookie request every 2s)
when we receive usage information or a cookie
-> STATE_STANBDY
Now broker selection is performed; for the selected broker the main loop changes the state so
that we go on:
-> STATE_GET_COOKIE (sending a cookie request every 2s)
when we receive the cookie
-> STATE_GET_TUNNEL
when we receive the tunnel information
-> STATE_KEEPALIVE
when the connection fails
-> STATE_FAILED
In case of an error, we transition to STATE_REINIT (if it happens early) or STATE_FAILED
(if it happens when we are already >= STATE_GET_COOKIE). The main loop restarts everything
once the selected broker enters STATE_FAILED.
For broken brokers, the main loop sets the state to STATE_FAILED to make sure that
they do not do anything.
*/
enum l2tp_ctrl_state {
STATE_REINIT,
STATE_RESOLVING,
STATE_GET_USAGE,
STATE_STANBDY,
STATE_GET_COOKIE,
STATE_GET_TUNNEL,
STATE_KEEPALIVE,
STATE_FAILED,
};
enum l2tp_session_features {
FEATURE_UNIQUE_SESSION_ID = 1 << 0,
FEATURES_MASK = FEATURE_UNIQUE_SESSION_ID,
};
typedef struct reliable_message {
uint16_t seqno;
uint8_t retries;
time_t timer_rexmit;
char *msg;
uint8_t len;
struct reliable_message *next;
} reliable_message;
typedef struct {
// UUID.
char *uuid;
// Tunnel interface name.
char *tunnel_iface;
// Local tunnel identifer.
unsigned int tunnel_id;
// External hook script.
char *hook;
// Local IP endpoint.
struct sockaddr_in local_endpoint;
// Broker hostname.
char *broker_hostname;
// Broker port (or service name).
char *broker_port;
// Broker hostname resolution.
asyncns_query_t *broker_resq;
struct addrinfo broker_reshints;
// Tunnel's UDP socket file descriptor.
int fd;
// Tunnel state.
int state;
// Broker usage.
uint16_t usage;
// Cookie.
char cookie[8];
// Netlink socket.
struct nl_sock *nl_sock;
int nl_family;
// Sequence number for reliable messages.
uint16_t reliable_seqno;
// Sequence number for keep alive.
uint32_t keepalive_seqno;
// List of unacked reliable messages.
reliable_message *reliable_unacked;
// Force the tunnel to go over a certain interface.
char *bind_iface;
// Limits.
uint32_t limit_bandwidth_down;
// Tunnel uptime.
time_t tunnel_up_since;
// PMTU probing.
int pmtu;
int peer_pmtu;
int probed_pmtu;
time_t pmtu_reprobe_interval;
time_t timer_pmtu_reprobe;
time_t timer_pmtu_collect;
time_t timer_pmtu_xmit;
// Last keepalive and timers.
time_t last_alive;
time_t timer_usage;
time_t timer_cookie;
time_t timer_tunnel;
time_t timer_keepalive;
time_t timer_reinit;
time_t timer_resolving;
} l2tp_context;
// Broker configuration.
typedef struct {
char *address;
char *port;
l2tp_context *ctx;
uint8_t broken;
} broker_cfg;
// Maximum number of brokers that can be handled in a single process.
#ifndef MAX_BROKERS
#define MAX_BROKERS 10
#endif
// Forward declarations.
void context_delete_tunnel(l2tp_context *ctx);
void context_close_tunnel(l2tp_context *ctx, uint8_t reason);
int context_session_set_mtu(l2tp_context *ctx);
void context_send_packet(l2tp_context *ctx, uint8_t type, char *payload, uint8_t len);
void context_send_raw_packet(l2tp_context *ctx, char *packet, uint8_t len);
void context_send_reliable_packet(l2tp_context *ctx, uint8_t type, char *payload, uint8_t len);
int context_setup_tunnel(l2tp_context *ctx, uint32_t peer_tunnel_id, uint32_t server_features);
void context_free(l2tp_context *ctx);
void broker_select(broker_cfg *brokers, int broker_cnt);
static l2tp_context *main_context = NULL;
static asyncns_t *asyncns_context = NULL;
int broker_selector_usage(broker_cfg *brokers, int broker_cnt, int ready_cnt)
{
// Select the available broker with the least usage and use it to establish a tunnel.
int i = -1;
int best = -1;
for (i = 0; i < broker_cnt; i++) {
if (brokers[i].ctx->state == STATE_STANBDY &&
(best < 0 || brokers[i].ctx->usage < brokers[best].ctx->usage)) {
best = i;
}
}
return best;
}
int broker_selector_first_available(broker_cfg *brokers, int broker_cnt, int ready_cnt)
{
// Select the first available broker and use it to establish a tunnel.
int i;
for (i = 0; i < broker_cnt; i++) {
if (brokers[i].ctx->state == STATE_STANBDY) {
return i;
}
}
return -1;
}
int broker_selector_random(broker_cfg *brokers, int broker_cnt, int ready_cnt)
{
// Select the r'th available broker and use it to establish a tunnel.
int i;
int r = rand() % ready_cnt;
for (i = 0; i < broker_cnt; i++) {
if (brokers[i].ctx->state == STATE_STANBDY && (r-- == 0)) {
return i;
}
}
return -1;
}
time_t timer_now()
{
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) < 0) {
syslog(LOG_ERR, "Failed to get monotonic clock, weird things may happen!");
return -1;
}
return ts.tv_sec;
}
int is_timeout(time_t *timer, time_t period)
{
if (*timer < 0)
return 0;
time_t now = timer_now();
if (now - *timer > period) {
*timer = now;
return 1;
}
return 0;
}
uint8_t parse_u8(char **buffer)
{
uint8_t value = *((uint8_t*) *buffer);
(*buffer) += sizeof(uint8_t);
return value;
}
uint16_t parse_u16(char **buffer)
{
uint16_t value = ntohs(*((uint16_t*) *buffer));
(*buffer) += sizeof(uint16_t);
return value;
}
uint32_t parse_u32(char **buffer)
{
uint32_t value = ntohl(*((uint32_t*) *buffer));
(*buffer) += sizeof(uint32_t);
return value;
}
void put_u8(char **buffer, uint8_t value)
{
(*buffer)[0] = value;
(*buffer) += sizeof(value);
}
void put_u16(char **buffer, uint16_t value)
{
(*buffer)[0] = value >> 8;
(*buffer)[1] = value;
(*buffer) += sizeof(value);
}
void put_u32(char **buffer, uint32_t value)
{
(*buffer)[0] = value >> 24;
(*buffer)[1] = value >> 16;
(*buffer)[2] = value >> 8;
(*buffer)[3] = value;
(*buffer) += sizeof(value);
}
l2tp_context *context_new(char *uuid, const char *local_ip, const char *broker_hostname,
char *broker_port, char *tunnel_iface, char *bind_iface, char *hook, int tunnel_id, int limit_bandwidth_down)
{
l2tp_context *ctx = (l2tp_context*) calloc(1, sizeof(l2tp_context));
if (!ctx) {
syslog(LOG_ERR, "Failed to allocate memory for context!");
return NULL;
}
ctx->state = STATE_REINIT;
ctx->local_endpoint.sin_family = AF_INET;
ctx->local_endpoint.sin_port = 0;
if (inet_aton(local_ip, &ctx->local_endpoint.sin_addr) < 0) {
syslog(LOG_ERR, "Failed to parse local endpoint!");
goto free_and_return;
}
ctx->broker_hostname = strdup(broker_hostname);
ctx->broker_port = strdup(broker_port);
ctx->uuid = strdup(uuid);
ctx->tunnel_iface = strdup(tunnel_iface);
ctx->tunnel_id = tunnel_id;
ctx->hook = hook ? strdup(hook) : NULL;
ctx->bind_iface = bind_iface ? strdup(bind_iface) : NULL;
// Reset limits.
ctx->limit_bandwidth_down = (uint32_t) limit_bandwidth_down;
// Setup the netlink socket.
ctx->nl_sock = nl_socket_alloc();
if (!ctx->nl_sock) {
syslog(LOG_ERR, "Failed to allocate a netlink socket!");
goto free_and_return;
}
if (nl_connect(ctx->nl_sock, NETLINK_GENERIC) < 0) {
syslog(LOG_ERR, "Failed to connect to netlink!");
goto free_and_return;
}
ctx->nl_family = genl_ctrl_resolve(ctx->nl_sock, L2TP_GENL_NAME);
if (ctx->nl_family < 0) {
syslog(LOG_ERR, "Failed to resolve L2TP netlink interface - check if L2TP kernel modules are loaded!");
goto free_and_return;
}
return ctx;
free_and_return:
context_free(ctx);
return NULL;
}
int context_reinitialize(l2tp_context *ctx)
{
// We have to set this state here to be sure ctx is in a sane state when this functions fails(ret -1)
// because other functions than the state machine call this function.
ctx->state = STATE_REINIT;
if (ctx->fd > 0)
close(ctx->fd);
ctx->fd = socket(AF_INET, SOCK_DGRAM, 0);
if (ctx->fd < 0)
return -1;
// Bind the socket to an interface if given.
if (ctx->bind_iface) {
int rc;
rc = setsockopt(ctx->fd, SOL_SOCKET, SO_BINDTODEVICE, ctx->bind_iface, strlen(ctx->bind_iface) + 1);
if (rc != 0) {
syslog(LOG_ERR, "[%s:%s] Failed to bind to device!",
ctx->broker_hostname, ctx->broker_port);
return -1;
}
}
if (bind(ctx->fd, (struct sockaddr*) &ctx->local_endpoint, sizeof(ctx->local_endpoint)) < 0) {
syslog(LOG_ERR, "[%s:%s] Failed to bind to local endpoint - check WAN connectivity!",
ctx->broker_hostname, ctx->broker_port);
return -1;
}
int val = IP_PMTUDISC_PROBE;
if (setsockopt(ctx->fd, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)) < 0)
return -1;
ctx->keepalive_seqno = 0;
ctx->reliable_seqno = 0;
while (ctx->reliable_unacked != NULL) {
reliable_message *next = ctx->reliable_unacked->next;
free(ctx->reliable_unacked->msg);
free(ctx->reliable_unacked);
ctx->reliable_unacked = next;
}
if (ctx->broker_resq)
asyncns_cancel(asyncns_context, ctx->broker_resq);
ctx->broker_resq = NULL;
ctx->usage = -1;
// Reset relevant timers.
time_t now = timer_now();
ctx->timer_usage = 0;
ctx->timer_cookie = 0;
ctx->timer_tunnel = 0;
ctx->timer_reinit = 0;
ctx->timer_keepalive = now;
ctx->timer_resolving = -1;
// PMTU discovery.
ctx->pmtu = 0;
ctx->peer_pmtu = 0;
ctx->probed_pmtu = 0;
ctx->pmtu_reprobe_interval = 15;
ctx->timer_pmtu_reprobe = now;
ctx->timer_pmtu_collect = -1;
ctx->timer_pmtu_xmit = -1;
ctx->state = STATE_RESOLVING;
// Ensure any tunnels are removed.
context_delete_tunnel(ctx);
return 0;
}
void context_start_connect(l2tp_context *ctx)
{
if (ctx->state != STATE_RESOLVING)
return;
memset(&ctx->broker_reshints, 0, sizeof(struct addrinfo));
ctx->broker_reshints.ai_family = AF_INET;
ctx->broker_reshints.ai_socktype = SOCK_DGRAM;
ctx->broker_resq = asyncns_getaddrinfo(asyncns_context, ctx->broker_hostname, ctx->broker_port,
&ctx->broker_reshints);
ctx->timer_resolving = timer_now();
if (!ctx->broker_resq) {
syslog(LOG_ERR, "[%s:%s] Failed to start name resolution!",
ctx->broker_hostname, ctx->broker_port);
return;
}
}
void context_call_hook(l2tp_context *ctx, const char *hook)
{
if (ctx->hook == NULL)
return;
int pid = fork();
if (pid == 0) {
execl(ctx->hook, ctx->hook, hook, ctx->tunnel_iface, (char*) NULL);
exit(1);
}
}
void context_limit_send_simple_request(l2tp_context *ctx, uint8_t type, uint32_t limit)
{
char buffer[16];
char *buf = buffer;
put_u8(&buf, type);
// Simple request are always a single 4 byte integer.
put_u8(&buf, 4);
put_u32(&buf, limit);
// Now send the packet.
context_send_reliable_packet(ctx, CONTROL_TYPE_LIMIT, (char*) &buffer, 6);
}
void context_setup_limits(l2tp_context *ctx)
{
// Configure downstream bandwidth limit.
if (ctx->limit_bandwidth_down > 0) {
syslog(LOG_INFO, "[%s:%s] Requesting the broker to configure downstream bandwidth limit of %d kbps.",
ctx->broker_hostname, ctx->broker_port, ctx->limit_bandwidth_down);
context_limit_send_simple_request(ctx, LIMIT_TYPE_BANDWIDTH_DOWN, ctx->limit_bandwidth_down);
}
}
void context_process_control_packet(l2tp_context *ctx)
{
char buffer[2048];
struct sockaddr_in endpoint;
socklen_t endpoint_len = sizeof(endpoint);
ssize_t bytes = recvfrom(ctx->fd, &buffer, sizeof(buffer), 0, (struct sockaddr*) &endpoint,
&endpoint_len);
// A valid package must at least 6 byte long.
if (bytes < 6)
return;
// Decode packet header.
char *buf = buffer;
if (parse_u8(&buf) != 0x80 || parse_u16(&buf) != 0x73A7)
return;
// Check version number.
if (parse_u8(&buf) != 1)
return;
uint8_t type = parse_u8(&buf);
uint8_t payload_length = parse_u8(&buf);
uint8_t error_code = 0;
if (payload_length > (bytes - 6))
return;
// Each received packet counts as a liveness indicator.
ctx->last_alive = timer_now();
// Check packet type.
switch (type) {
case CONTROL_TYPE_USAGE: {
if (ctx->state == STATE_GET_USAGE || ctx->state == STATE_STANBDY) {
// Broker usage information. We also received this in STATE_STANBY in case we first got
// a COOKIE, but later also received a USAGE.
ctx->usage = parse_u16(&buf);
syslog(LOG_DEBUG, "[%s:%s] Broker usage: %u\n", ctx->broker_hostname, ctx->broker_port, ctx->usage);
// Mark the connection as being available for later establishment.
ctx->state = STATE_STANBDY;
}
break;
}
case CONTROL_TYPE_COOKIE: {
if (ctx->state == STATE_GET_USAGE || ctx->state == STATE_GET_COOKIE) {
if (payload_length != 8)
break;
memcpy(&ctx->cookie, buf, 8);
if (ctx->state == STATE_GET_COOKIE) {
// Proceed building a tunnel.
ctx->state = STATE_GET_TUNNEL;
} else {
// State STATE_GET_USAGE. We are ready. Do not touch usage; the default is 0xFFFF and
// we may even have also received some usage information.
ctx->state = STATE_STANBDY;
}
}
break;
}
case CONTROL_TYPE_ERROR: {
if (payload_length > 0) {
error_code = parse_u8(&buf);
}
if (ctx->state == STATE_GET_TUNNEL) {
if (payload_length > 0)
syslog(LOG_WARNING, "[%s:%s] Received error response from broker with errorcode %d!",
ctx->broker_hostname, ctx->broker_port, error_code);
else
syslog(LOG_WARNING, "[%s:%s] Received error response from broker!",
ctx->broker_hostname, ctx->broker_port);
ctx->state = STATE_FAILED; // let the main loop restart everything
} else if (ctx->state == STATE_KEEPALIVE) {
if (payload_length > 0)
syslog(LOG_ERR, "[%s:%s] Broker sent us a teardown request, closing tunnel with errorcode %d!",
ctx->broker_hostname, ctx->broker_port, error_code);
else
syslog(LOG_ERR, "[%s:%s] Broker sent us a teardown request, closing tunnel!",
ctx->broker_hostname, ctx->broker_port);
context_close_tunnel(ctx, ERROR_REASON_OTHER_REQUEST);
}
break;
}
case CONTROL_TYPE_TUNNEL: {
if (ctx->state == STATE_GET_TUNNEL) {
if (payload_length < 4)
break;
uint32_t remote_tunnel_id = parse_u32(&buf);
uint32_t server_features = 0;
if (payload_length >= 8)
server_features = parse_u32(&buf);
if (context_setup_tunnel(ctx, remote_tunnel_id, server_features) < 0) {
syslog(LOG_ERR, "[%s:%s] Unable to create local L2TP tunnel!",
ctx->broker_hostname, ctx->broker_port);
ctx->state = STATE_FAILED; // let the main loop restart everything
} else {
syslog(LOG_INFO, "[%s:%s] Tunnel successfully established.",
ctx->broker_hostname, ctx->broker_port);
context_call_hook(ctx, "session.up");
ctx->tunnel_up_since = timer_now();
ctx->state = STATE_KEEPALIVE;
context_setup_limits(ctx);
}
}
break;
}
case CONTROL_TYPE_KEEPALIVE: break;
case CONTROL_TYPE_PMTUD: {
if (ctx->state == STATE_KEEPALIVE) {
// Send back an acknowledgement packet with proper size.
char buffer[16];
char *buf = buffer;
put_u16(&buf, bytes);
context_send_packet(ctx, CONTROL_TYPE_PMTUD_ACK, (char*) &buffer, 2);
}
break;
}
case CONTROL_TYPE_PMTUD_ACK: {
if (ctx->state == STATE_KEEPALIVE) {
if (payload_length != 2)
break;
// Process a PMTU probe.
uint16_t psize = parse_u16(&buf) + IPV4_HDR_OVERHEAD;
if (psize > ctx->probed_pmtu)
ctx->probed_pmtu = psize;
}
break;
}
case CONTROL_TYPE_PMTU_NTFY: {
if (ctx->state == STATE_KEEPALIVE) {
if (payload_length != 2)
break;
// Process a peer PMTU notification message.
uint16_t pmtu = parse_u16(&buf);
if (pmtu != ctx->peer_pmtu) {
ctx->peer_pmtu = pmtu;
context_session_set_mtu(ctx);
}
}
break;
}
case CONTROL_TYPE_REL_ACK: {
if (payload_length != 2)
break;
// ACK of a reliable message.
uint16_t seqno = parse_u16(&buf);
reliable_message *msg = ctx->reliable_unacked;
reliable_message *prev = NULL;
while (msg != NULL) {
if (msg->seqno == seqno) {
// Remove from list.
if (prev == NULL) {
ctx->reliable_unacked = msg->next;
} else {
prev->next = msg->next;
}
free(msg->msg);
free(msg);
return;
}
prev = msg;
msg = msg->next;
}
break;
}
default: return;
}
}
void context_prepare_packet(l2tp_context *ctx, char *buf, uint8_t type, char *payload, uint8_t len)
{
put_u8(&buf, 0x80);
put_u16(&buf, 0x73A7);
put_u8(&buf, 1);
put_u8(&buf, type);
put_u8(&buf, len);
if (payload)
memcpy(buf, payload, len);
}
void context_send_reliable_packet(l2tp_context *ctx, uint8_t type, char *payload, uint8_t len)
{
char *packet = (char*) malloc(L2TP_CONTROL_SIZE + len + 2);
char buffer[512];
char *buf = buffer;
put_u16(&buf, ctx->reliable_seqno);
memcpy(buf, payload, len);
context_prepare_packet(ctx, packet, type, (char*) &buffer, len + 2);
// Store packet to unacked list.
reliable_message *msg = (reliable_message*) malloc(sizeof(reliable_message));
msg->seqno = ctx->reliable_seqno;
msg->retries = 0;
msg->timer_rexmit = timer_now();
msg->msg = packet;
msg->len = L2TP_CONTROL_SIZE + len + 2;
msg->next = NULL;
size_t pending_messages = 0;
if (ctx->reliable_unacked == NULL) {
ctx->reliable_unacked = msg;
} else {
reliable_message *m = ctx->reliable_unacked;
while (m->next != NULL) {
m = m->next;
pending_messages++;
}
m->next = msg;
}
// If there are too many unacked messages, start dropping old ones.
if (pending_messages > MAX_PENDING_MESSAGES) {
reliable_message *m = ctx->reliable_unacked;
ctx->reliable_unacked = m->next;
free(m->msg);
free(m);
}
ctx->reliable_seqno++;
context_send_raw_packet(ctx, msg->msg, msg->len);
}
void context_send_raw_packet(l2tp_context *ctx, char *packet, uint8_t len)
{
if (send(ctx->fd, packet, len, 0) < 0) {
switch (errno) {
case EINVAL: {
// This may happen when the underlying interface is removed. In this case we
// need to bind the socket again and re-initialize the context.
syslog(LOG_WARNING, "[%s:%s] Failed to send() control packet, interface disappeared?",
ctx->broker_hostname, ctx->broker_port);
syslog(LOG_WARNING, "[%s:%s] Forcing tunnel reinitialization.",
ctx->broker_hostname, ctx->broker_port);
ctx->state = STATE_FAILED;
break;
}
default: {
syslog(LOG_WARNING, "[%s:%s] Failed to send() control packet (errno=%d, type=%x)!",
ctx->broker_hostname, ctx->broker_port, errno, packet[OFFSET_CONTROL_TYPE]);
break;
}
}
}
}
void context_send_packet(l2tp_context *ctx, uint8_t type, char *payload, uint8_t len)
{
char buffer[2048];
context_prepare_packet(ctx, &buffer[0], type, payload, len);
// Pad the packet to 12 bytes to avoid it being filtered by some firewalls
// when used over port 53.
if (L2TP_CONTROL_SIZE + len < 12)
len += 12 - L2TP_CONTROL_SIZE - len;
// Send the packet
context_send_raw_packet(ctx, (char*) &buffer, L2TP_CONTROL_SIZE + len);
}
void context_send_pmtu_probe(l2tp_context *ctx, size_t size)
{
char buffer[2048] = {0,};
if (size > 1500 || size < L2TP_CONTROL_SIZE)
return;
char *buf = buffer;
put_u8(&buf, 0x80);
put_u16(&buf, 0x73A7);
put_u8(&buf, 1);
put_u8(&buf, CONTROL_TYPE_PMTUD);
put_u8(&buf, 0);
// Send the packet.
if (send(ctx->fd, &buffer, size - IPV4_HDR_OVERHEAD, 0) < 0) {
switch (errno) {
// Sometimes EAFNOSUPPORT is emitted for messages larger than the local MTU in case of PPPoE.
case EAFNOSUPPORT:
case EMSGSIZE: {
// Message is larger than the local MTU. This is expected.
break;
}
default: {
syslog(LOG_WARNING, "[%s:%s] Failed to send() PMTU probe packet of size %zu (errno=%d)!",
ctx->broker_hostname, ctx->broker_port, size, errno);
break;
}
}
}
}
void context_pmtu_start_discovery(l2tp_context *ctx)
{
size_t sizes[] = {
1334, 1400, 1450, 1476, 1492, 1500
};
int i;
for (i = 0; i < 6; i++) {
context_send_pmtu_probe(ctx, sizes[i]);
}
}
void context_send_setup_request(l2tp_context *ctx)
{
char buffer[512];
char *buf = buffer;
// First 8 bytes of payload is the cookie value.
memcpy(buf, ctx->cookie, 8);
buf += 8;
// Then comes the size-prefixed UUID.
size_t uuid_len = strlen(ctx->uuid);
if (uuid_len > 255)
uuid_len = 255;
put_u8(&buf, uuid_len);
memcpy(buf, ctx->uuid, uuid_len);
buf += uuid_len;
// And the local tunnel identifier.
put_u32(&buf, ctx->tunnel_id);
// And finally, our feature flags.
put_u32(&buf, FEATURES_MASK);
// Now send the packet.
context_send_packet(ctx, CONTROL_TYPE_PREPARE, (char*) &buffer, (buf - &buffer[0]));
}
void context_send_usage_request(l2tp_context *ctx)
{
char buffer[512];
char *buf = buffer;
// First, 8 bytes of padding.
memcpy(buf, "UUUUUUUU", 8);
buf += 8;
// Then our feature flags.
put_u32(&buf, FEATURES_MASK);
// Now send the packet.
context_send_packet(ctx, CONTROL_TYPE_USAGE, (char*) &buffer, (buf - &buffer[0]));
}
void context_delete_tunnel(l2tp_context *ctx)
{
// Take the interface down.
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, ctx->tunnel_iface, sizeof(ifr.ifr_name));
if (ioctl(ctx->fd, SIOCGIFFLAGS, &ifr) == 0) {
ifr.ifr_flags &= ~IFF_UP;
if (ioctl(ctx->fd, SIOCSIFFLAGS, &ifr) < 0) {
syslog(LOG_WARNING, "[%s:%s] Failed to take down interface %s (errno=%d).",
ctx->broker_hostname, ctx->broker_port, ifr.ifr_name, errno);
}
}
// Delete the session.
struct nl_msg *msg = nlmsg_alloc();
genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, ctx->nl_family, 0, NLM_F_REQUEST,
L2TP_CMD_SESSION_DELETE, L2TP_GENL_VERSION);
nla_put_u32(msg, L2TP_ATTR_CONN_ID, ctx->tunnel_id);
nla_put_u32(msg, L2TP_ATTR_SESSION_ID, 1);
nl_send_auto_complete(ctx->nl_sock, msg);
nlmsg_free(msg);
nl_wait_for_ack(ctx->nl_sock);
// Delete the tunnel.
msg = nlmsg_alloc();
genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, ctx->nl_family, 0, NLM_F_REQUEST,
L2TP_CMD_TUNNEL_DELETE, L2TP_GENL_VERSION);
nla_put_u32(msg, L2TP_ATTR_CONN_ID, ctx->tunnel_id);
nl_send_auto_complete(ctx->nl_sock, msg);
nlmsg_free(msg);
nl_wait_for_ack(ctx->nl_sock);
}
int context_setup_tunnel(l2tp_context *ctx, uint32_t peer_tunnel_id, uint32_t server_features)
{
// Create a tunnel.
struct nl_msg *msg = nlmsg_alloc();
genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, ctx->nl_family, 0, NLM_F_REQUEST,
L2TP_CMD_TUNNEL_CREATE, L2TP_GENL_VERSION);
nla_put_u32(msg, L2TP_ATTR_CONN_ID, ctx->tunnel_id);
nla_put_u32(msg, L2TP_ATTR_PEER_CONN_ID, peer_tunnel_id);
nla_put_u8(msg, L2TP_ATTR_PROTO_VERSION, 3);
nla_put_u16(msg, L2TP_ATTR_ENCAP_TYPE, L2TP_ENCAPTYPE_UDP);
nla_put_u32(msg, L2TP_ATTR_FD, ctx->fd);
nl_send_auto_complete(ctx->nl_sock, msg);
nlmsg_free(msg);
int result = nl_wait_for_ack(ctx->nl_sock);
if (result < 0)
return -1;
// Create a session (currently only a single session is supported).
msg = nlmsg_alloc();
genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, ctx->nl_family, 0, NLM_F_REQUEST,
L2TP_CMD_SESSION_CREATE, L2TP_GENL_VERSION);
nla_put_u32(msg, L2TP_ATTR_CONN_ID, ctx->tunnel_id);
if (server_features & FEATURE_UNIQUE_SESSION_ID) {
nla_put_u32(msg, L2TP_ATTR_SESSION_ID, ctx->tunnel_id);
nla_put_u32(msg, L2TP_ATTR_PEER_SESSION_ID, peer_tunnel_id);
} else {
nla_put_u32(msg, L2TP_ATTR_SESSION_ID, 1);
nla_put_u32(msg, L2TP_ATTR_PEER_SESSION_ID, 1);
}
nla_put_u16(msg, L2TP_ATTR_PW_TYPE, L2TP_PWTYPE_ETH);
nla_put_string(msg, L2TP_ATTR_IFNAME, ctx->tunnel_iface);
nl_send_auto_complete(ctx->nl_sock, msg);
nlmsg_free(msg);
result = nl_wait_for_ack(ctx->nl_sock);
if (result < 0) {
// Make sure we delete the tunnel again
msg = nlmsg_alloc();
genlmsg_put(msg, NL_AUTO_PID, NL_AUTO_SEQ, ctx->nl_family, 0, NLM_F_REQUEST,
L2TP_CMD_TUNNEL_DELETE, L2TP_GENL_VERSION);
nla_put_u32(msg, L2TP_ATTR_CONN_ID, ctx->tunnel_id);
nl_send_auto_complete(ctx->nl_sock, msg);
nlmsg_free(msg);
nl_wait_for_ack(ctx->nl_sock);
return -1;
}
return 0;
}
int context_session_set_mtu(l2tp_context *ctx)