Merge from Master
[l2tpns.git] / l2tpns.h
1 // L2TPNS Global Stuff
2 // $Id: l2tpns.h,v 1.121 2009-12-08 14:49:28 bodea Exp $
3
4 #ifndef __L2TPNS_H__
5 #define __L2TPNS_H__
6
7 #include <netinet/in.h>
8 #include <stdio.h>
9 #include <signal.h>
10 #include <stdlib.h>
11 #include <netinet/in.h>
12 #include <net/ethernet.h>
13 #include <sys/socket.h>
14 #include <arpa/inet.h>
15 #include <sys/types.h>
16 #include <libcli.h>
17
18 #define VERSION "2.2.1-2sames3.14"
19
20 // Limits
21 #define MAXTUNNEL 500 // could be up to 65535
22 #define MAXBUNDLE 300 // could be up to 65535
23 #define MAXBUNDLESES 12 // Maximum number of member links in bundle
24 #define MAXADDRESS 20 // Maximum length for the Endpoint Discrminiator address
25 #define MAXSESSION 60000 // could be up to 65535
26 #define MAXTBFS 6000 // Maximum token bucket filters. Might need up to 2 * session.
27 #define MAXSESSINGRP 12 // Maximum number of member links in grouped session
28 #define MAXGROUPE 300 // could be up to 65535, Maximum number of grouped session
29 #define MAXROUTEINGRP 15 // max static routes per group
30
31 // Tunnel Id reserved for pppoe
32 #define TUNNEL_ID_PPPOE 1
33
34 #define RADIUS_SHIFT 6
35 #define RADIUS_FDS (1 << RADIUS_SHIFT)
36 #define RADIUS_MASK ((1 << RADIUS_SHIFT) - 1)
37 #define MAXRADIUS (1 << (8 + RADIUS_SHIFT))
38
39 #define T_UNDEF (0xffff) // A tunnel ID that won't ever be used. Mark session as undefined.
40 #define T_FREE (0) // A tunnel ID that won't ever be used. Mark session as free.
41
42 #define MAXCONTROL 1000 // max length control message we ever send...
43 #define MINMTU 576 // minimum recommended MTU (rfc1063)
44 #define MAXMTU 2600 // arbitrary maximum MTU
45 #define PPPoE_MRU 1492 // maximum PPPoE MRU (rfc2516: 1500 less PPPoE header (6) and PPP protocol ID (2))
46 #define MAXETHER (MAXMTU+18) // max packet we try sending to tun
47 #define MAXTEL 96 // telephone number
48 #define MAXHOSTNAME 256 // hostname
49 #define MAXUSER 128 // username
50 #define MAXPASS 128 // password
51 #define MAXCLASS 128 // radius class attribute size
52 #define MAXPLUGINS 20 // maximum number of plugins to load
53 #define MAXRADSERVER 10 // max radius servers
54 #define MAXROUTE 10 // max static routes per session
55 #define MAXIPPOOL 131072 // max number of ip addresses in pool
56 #define RINGBUFFER_SIZE 10000 // Number of ringbuffer entries to allocate
57 #define MAX_LOG_LENGTH 512 // Maximum size of log message
58 #define ECHO_TIMEOUT 10 // Time between last packet sent and LCP ECHO generation
59 #define IDLE_ECHO_TIMEOUT 240 // Time between last packet seen and session shutdown
60 #define BUSY_WAIT_TIME 3000 // 5 minutes in 1/10th seconds to wait for radius to cleanup on shutdown
61
62 #define MP_BEGIN 0x80 // This value is used when (b)egin bit is set in MP header
63 #define MP_END 0x40 // This value is used when (e)nd bit is set in MP header
64 #define MP_BOTH_BITS 0xC0 // This value is used when both bits (begin and end) are set in MP header
65
66 #define MINFRAGLEN 64 // Minumum fragment length
67 #define MAXFRAGLEN 1496 // Maximum length for Multilink fragment (The multilink may contain only one link)
68 #define MAXFRAGNUM 512 // Maximum number of Multilink fragment in a bundle (must be in the form of 2^X)
69 // it's not expected to have a space for more than 10 unassembled packets = 10 * MAXBUNDLESES
70 #define MAXFRAGNUM_MASK (MAXFRAGNUM - 1) // Must be equal to MAXFRAGNUM-1
71
72 // Multi bind address constants
73 #define MAX_UDPFD 4
74 #define MAX_BINDADDR MAX_UDPFD
75 // + 1 for the LAC Hostname
76 #define MAX_NBHOSTNAME (MAX_UDPFD + 1)
77 // 4 + 1 for the udplac
78 #define INIT_TABUDPFD {-1, -1, -1, -1, -1}
79 #define INIT_TABUDPVAR {0, 0, 0, 0, 0}
80
81 // Constants
82 #ifndef ETCDIR
83 #define ETCDIR "/etc/l2tpns"
84 #endif
85
86 #ifndef LIBDIR
87 #define LIBDIR "/usr/lib/l2tpns"
88 #endif
89
90 #ifndef PLUGINDIR
91 #define PLUGINDIR LIBDIR // Plugins
92 #endif
93
94 #ifndef PLUGINCONF
95 #define PLUGINCONF ETCDIR // Plugin config dir
96 #endif
97
98 #ifndef FLASHDIR
99 #define FLASHDIR ETCDIR
100 #endif
101
102 #define TUNDEVICE "/dev/net/tun"
103 #define RANDOMDEVICE "/dev/urandom" // default, not as secure as /dev/random but non-blocking
104 #define CONFIGFILE FLASHDIR "/startup-config" // Configuration file
105 #define CLIUSERS FLASHDIR "/users" // CLI Users file
106 #define IPPOOLFILE FLASHDIR "/ip_pool" // Address pool configuration
107 #define ACCT_TIME 3000 // 5 minute accounting interval
108 #define ACCT_SHUT_TIME 600 // 1 minute for counters of shutdown sessions
109 #define L2TPPORT 1701 // L2TP port
110 #define RADPORT 1645 // old radius port...
111 #define DAEPORT 3799 // DAE port
112 #define PKTARP 0x0806 // ARP packet type
113 #define PKTIP 0x0800 // IPv4 packet type
114 #define PKTIPV6 0x86DD // IPv6 packet type
115 #define PPPPAP 0xC023
116 #define PPPCHAP 0xC223
117 #define PPPLCP 0xC021
118 #define PPPIPCP 0x8021
119 #define PPPIPV6CP 0x8057
120 #define PPPCCP 0x80FD
121 #define PPPIP 0x0021
122 #define PPPIPV6 0x0057
123 #define PPPMP 0x003D
124 #define MIN_IP_SIZE 0x19
125
126 enum {
127 ConfigReq = 1,
128 ConfigAck,
129 ConfigNak,
130 ConfigRej,
131 TerminateReq,
132 TerminateAck,
133 CodeRej,
134 ProtocolRej,
135 EchoReq,
136 EchoReply,
137 DiscardRequest,
138 IdentRequest
139 };
140
141 enum {
142 AccessRequest = 1,
143 AccessAccept,
144 AccessReject,
145 AccountingRequest,
146 AccountingResponse,
147 AccessChallenge = 11,
148 DisconnectRequest = 40,
149 DisconnectACK,
150 DisconnectNAK,
151 CoARequest,
152 CoAACK,
153 CoANAK
154 };
155
156 // PPP phases
157 enum {
158 Dead,
159 Establish,
160 Authenticate,
161 Network,
162 Terminate
163 };
164
165 // PPP states
166 enum {
167 Initial,
168 Starting,
169 Closed,
170 Stopped,
171 Closing,
172 Stopping,
173 RequestSent,
174 AckReceived,
175 AckSent,
176 Opened
177 };
178
179 // reset state machine counters
180 #define initialise_restart_count(_s, _fsm) \
181 sess_local[_s]._fsm.conf_sent = \
182 sess_local[_s]._fsm.nak_sent = 0
183
184 // no more attempts
185 #define zero_restart_count(_s, _fsm) ({ \
186 sess_local[_s]._fsm.conf_sent = \
187 config->ppp_max_configure; \
188 sess_local[_s]._fsm.restart = \
189 time_now + config->ppp_restart_time; \
190 })
191
192 // increment ConfReq counter and reset timer
193 #define restart_timer(_s, _fsm) ({ \
194 sess_local[_s]._fsm.conf_sent++; \
195 sess_local[_s]._fsm.restart = \
196 time_now + config->ppp_restart_time; \
197 })
198
199 // stop timer on change to state where timer does not run
200 #define change_state(_s, _fsm, _new) ({ \
201 if (_new != session[_s].ppp._fsm) \
202 { \
203 switch (_new) \
204 { \
205 case Initial: \
206 case Starting: \
207 case Closed: \
208 case Stopped: \
209 case Opened: \
210 sess_local[_s]._fsm.restart = 0; \
211 initialise_restart_count(_s, _fsm); \
212 } \
213 session[_s].ppp._fsm = _new; \
214 cluster_send_session(_s); \
215 } \
216 })
217
218 // Types
219 typedef uint16_t sessionidt;
220 typedef uint16_t bundleidt;
221 typedef uint16_t tunnelidt;
222 typedef uint16_t groupidt;
223 typedef uint32_t clockt;
224 typedef uint8_t hasht[16];
225
226 // CLI actions
227 struct cli_session_actions {
228 char action;
229 in_addr_t snoop_ip;
230 uint16_t snoop_port;
231 int throttle_in;
232 int throttle_out;
233 int filter_in;
234 int filter_out;
235 };
236
237 #define CLI_SESS_KILL 0x01
238 #define CLI_SESS_SNOOP 0x02
239 #define CLI_SESS_NOSNOOP 0x04
240 #define CLI_SESS_THROTTLE 0x08
241 #define CLI_SESS_NOTHROTTLE 0x10
242 #define CLI_SESS_FILTER 0x20
243 #define CLI_SESS_NOFILTER 0x40
244
245 struct cli_tunnel_actions {
246 char action;
247 };
248
249 #define CLI_TUN_KILL 0x01
250
251 // structures
252 typedef struct // route
253 {
254 in_addr_t ip;
255 int prefixlen;
256 }
257 routet;
258
259 typedef struct controls // control message
260 {
261 struct controls *next; // next in queue
262 uint16_t length; // length
263 uint8_t buf[MAXCONTROL];
264 }
265 controlt;
266
267 typedef struct {
268 uint8_t length; // Endpoint Discriminator length
269 uint8_t addr_class; // Endpoint Discriminator class
270 uint8_t address[MAXADDRESS]; // Endpoint Discriminator address
271 } epdist;
272
273 typedef struct {
274 sessionidt sid; // Fragment originating session
275 tunnelidt tid; // Fragment originating tunnel
276 uint8_t flags; // MP frame flags
277 uint32_t seq; // fragment seq num
278 uint32_t jitteravg;
279 uint16_t length; // Fragment length
280 uint8_t data[MAXFRAGLEN]; // Fragment data
281 } fragmentt;
282
283 typedef struct
284 {
285 sessionidt next; // next session in linked list
286 sessionidt far; // far end session ID
287 tunnelidt tunnel; // near end tunnel ID
288 uint8_t flags; // session flags: see SESSION_*
289 struct {
290 uint8_t phase; // PPP phase
291 uint8_t lcp:4; // LCP state
292 uint8_t ipcp:4; // IPCP state
293 uint8_t ipv6cp:4; // IPV6CP state
294 uint8_t ccp:4; // CCP state
295 } ppp;
296 uint16_t mru; // maximum receive unit
297 in_addr_t ip; // IP of session set by RADIUS response (host byte order).
298 int ip_pool_index; // index to IP pool
299 uint32_t unique_id; // unique session id
300 uint32_t magic; // ppp magic number
301 uint32_t pin, pout; // packet counts
302 uint32_t cin, cout; // byte counts
303 uint32_t cin_wrap, cout_wrap; // byte counter wrap count (RADIUS accounting giagawords)
304 uint32_t cin_delta, cout_delta; // byte count changes (for dump_session())
305 uint16_t throttle_in; // upstream throttle rate (kbps)
306 uint16_t throttle_out; // downstream throttle rate
307 uint8_t filter_in; // input filter index (to ip_filters[N-1]; 0 if none)
308 uint8_t filter_out; // output filter index
309 uint16_t snoop_port; // Interception destination port
310 in_addr_t snoop_ip; // Interception destination IP
311 clockt opened; // when started
312 clockt die; // being closed, when to finally free
313 uint32_t session_timeout; // Maximum session time in seconds
314 uint32_t idle_timeout; // Maximum idle time in seconds
315 time_t last_packet; // Last packet from the user (used for idle timeouts)
316 time_t last_data; // Last data packet to/from the user (used for idle timeouts)
317 in_addr_t dns1, dns2; // DNS servers
318 routet route[MAXROUTE]; // static routes
319 uint16_t tbf_in; // filter bucket for throttling in from the user.
320 uint16_t tbf_out; // filter bucket for throttling out to the user.
321 int random_vector_length;
322 uint8_t random_vector[MAXTEL];
323 char user[MAXUSER]; // user (needed in session for radius stop messages)
324 char called[MAXTEL]; // called number
325 char calling[MAXTEL]; // calling number
326 uint32_t tx_connect_speed;
327 uint32_t rx_connect_speed;
328 clockt timeout; // Session timeout
329 uint32_t mrru; // Multilink Max-Receive-Reconstructed-Unit
330 epdist epdis; // Multilink Endpoint Discriminator
331 bundleidt bundle; // Multilink Bundle Identifier
332 uint8_t mssf; // Multilink Short Sequence Number Header Format
333 uint8_t walled_garden; // is this session gardened?
334 uint8_t classlen; // class (needed for radius accounting messages)
335 char class[MAXCLASS];
336 uint8_t ipv6prefixlen; // IPv6 route prefix length
337 struct in6_addr ipv6route; // Static IPv6 route
338 sessionidt forwardtosession; // LNS id_session to forward
339 uint8_t src_hwaddr[ETH_ALEN]; // MAC addr source (for pppoe sessions 6 bytes)
340 uint32_t dhcpv6_prefix_iaid; // prefix iaid requested by client
341 uint32_t dhcpv6_iana_iaid; // iaid of iana requested by client
342 struct in6_addr ipv6address; // Framed Ipv6 address
343 struct dhcp6_opt_clientid dhcpv6_client_id; // Size max (headers + DUID)
344 char reserved[4]; // Space to expand structure without changing HB_VERSION
345 }
346 sessiont;
347
348 typedef struct
349 {
350 uint32_t tx_rate;
351 uint32_t prev_coutgrp;
352 sessionidt sid;
353 uint8_t weight;
354 }
355 groupsesslistt;
356
357 typedef struct
358 {
359 int state; // current state (groupestate enum)
360 uint32_t time_changed;
361 groupidt prev;
362 sessionidt smax;
363 sessionidt smin;
364 groupsesslistt sesslist[MAXSESSINGRP];
365 routet route[MAXROUTEINGRP]; // static routes
366 uint8_t nbroutesgrp;
367 uint8_t nbsession;
368 }
369 groupsesst;
370
371 union iphash
372 {
373 sessionidt sess;
374 union iphash *idx;
375 }; // Mapping from IP address to session structures.
376
377 typedef struct
378 {
379 int state; // current state (bundlestate enum)
380 uint32_t seq_num_t; // Sequence Number (transmission)
381 uint32_t timeout; // Session-Timeout for bundle
382 uint32_t max_seq; // Max value of sequence number field
383 uint8_t num_of_links; // Number of links joint to this bundle
384 uint32_t online_time; // The time this bundle is online
385 clockt last_check; // Last time the timeout is checked
386 uint32_t mrru; // Multilink Max-Receive-Reconstructed-Unit
387 uint8_t mssf; // Multilink Short Sequence Number Header Format
388 epdist epdis; // Multilink Endpoint Discriminator
389 char user[MAXUSER]; // Needed for matching member links
390 sessionidt current_ses; // Current session to use for sending (used in RR load-balancing)
391 sessionidt members[MAXBUNDLESES]; // Array for member links sessions
392 }
393 bundlet;
394
395 typedef struct
396 {
397 fragmentt fragment[MAXFRAGNUM];
398 uint8_t reassembled_frame[MAXETHER]; // The reassembled frame
399 uint16_t re_frame_len; // The reassembled frame length
400 uint16_t re_frame_begin_index, re_frame_end_index; // reassembled frame begin index, end index respectively
401 uint16_t start_index, end_index; // start and end sequence numbers available on the fragments array respectively
402 uint32_t M; // Minumum frame sequence number received over all bundle members
403 uint32_t start_seq; // Last received frame sequence number (bearing B bit)
404 }
405 fragmentationt;
406
407 #define AUTHPAP 1 // allow PAP
408 #define AUTHCHAP 2 // allow CHAP
409
410 typedef struct
411 {
412 // packet counters
413 uint32_t pin;
414 uint32_t pout;
415
416 // byte counters
417 uint32_t cin;
418 uint32_t cout;
419
420 // PPP restart timer/counters
421 struct {
422 time_t restart;
423 int conf_sent;
424 int nak_sent;
425 } lcp, ipcp, ipv6cp, ccp;
426
427 // identifier for Protocol-Reject, Code-Reject
428 uint8_t lcp_ident;
429
430 // authentication to use
431 int lcp_authtype;
432
433 // our MRU
434 uint16_t ppp_mru;
435
436 // our MRRU
437 uint16_t mp_mrru;
438
439 // our mssf
440 uint16_t mp_mssf;
441
442 // our Endpoint Discriminator
443 in_addr_t mp_epdis;
444
445 // DoS prevention
446 clockt last_packet_out;
447 uint32_t packets_out;
448 uint32_t packets_dropped;
449
450 // RADIUS session in use
451 uint16_t radius;
452
453 // interim RADIUS
454 time_t last_interim;
455
456 // last LCP Echo
457 time_t last_echo;
458
459 // Last Multilink frame sequence number received
460 uint32_t last_seq;
461
462 // jitter average of the session
463 uint32_t jitteravg;
464 // time in milliseconds of the last fragment.
465 uint64_t prev_time;
466 } sessionlocalt;
467
468 // session flags
469 #define SESSION_PFC (1 << 0) // use Protocol-Field-Compression
470 #define SESSION_ACFC (1 << 1) // use Address-and-Control-Field-Compression
471 #define SESSION_STARTED (1 << 2) // RADIUS Start record sent
472
473 // 328 bytes per tunnel
474 typedef struct
475 {
476 tunnelidt far; // far end tunnel ID
477 in_addr_t ip; // Ip for far end
478 uint16_t port; // port for far end
479 uint16_t window; // Rx window
480 uint16_t nr; // next receive
481 uint16_t ns; // next send
482 int state; // current state (tunnelstate enum)
483 clockt last; // when last control message sent (used for resend timeout)
484 clockt retry; // when to try resending pending control
485 clockt die; // being closed, when to finally free
486 clockt lastrec; // when the last control message was received
487 char hostname[128]; // tunnel hostname
488 char vendor[128]; // LAC vendor
489 uint8_t try; // number of retrys on a control message
490 uint16_t controlc; // outstaind messages in queue
491 controlt *controls; // oldest message
492 controlt *controle; // newest message
493 uint16_t isremotelns; // != 0 if the tunnel is to remote LNS (== index on the conf remote lns)
494 uint16_t indexudp; // Index UDP file handle (in udpfd[])
495 char reserved[12]; // Space to expand structure without changing HB_VERSION
496 }
497 tunnelt;
498
499 // 164 bytes per radius session
500 typedef struct // outstanding RADIUS requests
501 {
502 sessionidt session; // which session this applies to
503 hasht auth; // request authenticator
504 clockt retry; // when to try next
505 char pass[129]; // password
506 uint8_t id; // ID for PPP response
507 uint8_t try; // which try we are on
508 uint8_t state; // state of radius requests
509 uint8_t chap; // set if CHAP used (is CHAP identifier)
510 uint8_t term_cause; // Stop record: Acct-Terminate-Cause
511 char const *term_msg; // terminate reason
512 }
513 radiust;
514
515 typedef struct
516 {
517 in_addr_t address; // Host byte order..
518 char assigned; // 1 if assigned, 0 if free
519 sessionidt session;
520 clockt last; // last used
521 char user[129]; // user (try to have ip addresses persistent)
522 }
523 ippoolt;
524
525 #ifdef RINGBUFFER
526 struct Tringbuffer
527 {
528 struct {
529 char level;
530 sessionidt session;
531 tunnelidt tunnel;
532 char message[MAX_LOG_LENGTH];
533 } buffer[RINGBUFFER_SIZE];
534 int head;
535 int tail;
536 };
537 #endif
538
539 /*
540 * Possible tunnel states
541 * TUNNELFREE -> TUNNELOPEN -> TUNNELDIE -> TUNNELFREE
542 */
543 enum
544 {
545 TUNNELFREE, // Not in use
546 TUNNELOPEN, // Active tunnel
547 TUNNELDIE, // Currently closing
548 TUNNELOPENING, // Busy opening
549 TUNNELUNDEF, // Undefined
550 };
551
552 enum
553 {
554 BUNDLEFREE, // Not in use
555 BUNDLEOPEN, // Active bundle
556 BUNDLEUNDEF, // Undefined
557 };
558
559 enum
560 {
561 GROUPEFREE, // Not in use
562 GROUPEOPEN, // Active bundle
563 GROUPEUNDEF // Undefined
564 };
565
566 enum
567 {
568 NULLCLASS = 0, //End Point Discriminator classes
569 LOCALADDR,
570 IPADDR,
571 IEEEMACADDR,
572 PPPMAGIC,
573 PSNDN,
574 };
575
576 enum
577 {
578 RADIUSNULL, // Not in use
579 RADIUSCHAP, // sending CHAP down PPP
580 RADIUSAUTH, // sending auth to RADIUS server
581 RADIUSSTART, // sending start accounting to RADIUS server
582 RADIUSSTOP, // sending stop accounting to RADIUS server
583 RADIUSINTERIM, // sending interim accounting to RADIUS server
584 RADIUSWAIT, // waiting timeout before available, in case delayed replies
585 RADIUSJUSTAUTH, // sending auth to RADIUS server, just authentication, no ip assigning
586 };
587
588 struct Tstats
589 {
590 time_t start_time;
591 time_t last_reset;
592
593 uint32_t tun_rx_packets;
594 uint32_t tun_tx_packets;
595 uint32_t tun_rx_bytes;
596 uint32_t tun_tx_bytes;
597 uint32_t tun_rx_errors;
598 uint32_t tun_tx_errors;
599 uint32_t tun_rx_dropped;
600
601 uint32_t tunnel_rx_packets;
602 uint32_t tunnel_tx_packets;
603 uint32_t tunnel_rx_bytes;
604 uint32_t tunnel_tx_bytes;
605 uint32_t tunnel_rx_errors;
606 uint32_t tunnel_tx_errors;
607
608 uint32_t tunnel_retries;
609 uint32_t radius_retries;
610
611 uint32_t arp_sent;
612
613 uint32_t packets_snooped;
614
615 uint32_t tunnel_created;
616 uint32_t session_created;
617 uint32_t tunnel_timeout;
618 uint32_t session_timeout;
619 uint32_t radius_timeout;
620 uint32_t radius_overflow;
621 uint32_t tunnel_overflow;
622 uint32_t session_overflow;
623
624 uint32_t ip_allocated;
625 uint32_t ip_freed;
626
627 uint32_t c_forwarded;
628 uint32_t recv_forward;
629
630 uint32_t select_called;
631 uint32_t multi_read_used;
632 uint32_t multi_read_exceeded;
633
634 #ifdef STATISTICS
635 uint32_t call_processtun;
636 uint32_t call_processipout;
637 uint32_t call_processipv6out;
638 uint32_t call_processudp;
639 uint32_t call_sessionbyip;
640 uint32_t call_sessionbyipv6;
641 uint32_t call_sessionbyuser;
642 uint32_t call_sendarp;
643 uint32_t call_sendipcp;
644 uint32_t call_sendipv6cp;
645 uint32_t call_processipv6cp;
646 uint32_t call_tunnelsend;
647 uint32_t call_sessionkill;
648 uint32_t call_sessionshutdown;
649 uint32_t call_tunnelkill;
650 uint32_t call_tunnelshutdown;
651 uint32_t call_assign_ip_address;
652 uint32_t call_free_ip_address;
653 uint32_t call_dump_acct_info;
654 uint32_t call_sessionsetup;
655 uint32_t call_processpap;
656 uint32_t call_processchap;
657 uint32_t call_processlcp;
658 uint32_t call_processipcp;
659 uint32_t call_processipin;
660 uint32_t call_processipv6in;
661 uint32_t call_processccp;
662 uint32_t call_sendchap;
663 uint32_t call_processrad;
664 uint32_t call_radiussend;
665 uint32_t call_radiusretry;
666 uint32_t call_random_data;
667 uint32_t call_dhcpv6_process;
668 #endif
669 };
670
671 #ifdef STATISTICS
672
673 #ifdef STAT_CALLS
674 #define CSTAT(x) STAT(call_ ## x)
675 #else
676 #define CSTAT(x)
677 #endif
678
679 #define STAT(x) (_statistics->x++)
680 #define INC_STAT(x,y) (_statistics->x += (y))
681 #define GET_STAT(x) (_statistics->x)
682 #define SET_STAT(x, y) (_statistics->x = (y))
683 #else
684 #define CSTAT(x)
685 #define STAT(x)
686 #define INC_STAT(x,y)
687 #define GET_STAT(x) 0
688 #define SET_STAT(x, y)
689 #endif
690
691 #ifndef IFNAMSIZ
692 # define IFNAMSIZ 16
693 #endif
694
695 typedef struct
696 {
697 int debug; // debugging level
698 time_t start_time; // time when l2tpns was started
699 char bandwidth[256]; // current bandwidth
700 char pid_file[256]; // file to write PID to on startup
701 int wrote_pid;
702 clockt current_time; // 1/10ths of a second since the process started.
703 // means that we can only run a given process
704 // for 13 years without re-starting!
705
706 char config_file[128];
707 int reload_config; // flag to re-read config (set by cli)
708 int multi_read_count; // amount of packets to read per fd in processing loop
709
710 char tundevicename[IFNAMSIZ]; // tun device name
711 char log_filename[128];
712
713 char l2tp_secret[64]; // L2TP shared secret
714 int l2tp_mtu; // MTU of interface used for L2TP
715
716 char random_device[256]; // random device path, defaults to RANDOMDEVICE
717
718 int ppp_restart_time; // timeout for PPP restart
719 int ppp_max_configure; // max lcp configure requests to send
720 int ppp_max_failure; // max lcp configure naks to send
721
722 char radiussecret[64];
723 int radius_accounting;
724 int radius_interim;
725 in_addr_t radiusserver[MAXRADSERVER]; // radius servers
726 uint16_t radiusport[MAXRADSERVER]; // radius base ports
727 uint8_t numradiusservers; // radius server count
728
729 uint16_t radius_dae_port; // port for radius DAE
730 uint16_t radius_bind_min; // port range for udp sockets used to send/recv radius packets
731 uint16_t radius_bind_max;
732
733 char radius_authtypes_s[32]; // list of valid authentication types (chap, pap) in order of preference
734 int radius_authtypes;
735 int radius_authprefer;
736
737 int allow_duplicate_users; // allow multiple logins with the same username
738 int kill_timedout_sessions; // kill authenticated sessions with "session_timeout == 0"
739
740 in_addr_t default_dns1, default_dns2;
741
742 unsigned long rl_rate; // default throttle rate
743 int num_tbfs; // number of throttle buckets
744
745 char accounting_dir[128];
746 int account_all_origin; // Accouting all origin (LAC data + Remote LNS Data + PPPOE data)
747 in_addr_t bind_address;
748 in_addr_t peer_address;
749 int send_garp; // Set to true to garp for vip address on startup
750
751 int dump_speed;
752 char plugins[64][MAXPLUGINS];
753 char old_plugins[64][MAXPLUGINS];
754
755 int next_tbf; // Next HTB id available to use
756 int scheduler_fifo; // If the system has multiple CPUs, use FIFO scheduling
757 // policy for this process.
758 int lock_pages; // Lock pages into memory.
759 int icmp_rate; // Max number of ICMP unreachable per second to send
760 int max_packets; // DoS prevention: per session limit of packets/0.1s
761 char epdis_addr[20]; // MP Endpoint Discriminator address
762
763 in_addr_t cluster_address; // Multicast address of cluster.
764 // Send to this address to have everyone hear.
765 char cluster_interface[64]; // Which interface to listen for multicast on.
766 int cluster_iam_master; // Are we the cluster master???
767 int cluster_iam_uptodate; // Set if we've got a full set of state from the master.
768 in_addr_t cluster_master_address; // The network address of the cluster master.
769 // Zero if i am the cluster master.
770 int cluster_seq_number; // Sequence number of the next heartbeat we'll send out
771 // (or the seq number we're next expecting if we're a slave).
772 int cluster_undefined_sessions; // How many sessions we're yet to receive from the master.
773 int cluster_undefined_bundles; // How many bundles we're yet to receive from the master.
774 int cluster_undefined_tunnels; // How many tunnels we're yet to receive from the master.
775 int cluster_undefined_groupes; // How many groupes we're yet to receive from the master.
776 int cluster_highest_sessionid;
777 int cluster_highest_bundleid;
778 int cluster_highest_groupeid;
779 int cluster_highest_tunnelid;
780 clockt cluster_last_hb; // Last time we saw a heartbeat from the master.
781 int cluster_last_hb_ver; // Heartbeat version last seen from master
782 int cluster_num_changes; // Number of changes queued.
783
784 int cluster_mcast_ttl; // TTL for multicast packets
785 int cluster_hb_interval; // How often to send a heartbeat.
786 int cluster_hb_timeout; // How many missed heartbeats trigger an election.
787 uint64_t cluster_table_version; // # state changes processed by cluster
788
789 struct in6_addr ipv6_prefix; // Our IPv6 network pool.
790
791
792 int cluster_master_min_adv; // Master advertises routes while the number of up to date
793 // slaves is less than this value.
794 in_addr_t cli_bind_address; // bind address for CLI
795 char hostname[MAXHOSTNAME]; // hostname (overridden by -h on command line)
796 // Guest change
797 char guest_user[MAXUSER]; // Guest account username
798
799 #ifdef BGP
800 #define BGP_NUM_PEERS 2
801 uint16_t as_number;
802 struct {
803 char name[64];
804 uint16_t as;
805 int keepalive;
806 int hold;
807 struct in_addr update_source;
808 } neighbour[BGP_NUM_PEERS];
809 in_addr_t nexthop_address;
810 struct in6_addr nexthop6_address;
811 #endif
812
813 int echo_timeout; // Time between last packet sent and LCP ECHO generation
814 int idle_echo_timeout; // Time between last packet seen and
815 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
816 in_addr_t iftun_address;
817 int disable_lac_func;
818 int auth_tunnel_change_addr_src;
819 int highest_rlnsid;
820 uint16_t bind_portremotelns;
821 in_addr_t bind_address_remotelns;
822 char pppoe_if_to_bind[IFNAMSIZ]; // Name pppoe interface to bind
823 char pppoe_service_name[64]; // pppoe service name
824 char pppoe_ac_name[64];
825 uint8_t pppoe_hwaddr[ETH_ALEN]; // MAC addr of interface pppoe to bind
826 int pppoe_only_equal_svc_name; // Accept only PADI with service-name equal to server
827 int disable_sending_hello; // Disable l2tp sending HELLO message for Apple compatibility.
828 int disable_no_spoof; // Disable no spoof (permit load balancing client --> internet)
829 int nbudpfd; // number UDP file handle
830 int nbmultiaddress; // number multi address to bind
831 int indexlacudpfd; // Index UDP LAC file handle (in udpfd[])
832 int nbmultihostname; // number hostname, normally the same number as the nbudpfd
833 int grp_txrate_average_time; // caculation txrate average time (default 10s)
834 int no_throttle_local_IP; // no throttle traffic from session to session
835 in_addr_t bind_n_address[MAX_BINDADDR];
836 in_addr_t iftun_n_address[MAX_BINDADDR];
837 char bind_multi_address[256];
838 char multi_hostname[512];
839 char multi_n_hostname[MAX_NBHOSTNAME][MAXHOSTNAME]; // list hostname
840 struct in6_addr default_ipv6_dns1;
841 struct in6_addr default_ipv6_dns2;
842 uint32_t dhcp6_preferred_lifetime; // preferred lifetime (see rfc3315)
843 uint32_t dhcp6_valid_lifetime; // valid lifetime (see rfc3315)
844 uint32_t dhcp6_server_duid; // DUID of dhcpv6 server (see rfc3315)
845 char default_ipv6_domain_list[255];
846 } configt;
847
848 enum config_typet { INT, STRING, UNSIGNED_LONG, SHORT, BOOL, IPv4, IPv6 };
849 typedef struct
850 {
851 char *key;
852 int offset;
853 int size;
854 enum config_typet type;
855 } config_descriptt;
856
857 typedef struct
858 {
859 uint8_t op; // operation
860 #define FILTER_PORT_OP_NONE 0 // all ports match
861 #define FILTER_PORT_OP_EQ 1
862 #define FILTER_PORT_OP_NEQ 2
863 #define FILTER_PORT_OP_GT 3
864 #define FILTER_PORT_OP_LT 4
865 #define FILTER_PORT_OP_RANGE 5
866 uint16_t port; // port (host byte order)
867 uint16_t port2; // range
868 } ip_filter_portt;
869
870 typedef struct
871 {
872 int action; // permit/deny
873 #define FILTER_ACTION_DENY 1
874 #define FILTER_ACTION_PERMIT 2
875 uint8_t proto; // protocol: IPPROTO_* (netinet/in.h)
876 in_addr_t src_ip; // source ip (network byte order)
877 in_addr_t src_wild;
878 ip_filter_portt src_ports;
879 in_addr_t dst_ip; // dest ip
880 in_addr_t dst_wild;
881 ip_filter_portt dst_ports;
882 uint8_t frag; // apply to non-initial fragments
883 uint8_t tcp_flag_op; // match type: any, all, established
884 #define FILTER_FLAG_OP_ANY 1
885 #define FILTER_FLAG_OP_ALL 2
886 #define FILTER_FLAG_OP_EST 3
887 uint8_t tcp_sflags; // flags set
888 uint8_t tcp_cflags; // flags clear
889 uint32_t counter; // match count
890 } ip_filter_rulet;
891
892 #define TCP_FLAG_FIN 0x01
893 #define TCP_FLAG_SYN 0x02
894 #define TCP_FLAG_RST 0x04
895 #define TCP_FLAG_PSH 0x08
896 #define TCP_FLAG_ACK 0x10
897 #define TCP_FLAG_URG 0x20
898
899 #define MAXFILTER 32
900 #define MAXFILTER_RULES 32
901 typedef struct
902 {
903 char name[32]; // ACL name
904 int extended; // type: 0 = standard, 1 = extended
905 ip_filter_rulet rules[MAXFILTER_RULES];
906 int used; // session ref count
907 } ip_filtert;
908
909 // CDN result/error codes
910 #define CDN_NONE 0, 0
911 #define CDN_TRY_ANOTHER 2, 7
912 #define CDN_ADMIN_DISC 3, 0
913 #define CDN_UNAVAILABLE 4, 0
914
915 // RADIUS Acct-Terminate-Cause values
916 #define TERM_USER_REQUEST 1
917 #define TERM_LOST_CARRIER 2
918 #define TERM_LOST_SERVICE 3
919 #define TERM_IDLE_TIMEOUT 4
920 #define TERM_SESSION_TIMEOUT 5
921 #define TERM_ADMIN_RESET 6
922 #define TERM_ADMIN_REBOOT 7
923 #define TERM_PORT_ERROR 8
924 #define TERM_NAS_ERROR 9
925 #define TERM_NAS_REQUEST 10
926 #define TERM_NAS_REBOOT 11
927 #define TERM_PORT_UNNEEDED 12
928 #define TERM_PORT_PREEMPTED 13
929 #define TERM_PORT_SUSPENDED 14
930 #define TERM_SERVICE_UNAVAILABLE 15
931 #define TERM_CALLBACK 16
932 #define TERM_USER_ERROR 17
933 #define TERM_HOST_REQUEST 18
934 #define TERM_SUPPLICANT_RESTART 19
935 #define TERM_REAUTHENTICATION_FAILURE 20
936 #define TERM_PORT_REINIT 21
937 #define TERM_PORT_DISABLED 22
938
939 // on slaves, alow BGP to withdraw cleanly before exiting
940 #define QUIT_DELAY 5
941
942 // quit actions (master)
943 #define QUIT_FAILOVER 1 // SIGTERM: exit when all control messages have been acked (for cluster failover)
944 #define QUIT_SHUTDOWN 2 // SIGQUIT: shutdown sessions/tunnels, reject new connections
945
946 // arp.c
947 void sendarp(int ifr_idx, const unsigned char* mac, in_addr_t ip);
948
949
950 // ppp.c
951 void processpap(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
952 void processchap(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
953 void lcp_open(sessionidt s, tunnelidt t);
954 void lcp_restart(sessionidt s);
955 void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
956 void processipcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
957 void processipv6cp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
958 void processipin(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
959 void processmpin(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
960 void processmpframe(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l, uint8_t extra);
961 void processipv6in(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
962 void processccp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
963 void sendchap(sessionidt s, tunnelidt t);
964 uint8_t *makeppp(uint8_t *b, int size, uint8_t *p, int l, sessionidt s, tunnelidt t, uint16_t mtype, uint8_t prio, bundleidt bid, uint8_t mp_bits);
965 uint8_t *opt_makeppp(uint8_t *p, int l, sessionidt s, tunnelidt t, uint16_t mtype, uint8_t prio, bundleidt bid, uint8_t mp_bits);
966 void sendlcp(sessionidt s, tunnelidt t);
967 void send_ipin(sessionidt s, uint8_t *buf, int len);
968 void sendccp(sessionidt s, tunnelidt t);
969 void protoreject(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l, uint16_t proto);
970 int join_bundle(sessionidt s);
971
972
973 // radius.c
974 void initrad(void);
975 void radiussend(uint16_t r, uint8_t state);
976 void processrad(uint8_t *buf, int len, char socket_index);
977 void radiusretry(uint16_t r);
978 uint16_t radiusnew(sessionidt s);
979 void radiusclear(uint16_t r, sessionidt s);
980 void processdae(uint8_t *buf, int len, struct sockaddr_in *addr, int alen, struct in_addr *local);
981 int rad_tunnel_pwdecode(uint8_t *pl2tpsecret, size_t *pl2tpsecretlen, const char *radiussecret, const uint8_t * auth);
982
983 // l2tpns.c
984 clockt backoff(uint8_t try);
985 void send_ipv6_ra(sessionidt s, tunnelidt t, struct in6_addr *ip);
986 void route6set(sessionidt s, struct in6_addr ip, int prefixlen, int add);
987 sessionidt sessionbyip(in_addr_t ip);
988 sessionidt sessionbyipv6(struct in6_addr ip);
989 sessionidt sessionbyuser(char *username);
990 void increment_counter(uint32_t *counter, uint32_t *wrap, uint32_t delta);
991 void random_data(uint8_t *buf, int len);
992 void sessionkill(sessionidt s, char *reason);
993 void sessionshutdown(sessionidt s, char const *reason, int cdn_result, int cdn_error, int term_cause);
994 void filter_session(sessionidt s, int filter_in, int filter_out);
995 void send_garp(in_addr_t ip);
996 void tunnelsend(uint8_t *buf, uint16_t l, tunnelidt t);
997 int tun_write(uint8_t *data, int size);
998 void adjust_tcp_mss(sessionidt s, tunnelidt t, uint8_t *buf, int len, uint8_t *tcp);
999 void sendipcp(sessionidt s, tunnelidt t);
1000 void sendipv6cp(sessionidt s, tunnelidt t);
1001 void processudp(uint8_t *buf, int len, struct sockaddr_in *addr, uint16_t indexudpfd);
1002 void processipout(uint8_t *buf, int len);
1003 void snoop_send_packet(uint8_t *packet, uint16_t size, in_addr_t destination, uint16_t port);
1004 int find_filter(char const *name, size_t len);
1005 int ip_filter(uint8_t *buf, int len, uint8_t filter);
1006 int cmd_show_ipcache(struct cli_def *cli, const char *command, char **argv, int argc);
1007 int cmd_show_hist_idle(struct cli_def *cli, const char *command, char **argv, int argc);
1008 int cmd_show_hist_open(struct cli_def *cli, const char *command, char **argv, int argc);
1009 void netlink_addattr(struct nlmsghdr *nh, int type, const void *data, int alen);
1010 ssize_t netlink_send(struct nlmsghdr *nh);
1011 void cache_ipmap(in_addr_t ip, sessionidt s);
1012 tunnelidt lac_new_tunnel();
1013 void lac_tunnelclear(tunnelidt t);
1014 void lac_send_SCCRQ(tunnelidt t, uint8_t * auth, unsigned int auth_len);
1015 void lac_send_ICRQ(tunnelidt t, sessionidt s);
1016 void lac_tunnelshutdown(tunnelidt t, char *reason, int result, int error, char *msg);
1017
1018 // grpsess.c
1019 sessionidt grp_getnextsession(groupidt g, in_addr_t ip, in_addr_t ip_src);
1020 void grp_initdata(void);
1021 void grp_processvendorspecific(sessionidt s, uint8_t *pvs);
1022 groupidt grp_groupbysession(sessionidt s);
1023 groupidt grp_groupbyip(in_addr_t ip);
1024 void grp_setgrouproute(groupidt g, int add);
1025 void grp_time_changed(void);
1026 void grp_removesession(groupidt g, sessionidt s);
1027 int grp_cluster_load_groupe(groupidt g, groupsesst *new);
1028
1029 #undef LOG
1030 #undef LOG_HEX
1031 #define LOG(D, s, t, f, ...) ({ if (D <= config->debug) _log(D, s, t, f, ## __VA_ARGS__); })
1032 #define LOG_HEX(D, t, d, s) ({ if (D <= config->debug) _log_hex(D, t, d, s); })
1033
1034 void _log(int level, sessionidt s, tunnelidt t, const char *format, ...) __attribute__((format (printf, 4, 5)));
1035 void _log_hex(int level, const char *title, const uint8_t *data, int maxsize);
1036
1037
1038 int sessionsetup(sessionidt s, tunnelidt t);
1039 int run_plugins(int plugin_type, void *data);
1040 void rebuild_address_pool(void);
1041 void throttle_session(sessionidt s, int rate_in, int rate_out);
1042 int load_session(sessionidt, sessiont *);
1043 void become_master(void); // We're the master; kick off any required master initializations.
1044
1045
1046 // cli.c
1047 void init_cli();
1048 void cli_init_complete(char *hostname);
1049 void cli_do_file(FILE *fh);
1050 void cli_do(int sockfd);
1051 int cli_arg_help(struct cli_def *cli, int cr_ok, char *entry, ...);
1052
1053
1054 // icmp.c
1055 void host_unreachable(in_addr_t destination, uint16_t id, in_addr_t source, uint8_t *packet, int packet_len);
1056
1057
1058 extern tunnelt *tunnel;
1059 extern bundlet *bundle;
1060 extern sessiont *session;
1061 extern sessionlocalt *sess_local;
1062 extern ippoolt *ip_address_pool;
1063 extern groupsesst *grpsession;
1064 extern groupidt gnextgrpid;
1065 #define sessionfree (session[0].next)
1066
1067
1068 extern configt *config;
1069 extern time_t basetime; // Time when this process started.
1070 extern time_t time_now; // Seconds since EPOCH.
1071 extern char main_quit;
1072 extern uint32_t last_id;
1073 extern struct Tstats *_statistics;
1074 extern in_addr_t my_address;
1075 extern int clifd;
1076 extern int epollfd;
1077 extern int tunidx; // ifr_ifindex of tun device
1078 extern union iphash ip_hash[256];
1079
1080 struct event_data {
1081 enum {
1082 FD_TYPE_CLI,
1083 FD_TYPE_CLUSTER,
1084 FD_TYPE_TUN,
1085 FD_TYPE_UDP,
1086 FD_TYPE_CONTROL,
1087 FD_TYPE_DAE,
1088 FD_TYPE_RADIUS,
1089 FD_TYPE_BGP,
1090 FD_TYPE_NETLINK,
1091 FD_TYPE_PPPOEDISC,
1092 FD_TYPE_PPPOESESS
1093 } type;
1094 int index; // for RADIUS, BGP, UDP
1095 };
1096
1097 #define TIME (config->current_time)
1098
1099 extern uint16_t MRU;
1100 extern uint16_t MSS;
1101
1102 // macros for handling help in cli commands
1103 #define CLI_HELP_REQUESTED (argc > 0 && argv[argc-1][strlen(argv[argc-1])-1] == '?')
1104 #define CLI_HELP_NO_ARGS (argc > 1 || argv[0][1]) ? CLI_OK : cli_arg_help(cli, 1, NULL)
1105
1106 #endif /* __L2TPNS_H__ */