1ce46a358f50711f54750150100e625db8b50cfe
[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"
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 char reserved[4]; // Space to expand structure without changing HB_VERSION
341 }
342 sessiont;
343
344 typedef struct
345 {
346 uint32_t tx_rate;
347 uint32_t prev_coutgrp;
348 sessionidt sid;
349 uint8_t weight;
350 }
351 groupsesslistt;
352
353 typedef struct
354 {
355 int state; // current state (groupestate enum)
356 uint32_t time_changed;
357 groupidt prev;
358 sessionidt smax;
359 sessionidt smin;
360 groupsesslistt sesslist[MAXSESSINGRP];
361 routet route[MAXROUTEINGRP]; // static routes
362 uint8_t nbroutesgrp;
363 uint8_t nbsession;
364 }
365 groupsesst;
366
367 union iphash
368 {
369 sessionidt sess;
370 union iphash *idx;
371 }; // Mapping from IP address to session structures.
372
373 typedef struct
374 {
375 int state; // current state (bundlestate enum)
376 uint32_t seq_num_t; // Sequence Number (transmission)
377 uint32_t timeout; // Session-Timeout for bundle
378 uint32_t max_seq; // Max value of sequence number field
379 uint8_t num_of_links; // Number of links joint to this bundle
380 uint32_t online_time; // The time this bundle is online
381 clockt last_check; // Last time the timeout is checked
382 uint32_t mrru; // Multilink Max-Receive-Reconstructed-Unit
383 uint8_t mssf; // Multilink Short Sequence Number Header Format
384 epdist epdis; // Multilink Endpoint Discriminator
385 char user[MAXUSER]; // Needed for matching member links
386 sessionidt current_ses; // Current session to use for sending (used in RR load-balancing)
387 sessionidt members[MAXBUNDLESES]; // Array for member links sessions
388 }
389 bundlet;
390
391 typedef struct
392 {
393 fragmentt fragment[MAXFRAGNUM];
394 uint8_t reassembled_frame[MAXETHER]; // The reassembled frame
395 uint16_t re_frame_len; // The reassembled frame length
396 uint16_t re_frame_begin_index, re_frame_end_index; // reassembled frame begin index, end index respectively
397 uint16_t start_index, end_index; // start and end sequence numbers available on the fragments array respectively
398 uint32_t M; // Minumum frame sequence number received over all bundle members
399 uint32_t start_seq; // Last received frame sequence number (bearing B bit)
400 }
401 fragmentationt;
402
403 #define AUTHPAP 1 // allow PAP
404 #define AUTHCHAP 2 // allow CHAP
405
406 typedef struct
407 {
408 // packet counters
409 uint32_t pin;
410 uint32_t pout;
411
412 // byte counters
413 uint32_t cin;
414 uint32_t cout;
415
416 // PPP restart timer/counters
417 struct {
418 time_t restart;
419 int conf_sent;
420 int nak_sent;
421 } lcp, ipcp, ipv6cp, ccp;
422
423 // identifier for Protocol-Reject, Code-Reject
424 uint8_t lcp_ident;
425
426 // authentication to use
427 int lcp_authtype;
428
429 // our MRU
430 uint16_t ppp_mru;
431
432 // our MRRU
433 uint16_t mp_mrru;
434
435 // our mssf
436 uint16_t mp_mssf;
437
438 // our Endpoint Discriminator
439 in_addr_t mp_epdis;
440
441 // DoS prevention
442 clockt last_packet_out;
443 uint32_t packets_out;
444 uint32_t packets_dropped;
445
446 // RADIUS session in use
447 uint16_t radius;
448
449 // interim RADIUS
450 time_t last_interim;
451
452 // last LCP Echo
453 time_t last_echo;
454
455 // Last Multilink frame sequence number received
456 uint32_t last_seq;
457
458 // jitter average of the session
459 uint32_t jitteravg;
460 // time in milliseconds of the last fragment.
461 uint64_t prev_time;
462 } sessionlocalt;
463
464 // session flags
465 #define SESSION_PFC (1 << 0) // use Protocol-Field-Compression
466 #define SESSION_ACFC (1 << 1) // use Address-and-Control-Field-Compression
467 #define SESSION_STARTED (1 << 2) // RADIUS Start record sent
468
469 // 328 bytes per tunnel
470 typedef struct
471 {
472 tunnelidt far; // far end tunnel ID
473 in_addr_t ip; // Ip for far end
474 uint16_t port; // port for far end
475 uint16_t window; // Rx window
476 uint16_t nr; // next receive
477 uint16_t ns; // next send
478 int state; // current state (tunnelstate enum)
479 clockt last; // when last control message sent (used for resend timeout)
480 clockt retry; // when to try resending pending control
481 clockt die; // being closed, when to finally free
482 clockt lastrec; // when the last control message was received
483 char hostname[128]; // tunnel hostname
484 char vendor[128]; // LAC vendor
485 uint8_t try; // number of retrys on a control message
486 uint16_t controlc; // outstaind messages in queue
487 controlt *controls; // oldest message
488 controlt *controle; // newest message
489 uint16_t isremotelns; // != 0 if the tunnel is to remote LNS (== index on the conf remote lns)
490 uint16_t indexudp; // Index UDP file handle (in udpfd[])
491 char reserved[12]; // Space to expand structure without changing HB_VERSION
492 }
493 tunnelt;
494
495 // 164 bytes per radius session
496 typedef struct // outstanding RADIUS requests
497 {
498 sessionidt session; // which session this applies to
499 hasht auth; // request authenticator
500 clockt retry; // when to try next
501 char pass[129]; // password
502 uint8_t id; // ID for PPP response
503 uint8_t try; // which try we are on
504 uint8_t state; // state of radius requests
505 uint8_t chap; // set if CHAP used (is CHAP identifier)
506 uint8_t term_cause; // Stop record: Acct-Terminate-Cause
507 char const *term_msg; // terminate reason
508 }
509 radiust;
510
511 typedef struct
512 {
513 in_addr_t address; // Host byte order..
514 char assigned; // 1 if assigned, 0 if free
515 sessionidt session;
516 clockt last; // last used
517 char user[129]; // user (try to have ip addresses persistent)
518 }
519 ippoolt;
520
521 #ifdef RINGBUFFER
522 struct Tringbuffer
523 {
524 struct {
525 char level;
526 sessionidt session;
527 tunnelidt tunnel;
528 char message[MAX_LOG_LENGTH];
529 } buffer[RINGBUFFER_SIZE];
530 int head;
531 int tail;
532 };
533 #endif
534
535 /*
536 * Possible tunnel states
537 * TUNNELFREE -> TUNNELOPEN -> TUNNELDIE -> TUNNELFREE
538 */
539 enum
540 {
541 TUNNELFREE, // Not in use
542 TUNNELOPEN, // Active tunnel
543 TUNNELDIE, // Currently closing
544 TUNNELOPENING, // Busy opening
545 TUNNELUNDEF, // Undefined
546 };
547
548 enum
549 {
550 BUNDLEFREE, // Not in use
551 BUNDLEOPEN, // Active bundle
552 BUNDLEUNDEF, // Undefined
553 };
554
555 enum
556 {
557 GROUPEFREE, // Not in use
558 GROUPEOPEN, // Active bundle
559 GROUPEUNDEF // Undefined
560 };
561
562 enum
563 {
564 NULLCLASS = 0, //End Point Discriminator classes
565 LOCALADDR,
566 IPADDR,
567 IEEEMACADDR,
568 PPPMAGIC,
569 PSNDN,
570 };
571
572 enum
573 {
574 RADIUSNULL, // Not in use
575 RADIUSCHAP, // sending CHAP down PPP
576 RADIUSAUTH, // sending auth to RADIUS server
577 RADIUSSTART, // sending start accounting to RADIUS server
578 RADIUSSTOP, // sending stop accounting to RADIUS server
579 RADIUSINTERIM, // sending interim accounting to RADIUS server
580 RADIUSWAIT, // waiting timeout before available, in case delayed replies
581 RADIUSJUSTAUTH, // sending auth to RADIUS server, just authentication, no ip assigning
582 };
583
584 struct Tstats
585 {
586 time_t start_time;
587 time_t last_reset;
588
589 uint32_t tun_rx_packets;
590 uint32_t tun_tx_packets;
591 uint32_t tun_rx_bytes;
592 uint32_t tun_tx_bytes;
593 uint32_t tun_rx_errors;
594 uint32_t tun_tx_errors;
595 uint32_t tun_rx_dropped;
596
597 uint32_t tunnel_rx_packets;
598 uint32_t tunnel_tx_packets;
599 uint32_t tunnel_rx_bytes;
600 uint32_t tunnel_tx_bytes;
601 uint32_t tunnel_rx_errors;
602 uint32_t tunnel_tx_errors;
603
604 uint32_t tunnel_retries;
605 uint32_t radius_retries;
606
607 uint32_t arp_sent;
608
609 uint32_t packets_snooped;
610
611 uint32_t tunnel_created;
612 uint32_t session_created;
613 uint32_t tunnel_timeout;
614 uint32_t session_timeout;
615 uint32_t radius_timeout;
616 uint32_t radius_overflow;
617 uint32_t tunnel_overflow;
618 uint32_t session_overflow;
619
620 uint32_t ip_allocated;
621 uint32_t ip_freed;
622
623 uint32_t c_forwarded;
624 uint32_t recv_forward;
625
626 uint32_t select_called;
627 uint32_t multi_read_used;
628 uint32_t multi_read_exceeded;
629
630 #ifdef STATISTICS
631 uint32_t call_processtun;
632 uint32_t call_processipout;
633 uint32_t call_processipv6out;
634 uint32_t call_processudp;
635 uint32_t call_sessionbyip;
636 uint32_t call_sessionbyipv6;
637 uint32_t call_sessionbyuser;
638 uint32_t call_sendarp;
639 uint32_t call_sendipcp;
640 uint32_t call_sendipv6cp;
641 uint32_t call_processipv6cp;
642 uint32_t call_tunnelsend;
643 uint32_t call_sessionkill;
644 uint32_t call_sessionshutdown;
645 uint32_t call_tunnelkill;
646 uint32_t call_tunnelshutdown;
647 uint32_t call_assign_ip_address;
648 uint32_t call_free_ip_address;
649 uint32_t call_dump_acct_info;
650 uint32_t call_sessionsetup;
651 uint32_t call_processpap;
652 uint32_t call_processchap;
653 uint32_t call_processlcp;
654 uint32_t call_processipcp;
655 uint32_t call_processipin;
656 uint32_t call_processipv6in;
657 uint32_t call_processccp;
658 uint32_t call_sendchap;
659 uint32_t call_processrad;
660 uint32_t call_radiussend;
661 uint32_t call_radiusretry;
662 uint32_t call_random_data;
663 #endif
664 };
665
666 #ifdef STATISTICS
667
668 #ifdef STAT_CALLS
669 #define CSTAT(x) STAT(call_ ## x)
670 #else
671 #define CSTAT(x)
672 #endif
673
674 #define STAT(x) (_statistics->x++)
675 #define INC_STAT(x,y) (_statistics->x += (y))
676 #define GET_STAT(x) (_statistics->x)
677 #define SET_STAT(x, y) (_statistics->x = (y))
678 #else
679 #define CSTAT(x)
680 #define STAT(x)
681 #define INC_STAT(x,y)
682 #define GET_STAT(x) 0
683 #define SET_STAT(x, y)
684 #endif
685
686 #ifndef IFNAMSIZ
687 # define IFNAMSIZ 16
688 #endif
689
690 typedef struct
691 {
692 int debug; // debugging level
693 time_t start_time; // time when l2tpns was started
694 char bandwidth[256]; // current bandwidth
695 char pid_file[256]; // file to write PID to on startup
696 int wrote_pid;
697 clockt current_time; // 1/10ths of a second since the process started.
698 // means that we can only run a given process
699 // for 13 years without re-starting!
700
701 char config_file[128];
702 int reload_config; // flag to re-read config (set by cli)
703 int multi_read_count; // amount of packets to read per fd in processing loop
704
705 char tundevicename[IFNAMSIZ]; // tun device name
706 char log_filename[128];
707
708 char l2tp_secret[64]; // L2TP shared secret
709 int l2tp_mtu; // MTU of interface used for L2TP
710
711 char random_device[256]; // random device path, defaults to RANDOMDEVICE
712
713 int ppp_restart_time; // timeout for PPP restart
714 int ppp_max_configure; // max lcp configure requests to send
715 int ppp_max_failure; // max lcp configure naks to send
716
717 char radiussecret[64];
718 int radius_accounting;
719 int radius_interim;
720 in_addr_t radiusserver[MAXRADSERVER]; // radius servers
721 uint16_t radiusport[MAXRADSERVER]; // radius base ports
722 uint8_t numradiusservers; // radius server count
723
724 uint16_t radius_dae_port; // port for radius DAE
725 uint16_t radius_bind_min; // port range for udp sockets used to send/recv radius packets
726 uint16_t radius_bind_max;
727
728 char radius_authtypes_s[32]; // list of valid authentication types (chap, pap) in order of preference
729 int radius_authtypes;
730 int radius_authprefer;
731
732 int allow_duplicate_users; // allow multiple logins with the same username
733 int kill_timedout_sessions; // kill authenticated sessions with "session_timeout == 0"
734
735 in_addr_t default_dns1, default_dns2;
736
737 unsigned long rl_rate; // default throttle rate
738 int num_tbfs; // number of throttle buckets
739
740 char accounting_dir[128];
741 int account_all_origin; // Accouting all origin (LAC data + Remote LNS Data + PPPOE data)
742 in_addr_t bind_address;
743 in_addr_t peer_address;
744 int send_garp; // Set to true to garp for vip address on startup
745
746 int dump_speed;
747 char plugins[64][MAXPLUGINS];
748 char old_plugins[64][MAXPLUGINS];
749
750 int next_tbf; // Next HTB id available to use
751 int scheduler_fifo; // If the system has multiple CPUs, use FIFO scheduling
752 // policy for this process.
753 int lock_pages; // Lock pages into memory.
754 int icmp_rate; // Max number of ICMP unreachable per second to send
755 int max_packets; // DoS prevention: per session limit of packets/0.1s
756 char epdis_addr[20]; // MP Endpoint Discriminator address
757
758 in_addr_t cluster_address; // Multicast address of cluster.
759 // Send to this address to have everyone hear.
760 char cluster_interface[64]; // Which interface to listen for multicast on.
761 int cluster_iam_master; // Are we the cluster master???
762 int cluster_iam_uptodate; // Set if we've got a full set of state from the master.
763 in_addr_t cluster_master_address; // The network address of the cluster master.
764 // Zero if i am the cluster master.
765 int cluster_seq_number; // Sequence number of the next heartbeat we'll send out
766 // (or the seq number we're next expecting if we're a slave).
767 int cluster_undefined_sessions; // How many sessions we're yet to receive from the master.
768 int cluster_undefined_bundles; // How many bundles we're yet to receive from the master.
769 int cluster_undefined_tunnels; // How many tunnels we're yet to receive from the master.
770 int cluster_undefined_groupes; // How many groupes we're yet to receive from the master.
771 int cluster_highest_sessionid;
772 int cluster_highest_bundleid;
773 int cluster_highest_groupeid;
774 int cluster_highest_tunnelid;
775 clockt cluster_last_hb; // Last time we saw a heartbeat from the master.
776 int cluster_last_hb_ver; // Heartbeat version last seen from master
777 int cluster_num_changes; // Number of changes queued.
778
779 int cluster_mcast_ttl; // TTL for multicast packets
780 int cluster_hb_interval; // How often to send a heartbeat.
781 int cluster_hb_timeout; // How many missed heartbeats trigger an election.
782 uint64_t cluster_table_version; // # state changes processed by cluster
783
784 struct in6_addr ipv6_prefix; // Our IPv6 network pool.
785
786
787 int cluster_master_min_adv; // Master advertises routes while the number of up to date
788 // slaves is less than this value.
789 in_addr_t cli_bind_address; // bind address for CLI
790 char hostname[MAXHOSTNAME]; // hostname (overridden by -h on command line)
791 // Guest change
792 char guest_user[MAXUSER]; // Guest account username
793
794 #ifdef BGP
795 #define BGP_NUM_PEERS 2
796 uint16_t as_number;
797 struct {
798 char name[64];
799 uint16_t as;
800 int keepalive;
801 int hold;
802 struct in_addr update_source;
803 } neighbour[BGP_NUM_PEERS];
804 in_addr_t nexthop_address;
805 struct in6_addr nexthop6_address;
806 #endif
807
808 int echo_timeout; // Time between last packet sent and LCP ECHO generation
809 int idle_echo_timeout; // Time between last packet seen and
810 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
811 in_addr_t iftun_address;
812 int disable_lac_func;
813 int auth_tunnel_change_addr_src;
814 int highest_rlnsid;
815 uint16_t bind_portremotelns;
816 in_addr_t bind_address_remotelns;
817 char pppoe_if_to_bind[IFNAMSIZ]; // Name pppoe interface to bind
818 char pppoe_service_name[64]; // pppoe service name
819 char pppoe_ac_name[64];
820 uint8_t pppoe_hwaddr[ETH_ALEN]; // MAC addr of interface pppoe to bind
821 int pppoe_only_equal_svc_name; // Accept only PADI with service-name equal to server
822 int disable_sending_hello; // Disable l2tp sending HELLO message for Apple compatibility.
823 int disable_no_spoof; // Disable no spoof (permit load balancing client --> internet)
824 int nbudpfd; // number UDP file handle
825 int nbmultiaddress; // number multi address to bind
826 int indexlacudpfd; // Index UDP LAC file handle (in udpfd[])
827 int nbmultihostname; // number hostname, normally the same number as the nbudpfd
828 int grp_txrate_average_time; // caculation txrate average time (default 10s)
829 in_addr_t bind_n_address[MAX_BINDADDR];
830 in_addr_t iftun_n_address[MAX_BINDADDR];
831 char bind_multi_address[256];
832 char multi_hostname[512];
833 char multi_n_hostname[MAX_NBHOSTNAME][MAXHOSTNAME]; // list hostname
834 } configt;
835
836 enum config_typet { INT, STRING, UNSIGNED_LONG, SHORT, BOOL, IPv4, IPv6 };
837 typedef struct
838 {
839 char *key;
840 int offset;
841 int size;
842 enum config_typet type;
843 } config_descriptt;
844
845 typedef struct
846 {
847 uint8_t op; // operation
848 #define FILTER_PORT_OP_NONE 0 // all ports match
849 #define FILTER_PORT_OP_EQ 1
850 #define FILTER_PORT_OP_NEQ 2
851 #define FILTER_PORT_OP_GT 3
852 #define FILTER_PORT_OP_LT 4
853 #define FILTER_PORT_OP_RANGE 5
854 uint16_t port; // port (host byte order)
855 uint16_t port2; // range
856 } ip_filter_portt;
857
858 typedef struct
859 {
860 int action; // permit/deny
861 #define FILTER_ACTION_DENY 1
862 #define FILTER_ACTION_PERMIT 2
863 uint8_t proto; // protocol: IPPROTO_* (netinet/in.h)
864 in_addr_t src_ip; // source ip (network byte order)
865 in_addr_t src_wild;
866 ip_filter_portt src_ports;
867 in_addr_t dst_ip; // dest ip
868 in_addr_t dst_wild;
869 ip_filter_portt dst_ports;
870 uint8_t frag; // apply to non-initial fragments
871 uint8_t tcp_flag_op; // match type: any, all, established
872 #define FILTER_FLAG_OP_ANY 1
873 #define FILTER_FLAG_OP_ALL 2
874 #define FILTER_FLAG_OP_EST 3
875 uint8_t tcp_sflags; // flags set
876 uint8_t tcp_cflags; // flags clear
877 uint32_t counter; // match count
878 } ip_filter_rulet;
879
880 #define TCP_FLAG_FIN 0x01
881 #define TCP_FLAG_SYN 0x02
882 #define TCP_FLAG_RST 0x04
883 #define TCP_FLAG_PSH 0x08
884 #define TCP_FLAG_ACK 0x10
885 #define TCP_FLAG_URG 0x20
886
887 #define MAXFILTER 32
888 #define MAXFILTER_RULES 32
889 typedef struct
890 {
891 char name[32]; // ACL name
892 int extended; // type: 0 = standard, 1 = extended
893 ip_filter_rulet rules[MAXFILTER_RULES];
894 int used; // session ref count
895 } ip_filtert;
896
897 // CDN result/error codes
898 #define CDN_NONE 0, 0
899 #define CDN_TRY_ANOTHER 2, 7
900 #define CDN_ADMIN_DISC 3, 0
901 #define CDN_UNAVAILABLE 4, 0
902
903 // RADIUS Acct-Terminate-Cause values
904 #define TERM_USER_REQUEST 1
905 #define TERM_LOST_CARRIER 2
906 #define TERM_LOST_SERVICE 3
907 #define TERM_IDLE_TIMEOUT 4
908 #define TERM_SESSION_TIMEOUT 5
909 #define TERM_ADMIN_RESET 6
910 #define TERM_ADMIN_REBOOT 7
911 #define TERM_PORT_ERROR 8
912 #define TERM_NAS_ERROR 9
913 #define TERM_NAS_REQUEST 10
914 #define TERM_NAS_REBOOT 11
915 #define TERM_PORT_UNNEEDED 12
916 #define TERM_PORT_PREEMPTED 13
917 #define TERM_PORT_SUSPENDED 14
918 #define TERM_SERVICE_UNAVAILABLE 15
919 #define TERM_CALLBACK 16
920 #define TERM_USER_ERROR 17
921 #define TERM_HOST_REQUEST 18
922 #define TERM_SUPPLICANT_RESTART 19
923 #define TERM_REAUTHENTICATION_FAILURE 20
924 #define TERM_PORT_REINIT 21
925 #define TERM_PORT_DISABLED 22
926
927 // on slaves, alow BGP to withdraw cleanly before exiting
928 #define QUIT_DELAY 5
929
930 // quit actions (master)
931 #define QUIT_FAILOVER 1 // SIGTERM: exit when all control messages have been acked (for cluster failover)
932 #define QUIT_SHUTDOWN 2 // SIGQUIT: shutdown sessions/tunnels, reject new connections
933
934 // arp.c
935 void sendarp(int ifr_idx, const unsigned char* mac, in_addr_t ip);
936
937
938 // ppp.c
939 void processpap(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
940 void processchap(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
941 void lcp_open(sessionidt s, tunnelidt t);
942 void lcp_restart(sessionidt s);
943 void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
944 void processipcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
945 void processipv6cp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
946 void processipin(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
947 void processmpin(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
948 void processmpframe(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l, uint8_t extra);
949 void processipv6in(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
950 void processccp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l);
951 void sendchap(sessionidt s, tunnelidt t);
952 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);
953 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);
954 void sendlcp(sessionidt s, tunnelidt t);
955 void send_ipin(sessionidt s, uint8_t *buf, int len);
956 void sendccp(sessionidt s, tunnelidt t);
957 void protoreject(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l, uint16_t proto);
958 int join_bundle(sessionidt s);
959
960
961 // radius.c
962 void initrad(void);
963 void radiussend(uint16_t r, uint8_t state);
964 void processrad(uint8_t *buf, int len, char socket_index);
965 void radiusretry(uint16_t r);
966 uint16_t radiusnew(sessionidt s);
967 void radiusclear(uint16_t r, sessionidt s);
968 void processdae(uint8_t *buf, int len, struct sockaddr_in *addr, int alen, struct in_addr *local);
969 int rad_tunnel_pwdecode(uint8_t *pl2tpsecret, size_t *pl2tpsecretlen, const char *radiussecret, const uint8_t * auth);
970
971 // l2tpns.c
972 clockt backoff(uint8_t try);
973 void send_ipv6_ra(sessionidt s, tunnelidt t, struct in6_addr *ip);
974 void route6set(sessionidt s, struct in6_addr ip, int prefixlen, int add);
975 sessionidt sessionbyip(in_addr_t ip);
976 sessionidt sessionbyipv6(struct in6_addr ip);
977 sessionidt sessionbyuser(char *username);
978 void increment_counter(uint32_t *counter, uint32_t *wrap, uint32_t delta);
979 void random_data(uint8_t *buf, int len);
980 void sessionkill(sessionidt s, char *reason);
981 void sessionshutdown(sessionidt s, char const *reason, int cdn_result, int cdn_error, int term_cause);
982 void filter_session(sessionidt s, int filter_in, int filter_out);
983 void send_garp(in_addr_t ip);
984 void tunnelsend(uint8_t *buf, uint16_t l, tunnelidt t);
985 int tun_write(uint8_t *data, int size);
986 void adjust_tcp_mss(sessionidt s, tunnelidt t, uint8_t *buf, int len, uint8_t *tcp);
987 void sendipcp(sessionidt s, tunnelidt t);
988 void sendipv6cp(sessionidt s, tunnelidt t);
989 void processudp(uint8_t *buf, int len, struct sockaddr_in *addr, uint16_t indexudpfd);
990 void processipout(uint8_t *buf, int len);
991 void snoop_send_packet(uint8_t *packet, uint16_t size, in_addr_t destination, uint16_t port);
992 int find_filter(char const *name, size_t len);
993 int ip_filter(uint8_t *buf, int len, uint8_t filter);
994 int cmd_show_ipcache(struct cli_def *cli, char *command, char **argv, int argc);
995 int cmd_show_hist_idle(struct cli_def *cli, char *command, char **argv, int argc);
996 int cmd_show_hist_open(struct cli_def *cli, char *command, char **argv, int argc);
997 void netlink_addattr(struct nlmsghdr *nh, int type, const void *data, int alen);
998 ssize_t netlink_send(struct nlmsghdr *nh);
999 void cache_ipmap(in_addr_t ip, sessionidt s);
1000
1001 tunnelidt lac_new_tunnel();
1002 void lac_tunnelclear(tunnelidt t);
1003 void lac_send_SCCRQ(tunnelidt t, uint8_t * auth, unsigned int auth_len);
1004 void lac_send_ICRQ(tunnelidt t, sessionidt s);
1005 void lac_tunnelshutdown(tunnelidt t, char *reason, int result, int error, char *msg);
1006
1007 // grpsess.c
1008 sessionidt grp_getnextsession(groupidt g, in_addr_t ip);
1009 void grp_initdata(void);
1010 void grp_processvendorspecific(sessionidt s, uint8_t *pvs);
1011 groupidt grp_groupbysession(sessionidt s);
1012 groupidt grp_groupbyip(in_addr_t ip);
1013 void grp_setgrouproute(groupidt g, int add);
1014 void grp_time_changed(void);
1015 void grp_removesession(groupidt g, sessionidt s);
1016 int grp_cluster_load_groupe(groupidt g, groupsesst *new);
1017
1018 #undef LOG
1019 #undef LOG_HEX
1020 #define LOG(D, s, t, f, ...) ({ if (D <= config->debug) _log(D, s, t, f, ## __VA_ARGS__); })
1021 #define LOG_HEX(D, t, d, s) ({ if (D <= config->debug) _log_hex(D, t, d, s); })
1022
1023 void _log(int level, sessionidt s, tunnelidt t, const char *format, ...) __attribute__((format (printf, 4, 5)));
1024 void _log_hex(int level, const char *title, const uint8_t *data, int maxsize);
1025
1026
1027 int sessionsetup(sessionidt s, tunnelidt t);
1028 int run_plugins(int plugin_type, void *data);
1029 void rebuild_address_pool(void);
1030 void throttle_session(sessionidt s, int rate_in, int rate_out);
1031 int load_session(sessionidt, sessiont *);
1032 void become_master(void); // We're the master; kick off any required master initializations.
1033
1034
1035 // cli.c
1036 void init_cli();
1037 void cli_init_complete(char *hostname);
1038 void cli_do_file(FILE *fh);
1039 void cli_do(int sockfd);
1040 int cli_arg_help(struct cli_def *cli, int cr_ok, char *entry, ...);
1041
1042
1043 // icmp.c
1044 void host_unreachable(in_addr_t destination, uint16_t id, in_addr_t source, uint8_t *packet, int packet_len);
1045
1046
1047 extern tunnelt *tunnel;
1048 extern bundlet *bundle;
1049 extern sessiont *session;
1050 extern sessionlocalt *sess_local;
1051 extern ippoolt *ip_address_pool;
1052 extern groupsesst *grpsession;
1053 extern groupidt gnextgrpid;
1054 #define sessionfree (session[0].next)
1055
1056
1057 extern configt *config;
1058 extern time_t basetime; // Time when this process started.
1059 extern time_t time_now; // Seconds since EPOCH.
1060 extern char main_quit;
1061 extern uint32_t last_id;
1062 extern struct Tstats *_statistics;
1063 extern in_addr_t my_address;
1064 extern int clifd;
1065 extern int epollfd;
1066 extern int tunidx; // ifr_ifindex of tun device
1067 extern union iphash ip_hash[256];
1068
1069 struct event_data {
1070 enum {
1071 FD_TYPE_CLI,
1072 FD_TYPE_CLUSTER,
1073 FD_TYPE_TUN,
1074 FD_TYPE_UDP,
1075 FD_TYPE_CONTROL,
1076 FD_TYPE_DAE,
1077 FD_TYPE_RADIUS,
1078 FD_TYPE_BGP,
1079 FD_TYPE_NETLINK,
1080 FD_TYPE_PPPOEDISC,
1081 FD_TYPE_PPPOESESS
1082 } type;
1083 int index; // for RADIUS, BGP, UDP
1084 };
1085
1086 #define TIME (config->current_time)
1087
1088 extern uint16_t MRU;
1089 extern uint16_t MSS;
1090
1091 // macros for handling help in cli commands
1092 #define CLI_HELP_REQUESTED (argc > 0 && argv[argc-1][strlen(argv[argc-1])-1] == '?')
1093 #define CLI_HELP_NO_ARGS (argc > 1 || argv[0][1]) ? CLI_OK : cli_arg_help(cli, 1, NULL)
1094
1095 #endif /* __L2TPNS_H__ */