any traffic on a tunnel resets lastrec, not just control messages
[l2tpns.git] / cluster.c
1 // L2TPNS Clustering Stuff
2
3 char const *cvs_id_cluster = "$Id: cluster.c,v 1.46 2005-09-02 23:59:56 bodea Exp $";
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdarg.h>
8 #include <unistd.h>
9 #include <inttypes.h>
10 #include <sys/file.h>
11 #include <sys/stat.h>
12 #include <sys/socket.h>
13 #include <netinet/in.h>
14 #include <arpa/inet.h>
15 #include <sys/ioctl.h>
16 #include <net/if.h>
17 #include <string.h>
18 #include <malloc.h>
19 #include <errno.h>
20 #include <libcli.h>
21
22 #include "l2tpns.h"
23 #include "cluster.h"
24 #include "util.h"
25 #include "tbf.h"
26
27 #ifdef BGP
28 #include "bgp.h"
29 #endif
30 /*
31 * All cluster packets have the same format.
32 *
33 * One or more instances of
34 * a 32 bit 'type' id.
35 * a 32 bit 'extra' data dependant on the 'type'.
36 * zero or more bytes of structure data, dependant on the type.
37 *
38 */
39
40 // Module variables.
41 extern int cluster_sockfd; // The filedescriptor for the cluster communications port.
42
43 in_addr_t my_address = 0; // The network address of my ethernet port.
44 static int walk_session_number = 0; // The next session to send when doing the slow table walk.
45 static int walk_tunnel_number = 0; // The next tunnel to send when doing the slow table walk.
46 int forked = 0; // Sanity check: CLI must not diddle with heartbeat table
47
48 #define MAX_HEART_SIZE (8192) // Maximum size of heartbeat packet. Must be less than max IP packet size :)
49 #define MAX_CHANGES (MAX_HEART_SIZE/(sizeof(sessiont) + sizeof(int) ) - 2) // Assumes a session is the biggest type!
50
51 static struct {
52 int type;
53 int id;
54 } cluster_changes[MAX_CHANGES]; // Queue of changed structures that need to go out when next heartbeat.
55
56 static struct {
57 int seq;
58 int size;
59 uint8_t data[MAX_HEART_SIZE];
60 } past_hearts[HB_HISTORY_SIZE]; // Ring buffer of heartbeats that we've recently sent out. Needed so
61 // we can re-transmit if needed.
62
63 static struct {
64 in_addr_t peer;
65 uint32_t basetime;
66 clockt timestamp;
67 int uptodate;
68 } peers[CLUSTER_MAX_SIZE]; // List of all the peers we've heard from.
69 static int num_peers; // Number of peers in list.
70
71 static int rle_decompress(uint8_t **src_p, int ssize, uint8_t *dst, int dsize);
72 static int rle_compress(uint8_t **src_p, int ssize, uint8_t *dst, int dsize);
73
74 //
75 // Create a listening socket
76 //
77 // This joins the cluster multi-cast group.
78 //
79 int cluster_init()
80 {
81 struct sockaddr_in addr;
82 struct sockaddr_in interface_addr;
83 struct ip_mreq mreq;
84 struct ifreq ifr;
85 int opt;
86
87 config->cluster_undefined_sessions = MAXSESSION-1;
88 config->cluster_undefined_tunnels = MAXTUNNEL-1;
89
90 if (!config->cluster_address)
91 return 0;
92 if (!*config->cluster_interface)
93 return 0;
94
95 cluster_sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
96
97 memset(&addr, 0, sizeof(addr));
98 addr.sin_family = AF_INET;
99 addr.sin_port = htons(CLUSTERPORT);
100 addr.sin_addr.s_addr = INADDR_ANY;
101 setsockopt(cluster_sockfd, SOL_SOCKET, SO_REUSEADDR, &addr, sizeof(addr));
102
103 opt = fcntl(cluster_sockfd, F_GETFL, 0);
104 fcntl(cluster_sockfd, F_SETFL, opt | O_NONBLOCK);
105
106 if (bind(cluster_sockfd, (void *) &addr, sizeof(addr)) < 0)
107 {
108 LOG(0, 0, 0, "Failed to bind cluster socket: %s\n", strerror(errno));
109 return -1;
110 }
111
112 strcpy(ifr.ifr_name, config->cluster_interface);
113 if (ioctl(cluster_sockfd, SIOCGIFADDR, &ifr) < 0)
114 {
115 LOG(0, 0, 0, "Failed to get interface address for (%s): %s\n", config->cluster_interface, strerror(errno));
116 return -1;
117 }
118
119 memcpy(&interface_addr, &ifr.ifr_addr, sizeof(interface_addr));
120 my_address = interface_addr.sin_addr.s_addr;
121
122 // Join multicast group.
123 mreq.imr_multiaddr.s_addr = config->cluster_address;
124 mreq.imr_interface = interface_addr.sin_addr;
125
126
127 opt = 0; // Turn off multicast loopback.
128 setsockopt(cluster_sockfd, IPPROTO_IP, IP_MULTICAST_LOOP, &opt, sizeof(opt));
129
130 if (config->cluster_mcast_ttl != 1)
131 {
132 uint8_t ttl = 0;
133 if (config->cluster_mcast_ttl > 0)
134 ttl = config->cluster_mcast_ttl < 256 ? config->cluster_mcast_ttl : 255;
135
136 setsockopt(cluster_sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
137 }
138
139 if (setsockopt(cluster_sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0)
140 {
141 LOG(0, 0, 0, "Failed to setsockopt (join mcast group): %s\n", strerror(errno));
142 return -1;
143 }
144
145 if (setsockopt(cluster_sockfd, IPPROTO_IP, IP_MULTICAST_IF, &interface_addr, sizeof(interface_addr)) < 0)
146 {
147 LOG(0, 0, 0, "Failed to setsockopt (set mcast interface): %s\n", strerror(errno));
148 return -1;
149 }
150
151 config->cluster_last_hb = TIME;
152 config->cluster_seq_number = -1;
153
154 return cluster_sockfd;
155 }
156
157
158 //
159 // Send a chunk of data to the entire cluster (usually via the multicast
160 // address ).
161 //
162
163 static int cluster_send_data(void *data, int datalen)
164 {
165 struct sockaddr_in addr = {0};
166
167 if (!cluster_sockfd) return -1;
168 if (!config->cluster_address) return 0;
169
170 addr.sin_addr.s_addr = config->cluster_address;
171 addr.sin_port = htons(CLUSTERPORT);
172 addr.sin_family = AF_INET;
173
174 LOG(5, 0, 0, "Cluster send data: %d bytes\n", datalen);
175
176 if (sendto(cluster_sockfd, data, datalen, MSG_NOSIGNAL, (void *) &addr, sizeof(addr)) < 0)
177 {
178 LOG(0, 0, 0, "sendto: %s\n", strerror(errno));
179 return -1;
180 }
181
182 return 0;
183 }
184
185 //
186 // Add a chunk of data to a heartbeat packet.
187 // Maintains the format. Assumes that the caller
188 // has passed in a big enough buffer!
189 //
190 static void add_type(uint8_t **p, int type, int more, uint8_t *data, int size)
191 {
192 *((uint32_t *) (*p)) = type;
193 *p += sizeof(uint32_t);
194
195 *((uint32_t *)(*p)) = more;
196 *p += sizeof(uint32_t);
197
198 if (data && size > 0) {
199 memcpy(*p, data, size);
200 *p += size;
201 }
202 }
203
204 // advertise our presence via BGP or gratuitous ARP
205 static void advertise_routes(void)
206 {
207 #ifdef BGP
208 if (bgp_configured)
209 bgp_enable_routing(1);
210 else
211 #endif /* BGP */
212 if (config->send_garp)
213 send_garp(config->bind_address); // Start taking traffic.
214 }
215
216 // withdraw our routes (BGP only)
217 static void withdraw_routes(void)
218 {
219 #ifdef BGP
220 if (bgp_configured)
221 bgp_enable_routing(0);
222 #endif /* BGP */
223 }
224
225 static void cluster_uptodate(void)
226 {
227 if (config->cluster_iam_uptodate)
228 return;
229
230 if (config->cluster_undefined_sessions || config->cluster_undefined_tunnels)
231 return;
232
233 config->cluster_iam_uptodate = 1;
234
235 LOG(0, 0, 0, "Now uptodate with master.\n");
236 advertise_routes();
237 }
238
239 //
240 // Send a unicast UDP packet to a peer with 'data' as the
241 // contents.
242 //
243 static int peer_send_data(in_addr_t peer, uint8_t *data, int size)
244 {
245 struct sockaddr_in addr = {0};
246
247 if (!cluster_sockfd) return -1;
248 if (!config->cluster_address) return 0;
249
250 if (!peer) // Odd??
251 return -1;
252
253 addr.sin_addr.s_addr = peer;
254 addr.sin_port = htons(CLUSTERPORT);
255 addr.sin_family = AF_INET;
256
257 LOG_HEX(5, "Peer send", data, size);
258
259 if (sendto(cluster_sockfd, data, size, MSG_NOSIGNAL, (void *) &addr, sizeof(addr)) < 0)
260 {
261 LOG(0, 0, 0, "sendto: %s\n", strerror(errno));
262 return -1;
263 }
264
265 return 0;
266 }
267
268 //
269 // Send a structured message to a peer with a single element of type 'type'.
270 //
271 static int peer_send_message(in_addr_t peer, int type, int more, uint8_t *data, int size)
272 {
273 uint8_t buf[65536]; // Vast overkill.
274 uint8_t *p = buf;
275
276 LOG(4, 0, 0, "Sending message to peer (type %d, more %d, size %d)\n", type, more, size);
277 add_type(&p, type, more, data, size);
278
279 return peer_send_data(peer, buf, (p-buf) );
280 }
281
282 // send a packet to the master
283 static int _forward_packet(uint8_t *data, int size, in_addr_t addr, int port, int type)
284 {
285 uint8_t buf[65536]; // Vast overkill.
286 uint8_t *p = buf;
287
288 if (!config->cluster_master_address) // No election has been held yet. Just skip it.
289 return -1;
290
291 LOG(4, 0, 0, "Forwarding packet from %s to master (size %d)\n", fmtaddr(addr, 0), size);
292
293 STAT(c_forwarded);
294 add_type(&p, type, addr, (uint8_t *) &port, sizeof(port)); // ick. should be uint16_t
295 memcpy(p, data, size);
296 p += size;
297
298 return peer_send_data(config->cluster_master_address, buf, (p - buf));
299 }
300
301 //
302 // Forward a state changing packet to the master.
303 //
304 // The master just processes the payload as if it had
305 // received it off the tun device.
306 //
307 int master_forward_packet(uint8_t *data, int size, in_addr_t addr, int port)
308 {
309 return _forward_packet(data, size, addr, port, C_FORWARD);
310 }
311
312 // Forward a DAE RADIUS packet to the master.
313 int master_forward_dae_packet(uint8_t *data, int size, in_addr_t addr, int port)
314 {
315 return _forward_packet(data, size, addr, port, C_FORWARD_DAE);
316 }
317
318 //
319 // Forward a throttled packet to the master for handling.
320 //
321 // The master just drops the packet into the appropriate
322 // token bucket queue, and lets normal processing take care
323 // of it.
324 //
325 int master_throttle_packet(int tbfid, uint8_t *data, int size)
326 {
327 uint8_t buf[65536]; // Vast overkill.
328 uint8_t *p = buf;
329
330 if (!config->cluster_master_address) // No election has been held yet. Just skip it.
331 return -1;
332
333 LOG(4, 0, 0, "Throttling packet master (size %d, tbfid %d)\n", size, tbfid);
334
335 add_type(&p, C_THROTTLE, tbfid, data, size);
336
337 return peer_send_data(config->cluster_master_address, buf, (p-buf) );
338
339 }
340
341 //
342 // Forward a walled garden packet to the master for handling.
343 //
344 // The master just writes the packet straight to the tun
345 // device (where is will normally loop through the
346 // firewall rules, and come back in on the tun device)
347 //
348 // (Note that this must be called with the tun header
349 // as the start of the data).
350 int master_garden_packet(sessionidt s, uint8_t *data, int size)
351 {
352 uint8_t buf[65536]; // Vast overkill.
353 uint8_t *p = buf;
354
355 if (!config->cluster_master_address) // No election has been held yet. Just skip it.
356 return -1;
357
358 LOG(4, 0, 0, "Walled garden packet to master (size %d)\n", size);
359
360 add_type(&p, C_GARDEN, s, data, size);
361
362 return peer_send_data(config->cluster_master_address, buf, (p-buf));
363
364 }
365
366 //
367 // Send a chunk of data as a heartbeat..
368 // We save it in the history buffer as we do so.
369 //
370 static void send_heartbeat(int seq, uint8_t *data, int size)
371 {
372 int i;
373
374 if (size > sizeof(past_hearts[0].data))
375 {
376 LOG(0, 0, 0, "Tried to heartbeat something larger than the maximum packet!\n");
377 kill(0, SIGTERM);
378 exit(1);
379 }
380 i = seq % HB_HISTORY_SIZE;
381 past_hearts[i].seq = seq;
382 past_hearts[i].size = size;
383 memcpy(&past_hearts[i].data, data, size); // Save it.
384 cluster_send_data(data, size);
385 }
386
387 //
388 // Send an 'i am alive' message to every machine in the cluster.
389 //
390 void cluster_send_ping(time_t basetime)
391 {
392 uint8_t buff[100 + sizeof(pingt)];
393 uint8_t *p = buff;
394 pingt x;
395
396 if (config->cluster_iam_master && basetime) // We're heartbeating so no need to ping.
397 return;
398
399 LOG(5, 0, 0, "Sending cluster ping...\n");
400
401 x.ver = 1;
402 x.addr = config->bind_address;
403 x.undef = config->cluster_undefined_sessions + config->cluster_undefined_tunnels;
404 x.basetime = basetime;
405
406 add_type(&p, C_PING, basetime, (uint8_t *) &x, sizeof(x));
407 cluster_send_data(buff, (p-buff) );
408 }
409
410 //
411 // Walk the session counters looking for non-zero ones to send
412 // to the master. We send up to 600 of them at one time.
413 // We examine a maximum of 3000 sessions.
414 // (50k max session should mean that we normally
415 // examine the entire session table every 25 seconds).
416
417 #define MAX_B_RECS (600)
418 void master_update_counts(void)
419 {
420 int i, c;
421 bytest b[MAX_B_RECS+1];
422
423 if (config->cluster_iam_master) // Only happens on the slaves.
424 return;
425
426 if (!config->cluster_master_address) // If we don't have a master, skip it for a while.
427 return;
428
429 // C_BYTES format changed in 2.1.0 (cluster version 5)
430 // during upgrade from previous versions, hang onto our counters
431 // for a bit until the new master comes up
432 if (config->cluster_last_hb_ver < 5)
433 return;
434
435 i = MAX_B_RECS * 5; // Examine max 3000 sessions;
436 if (config->cluster_highest_sessionid > i)
437 i = config->cluster_highest_sessionid;
438
439 for ( c = 0; i > 0 ; --i) {
440 // Next session to look at.
441 walk_session_number++;
442 if ( walk_session_number > config->cluster_highest_sessionid)
443 walk_session_number = 1;
444
445 if (!sess_local[walk_session_number].cin && !sess_local[walk_session_number].cout)
446 continue; // Unchanged. Skip it.
447
448 b[c].sid = walk_session_number;
449 b[c].pin = sess_local[walk_session_number].pin;
450 b[c].pout = sess_local[walk_session_number].pout;
451 b[c].cin = sess_local[walk_session_number].cin;
452 b[c].cout = sess_local[walk_session_number].cout;
453
454 // Reset counters.
455 sess_local[walk_session_number].pin = sess_local[walk_session_number].pout = 0;
456 sess_local[walk_session_number].cin = sess_local[walk_session_number].cout = 0;
457
458 if (++c > MAX_B_RECS) // Send a max of 600 elements in a packet.
459 break;
460 }
461
462 if (!c) // Didn't find any that changes. Get out of here!
463 return;
464
465
466 // Forward the data to the master.
467 LOG(4, 0, 0, "Sending byte counters to master (%d elements)\n", c);
468 peer_send_message(config->cluster_master_address, C_BYTES, c, (uint8_t *) &b, sizeof(b[0]) * c);
469 return;
470 }
471
472 //
473 // On the master, check how our slaves are going. If
474 // one of them's not up-to-date we'll heartbeat faster.
475 // If we don't have any of them, then we need to turn
476 // on our own packet handling!
477 //
478 void cluster_check_slaves(void)
479 {
480 int i;
481 static int have_peers = 0;
482 int had_peers = have_peers;
483 clockt t = TIME;
484
485 if (!config->cluster_iam_master)
486 return; // Only runs on the master...
487
488 config->cluster_iam_uptodate = 1; // cleared in loop below
489
490 for (i = have_peers = 0; i < num_peers; i++)
491 {
492 if ((peers[i].timestamp + config->cluster_hb_timeout) < t)
493 continue; // Stale peer! Skip them.
494
495 if (!peers[i].basetime)
496 continue; // Shutdown peer! Skip them.
497
498 if (peers[i].uptodate)
499 have_peers++;
500 else
501 config->cluster_iam_uptodate = 0; // Start fast heartbeats
502 }
503
504 // in a cluster, withdraw/add routes when we get a peer/lose peers
505 if (have_peers != had_peers)
506 {
507 if (had_peers < config->cluster_master_min_adv &&
508 have_peers >= config->cluster_master_min_adv)
509 withdraw_routes();
510
511 else if (had_peers >= config->cluster_master_min_adv &&
512 have_peers < config->cluster_master_min_adv)
513 advertise_routes();
514 }
515 }
516
517 //
518 // Check that we have a master. If it's been too
519 // long since we heard from a master then hold an election.
520 //
521 void cluster_check_master(void)
522 {
523 int i, count, tcount, high_unique_id = 0;
524 int last_free = 0;
525 clockt t = TIME;
526 static int probed = 0;
527 int have_peers;
528
529 if (config->cluster_iam_master)
530 return; // Only runs on the slaves...
531
532 // If the master is late (missed 2 hearbeats by a second and a
533 // hair) it may be that the switch has dropped us from the
534 // multicast group, try unicasting probes to the master
535 // which will hopefully respond with a unicast heartbeat that
536 // will allow us to limp along until the querier next runs.
537 if (config->cluster_master_address
538 && TIME > (config->cluster_last_hb + 2 * config->cluster_hb_interval + 11))
539 {
540 if (!probed || (TIME > (probed + 2 * config->cluster_hb_interval)))
541 {
542 probed = TIME;
543 LOG(1, 0, 0, "Heartbeat from master %.1fs late, probing...\n",
544 0.1 * (TIME - (config->cluster_last_hb + config->cluster_hb_interval)));
545
546 peer_send_message(config->cluster_master_address,
547 C_LASTSEEN, config->cluster_seq_number, NULL, 0);
548 }
549 } else { // We got a recent heartbeat; reset the probe flag.
550 probed = 0;
551 }
552
553 if (TIME < (config->cluster_last_hb + config->cluster_hb_timeout))
554 return; // Everything's ok!
555
556 config->cluster_last_hb = TIME + 1; // Just the one election thanks.
557 config->cluster_master_address = 0;
558
559 LOG(0, 0, 0, "Master timed out! Holding election...\n");
560
561 // In the process of shutting down, can't be master
562 if (main_quit)
563 return;
564
565 for (i = have_peers = 0; i < num_peers; i++)
566 {
567 if ((peers[i].timestamp + config->cluster_hb_timeout) < t)
568 continue; // Stale peer! Skip them.
569
570 if (!peers[i].basetime)
571 continue; // Shutdown peer! Skip them.
572
573 if (peers[i].basetime < basetime) {
574 LOG(1, 0, 0, "Expecting %s to become master\n", fmtaddr(peers[i].peer, 0));
575 return; // They'll win the election. Get out of here.
576 }
577
578 if (peers[i].basetime == basetime &&
579 peers[i].peer > my_address) {
580 LOG(1, 0, 0, "Expecting %s to become master\n", fmtaddr(peers[i].peer, 0));
581 return; // They'll win the election. Wait for them to come up.
582 }
583
584 if (peers[i].uptodate)
585 have_peers++;
586 }
587
588 // Wow. it's been ages since I last heard a heartbeat
589 // and I'm better than an of my peers so it's time
590 // to become a master!!!
591
592 config->cluster_iam_master = 1;
593
594 LOG(0, 0, 0, "I am declaring myself the master!\n");
595
596 if (have_peers < config->cluster_master_min_adv)
597 advertise_routes();
598 else
599 withdraw_routes();
600
601 if (config->cluster_seq_number == -1)
602 config->cluster_seq_number = 0;
603
604 //
605 // Go through and mark all the tunnels as defined.
606 // Count the highest used tunnel number as well.
607 //
608 config->cluster_highest_tunnelid = 0;
609 for (i = 0, tcount = 0; i < MAXTUNNEL; ++i) {
610 if (tunnel[i].state == TUNNELUNDEF)
611 tunnel[i].state = TUNNELFREE;
612
613 if (tunnel[i].state != TUNNELFREE && i > config->cluster_highest_tunnelid)
614 config->cluster_highest_tunnelid = i;
615 }
616
617 //
618 // Go through and mark all the sessions as being defined.
619 // reset the idle timeouts.
620 // add temporary byte counters to permanent ones.
621 // Re-string the free list.
622 // Find the ID of the highest session.
623 last_free = 0;
624 high_unique_id = 0;
625 config->cluster_highest_sessionid = 0;
626 for (i = 0, count = 0; i < MAXSESSION; ++i) {
627 if (session[i].tunnel == T_UNDEF) {
628 session[i].tunnel = T_FREE;
629 ++count;
630 }
631
632 if (!session[i].opened) { // Unused session. Add to free list.
633 memset(&session[i], 0, sizeof(session[i]));
634 session[i].tunnel = T_FREE;
635 session[last_free].next = i;
636 session[i].next = 0;
637 last_free = i;
638 continue;
639 }
640
641 // Reset idle timeouts..
642 session[i].last_packet = time_now;
643
644 // Reset die relative to our uptime rather than the old master's
645 if (session[i].die) session[i].die = TIME;
646
647 // Accumulate un-sent byte/packet counters.
648 increment_counter(&session[i].cin, &session[i].cin_wrap, sess_local[i].cin);
649 increment_counter(&session[i].cout, &session[i].cout_wrap, sess_local[i].cout);
650 session[i].cin_delta += sess_local[i].cin;
651 session[i].cout_delta += sess_local[i].cout;
652
653 session[i].pin += sess_local[i].pin;
654 session[i].pout += sess_local[i].pout;
655
656 sess_local[i].cin = sess_local[i].cout = 0;
657 sess_local[i].pin = sess_local[i].pout = 0;
658
659 sess_local[i].radius = 0; // Reset authentication as the radius blocks aren't up to date.
660
661 if (session[i].unique_id >= high_unique_id) // This is different to the index into the session table!!!
662 high_unique_id = session[i].unique_id+1;
663
664 session[i].tbf_in = session[i].tbf_out = 0; // Remove stale pointers from old master.
665 throttle_session(i, session[i].throttle_in, session[i].throttle_out);
666
667 config->cluster_highest_sessionid = i;
668 }
669
670 session[last_free].next = 0; // End of chain.
671 last_id = high_unique_id; // Keep track of the highest used session ID.
672
673 become_master();
674
675 rebuild_address_pool();
676
677 // If we're not the very first master, this is a big issue!
678 if(count>0)
679 LOG(0, 0, 0, "Warning: Fixed %d uninitialized sessions in becoming master!\n", count);
680
681 config->cluster_undefined_sessions = 0;
682 config->cluster_undefined_tunnels = 0;
683 config->cluster_iam_uptodate = 1; // assume all peers are up-to-date
684
685 // FIXME. We need to fix up the tunnel control message
686 // queue here! There's a number of other variables we
687 // should also update.
688 }
689
690
691 //
692 // Check that our session table is validly matching what the
693 // master has in mind.
694 //
695 // In particular, if we have too many sessions marked 'undefined'
696 // we fix it up here, and we ensure that the 'first free session'
697 // pointer is valid.
698 //
699 static void cluster_check_sessions(int highsession, int freesession_ptr, int hightunnel)
700 {
701 int i;
702
703 sessionfree = freesession_ptr; // Keep the freesession ptr valid.
704
705 if (config->cluster_iam_uptodate)
706 return;
707
708 if (highsession > config->cluster_undefined_sessions && hightunnel > config->cluster_undefined_tunnels)
709 return;
710
711 // Clear out defined sessions, counting the number of
712 // undefs remaining.
713 config->cluster_undefined_sessions = 0;
714 for (i = 1 ; i < MAXSESSION; ++i) {
715 if (i > highsession) {
716 if (session[i].tunnel == T_UNDEF) session[i].tunnel = T_FREE; // Defined.
717 continue;
718 }
719
720 if (session[i].tunnel == T_UNDEF)
721 ++config->cluster_undefined_sessions;
722 }
723
724 // Clear out defined tunnels, counting the number of
725 // undefs remaining.
726 config->cluster_undefined_tunnels = 0;
727 for (i = 1 ; i < MAXTUNNEL; ++i) {
728 if (i > hightunnel) {
729 if (tunnel[i].state == TUNNELUNDEF) tunnel[i].state = TUNNELFREE; // Defined.
730 continue;
731 }
732
733 if (tunnel[i].state == TUNNELUNDEF)
734 ++config->cluster_undefined_tunnels;
735 }
736
737
738 if (config->cluster_undefined_sessions || config->cluster_undefined_tunnels) {
739 LOG(2, 0, 0, "Cleared undefined sessions/tunnels. %d sess (high %d), %d tunn (high %d)\n",
740 config->cluster_undefined_sessions, highsession, config->cluster_undefined_tunnels, hightunnel);
741 return;
742 }
743
744 // Are we up to date?
745
746 if (!config->cluster_iam_uptodate)
747 cluster_uptodate();
748 }
749
750 static int hb_add_type(uint8_t **p, int type, int id)
751 {
752 switch (type) {
753 case C_CSESSION: { // Compressed C_SESSION.
754 uint8_t c[sizeof(sessiont) * 2]; // Bigger than worst case.
755 uint8_t *d = (uint8_t *) &session[id];
756 uint8_t *orig = d;
757 int size;
758
759 size = rle_compress( &d, sizeof(sessiont), c, sizeof(c) );
760
761 // Did we compress the full structure, and is the size actually
762 // reduced??
763 if ( (d - orig) == sizeof(sessiont) && size < sizeof(sessiont) ) {
764 add_type(p, C_CSESSION, id, c, size);
765 break;
766 }
767 // Failed to compress : Fall through.
768 }
769 case C_SESSION:
770 add_type(p, C_SESSION, id, (uint8_t *) &session[id], sizeof(sessiont));
771 break;
772
773 case C_CTUNNEL: { // Compressed C_TUNNEL
774 uint8_t c[sizeof(tunnelt) * 2]; // Bigger than worst case.
775 uint8_t *d = (uint8_t *) &tunnel[id];
776 uint8_t *orig = d;
777 int size;
778
779 size = rle_compress( &d, sizeof(tunnelt), c, sizeof(c) );
780
781 // Did we compress the full structure, and is the size actually
782 // reduced??
783 if ( (d - orig) == sizeof(tunnelt) && size < sizeof(tunnelt) ) {
784 add_type(p, C_CTUNNEL, id, c, size);
785 break;
786 }
787 // Failed to compress : Fall through.
788 }
789 case C_TUNNEL:
790 add_type(p, C_TUNNEL, id, (uint8_t *) &tunnel[id], sizeof(tunnelt));
791 break;
792 default:
793 LOG(0, 0, 0, "Found an invalid type in heart queue! (%d)\n", type);
794 kill(0, SIGTERM);
795 exit(1);
796 }
797 return 0;
798 }
799
800 //
801 // Send a heartbeat, incidently sending out any queued changes..
802 //
803 void cluster_heartbeat()
804 {
805 int i, count = 0, tcount = 0;
806 uint8_t buff[MAX_HEART_SIZE + sizeof(heartt) + sizeof(int) ];
807 heartt h;
808 uint8_t *p = buff;
809
810 if (!config->cluster_iam_master) // Only the master does this.
811 return;
812
813 config->cluster_table_version += config->cluster_num_changes;
814
815 // Fill out the heartbeat header.
816 memset(&h, 0, sizeof(h));
817
818 h.version = HB_VERSION;
819 h.seq = config->cluster_seq_number;
820 h.basetime = basetime;
821 h.clusterid = config->bind_address; // Will this do??
822 h.basetime = basetime;
823 h.highsession = config->cluster_highest_sessionid;
824 h.freesession = sessionfree;
825 h.hightunnel = config->cluster_highest_tunnelid;
826 h.size_sess = sizeof(sessiont); // Just in case.
827 h.size_tunn = sizeof(tunnelt);
828 h.interval = config->cluster_hb_interval;
829 h.timeout = config->cluster_hb_timeout;
830 h.table_version = config->cluster_table_version;
831
832 add_type(&p, C_HEARTBEAT, HB_VERSION, (uint8_t *) &h, sizeof(h));
833
834 for (i = 0; i < config->cluster_num_changes; ++i) {
835 hb_add_type(&p, cluster_changes[i].type, cluster_changes[i].id);
836 }
837
838 if (p > (buff + sizeof(buff))) { // Did we somehow manage to overun the buffer?
839 LOG(0, 0, 0, "FATAL: Overran the heartbeat buffer! This is fatal. Exiting. (size %d)\n", (int) (p - buff));
840 kill(0, SIGTERM);
841 exit(1);
842 }
843
844 //
845 // Fill out the packet with sessions from the session table...
846 // (not forgetting to leave space so we can get some tunnels in too )
847 while ( (p + sizeof(uint32_t) * 2 + sizeof(sessiont) * 2 ) < (buff + MAX_HEART_SIZE) ) {
848
849 if (!walk_session_number) // session #0 isn't valid.
850 ++walk_session_number;
851
852 if (count >= config->cluster_highest_sessionid) // If we're a small cluster, don't go wild.
853 break;
854
855 hb_add_type(&p, C_CSESSION, walk_session_number);
856 walk_session_number = (1+walk_session_number)%(config->cluster_highest_sessionid+1); // +1 avoids divide by zero.
857
858 ++count; // Count the number of extra sessions we're sending.
859 }
860
861 //
862 // Fill out the packet with tunnels from the tunnel table...
863 // This effectively means we walk the tunnel table more quickly
864 // than the session table. This is good because stuffing up a
865 // tunnel is a much bigger deal than stuffing up a session.
866 //
867 while ( (p + sizeof(uint32_t) * 2 + sizeof(tunnelt) ) < (buff + MAX_HEART_SIZE) ) {
868
869 if (!walk_tunnel_number) // tunnel #0 isn't valid.
870 ++walk_tunnel_number;
871
872 if (tcount >= config->cluster_highest_tunnelid)
873 break;
874
875 hb_add_type(&p, C_CTUNNEL, walk_tunnel_number);
876 walk_tunnel_number = (1+walk_tunnel_number)%(config->cluster_highest_tunnelid+1); // +1 avoids divide by zero.
877
878 ++tcount;
879 }
880
881 //
882 // Did we do something wrong?
883 if (p > (buff + sizeof(buff))) { // Did we somehow manage to overun the buffer?
884 LOG(0, 0, 0, "Overran the heartbeat buffer now! This is fatal. Exiting. (size %d)\n", (int) (p - buff));
885 kill(0, SIGTERM);
886 exit(1);
887 }
888
889 LOG(3, 0, 0, "Sending v%d heartbeat #%d, change #%" PRIu64 " with %d changes "
890 "(%d x-sess, %d x-tunnels, %d highsess, %d hightun, size %d)\n",
891 HB_VERSION, h.seq, h.table_version, config->cluster_num_changes,
892 count, tcount, config->cluster_highest_sessionid,
893 config->cluster_highest_tunnelid, (int) (p - buff));
894
895 config->cluster_num_changes = 0;
896
897 send_heartbeat(h.seq, buff, (p-buff) ); // Send out the heartbeat to the cluster, keeping a copy of it.
898
899 config->cluster_seq_number = (config->cluster_seq_number+1)%HB_MAX_SEQ; // Next seq number to use.
900 }
901
902 //
903 // A structure of type 'type' has changed; Add it to the queue to send.
904 //
905 static int type_changed(int type, int id)
906 {
907 int i;
908
909 for (i = 0 ; i < config->cluster_num_changes ; ++i)
910 if ( cluster_changes[i].id == id &&
911 cluster_changes[i].type == type)
912 return 0; // Already marked for change.
913
914 cluster_changes[i].type = type;
915 cluster_changes[i].id = id;
916 ++config->cluster_num_changes;
917
918 if (config->cluster_num_changes > MAX_CHANGES)
919 cluster_heartbeat(); // flush now
920
921 return 1;
922 }
923
924
925 // A particular session has been changed!
926 int cluster_send_session(int sid)
927 {
928 if (!config->cluster_iam_master) {
929 LOG(0, sid, 0, "I'm not a master, but I just tried to change a session!\n");
930 return -1;
931 }
932
933 if (forked) {
934 LOG(0, sid, 0, "cluster_send_session called from child process!\n");
935 return -1;
936 }
937
938 return type_changed(C_CSESSION, sid);
939 }
940
941 // A particular tunnel has been changed!
942 int cluster_send_tunnel(int tid)
943 {
944 if (!config->cluster_iam_master) {
945 LOG(0, 0, tid, "I'm not a master, but I just tried to change a tunnel!\n");
946 return -1;
947 }
948
949 return type_changed(C_CTUNNEL, tid);
950 }
951
952
953 //
954 // We're a master, and a slave has just told us that it's
955 // missed a packet. We'll resend it every packet since
956 // the last one it's seen.
957 //
958 static int cluster_catchup_slave(int seq, in_addr_t slave)
959 {
960 int s;
961 int diff;
962
963 LOG(1, 0, 0, "Slave %s sent LASTSEEN with seq %d\n", fmtaddr(slave, 0), seq);
964 if (!config->cluster_iam_master) {
965 LOG(1, 0, 0, "Got LASTSEEN but I'm not a master! Redirecting it to %s.\n",
966 fmtaddr(config->cluster_master_address, 0));
967
968 peer_send_message(slave, C_MASTER, config->cluster_master_address, NULL, 0);
969 return 0;
970 }
971
972 diff = config->cluster_seq_number - seq; // How many packet do we need to send?
973 if (diff < 0)
974 diff += HB_MAX_SEQ;
975
976 if (diff >= HB_HISTORY_SIZE) { // Ouch. We don't have the packet to send it!
977 LOG(0, 0, 0, "A slave asked for message %d when our seq number is %d. Killing it.\n",
978 seq, config->cluster_seq_number);
979 return peer_send_message(slave, C_KILL, seq, NULL, 0);// Kill the slave. Nothing else to do.
980 }
981
982 LOG(1, 0, 0, "Sending %d catchup packets to slave %s\n", diff, fmtaddr(slave, 0) );
983
984 // Now resend every packet that it missed, in order.
985 while (seq != config->cluster_seq_number) {
986 s = seq % HB_HISTORY_SIZE;
987 if (seq != past_hearts[s].seq) {
988 LOG(0, 0, 0, "Tried to re-send heartbeat for %s but %d doesn't match %d! (%d,%d)\n",
989 fmtaddr(slave, 0), seq, past_hearts[s].seq, s, config->cluster_seq_number);
990 return -1; // What to do here!?
991 }
992 peer_send_data(slave, past_hearts[s].data, past_hearts[s].size);
993 seq = (seq+1)%HB_MAX_SEQ; // Increment to next seq number.
994 }
995 return 0; // All good!
996 }
997
998 //
999 // We've heard from another peer! Add it to the list
1000 // that we select from at election time.
1001 //
1002 static int cluster_add_peer(in_addr_t peer, time_t basetime, pingt *pp, int size)
1003 {
1004 int i;
1005 in_addr_t clusterid;
1006 pingt p;
1007
1008 // Allow for backward compatability.
1009 // Just the ping packet into a new structure to allow
1010 // for the possibility that we might have received
1011 // more or fewer elements than we were expecting.
1012 if (size > sizeof(p))
1013 size = sizeof(p);
1014
1015 memset( (void *) &p, 0, sizeof(p) );
1016 memcpy( (void *) &p, (void *) pp, size);
1017
1018 clusterid = p.addr;
1019 if (clusterid != config->bind_address)
1020 {
1021 // Is this for us?
1022 LOG(4, 0, 0, "Skipping ping from %s (different cluster)\n", fmtaddr(peer, 0));
1023 return 0;
1024 }
1025
1026 for (i = 0; i < num_peers ; ++i)
1027 {
1028 if (peers[i].peer != peer)
1029 continue;
1030
1031 // This peer already exists. Just update the timestamp.
1032 peers[i].basetime = basetime;
1033 peers[i].timestamp = TIME;
1034 peers[i].uptodate = !p.undef;
1035 break;
1036 }
1037
1038 // Is this the master shutting down??
1039 if (peer == config->cluster_master_address) {
1040 LOG(3, 0, 0, "Master %s %s\n", fmtaddr(config->cluster_master_address, 0),
1041 basetime ? "has restarted!" : "shutting down...");
1042
1043 config->cluster_master_address = 0;
1044 config->cluster_last_hb = 0; // Force an election.
1045 cluster_check_master();
1046 }
1047
1048 if (i >= num_peers)
1049 {
1050 LOG(4, 0, 0, "Adding %s as a peer\n", fmtaddr(peer, 0));
1051
1052 // Not found. Is there a stale slot to re-use?
1053 for (i = 0; i < num_peers ; ++i)
1054 {
1055 if (!peers[i].basetime) // Shutdown
1056 break;
1057
1058 if ((peers[i].timestamp + config->cluster_hb_timeout * 10) < TIME) // Stale.
1059 break;
1060 }
1061
1062 if (i >= CLUSTER_MAX_SIZE)
1063 {
1064 // Too many peers!!
1065 LOG(0, 0, 0, "Tried to add %s as a peer, but I already have %d of them!\n", fmtaddr(peer, 0), i);
1066 return -1;
1067 }
1068
1069 peers[i].peer = peer;
1070 peers[i].basetime = basetime;
1071 peers[i].timestamp = TIME;
1072 peers[i].uptodate = !p.undef;
1073 if (i == num_peers)
1074 ++num_peers;
1075
1076 LOG(1, 0, 0, "Added %s as a new peer. Now %d peers\n", fmtaddr(peer, 0), num_peers);
1077 }
1078
1079 return 1;
1080 }
1081
1082 // A slave responds with C_MASTER when it gets a message which should have gone to a master.
1083 static int cluster_set_master(in_addr_t peer, in_addr_t master)
1084 {
1085 if (config->cluster_iam_master) // Sanity...
1086 return 0;
1087
1088 LOG(3, 0, 0, "Peer %s set the master to %s...\n", fmtaddr(peer, 0),
1089 fmtaddr(master, 1));
1090
1091 config->cluster_master_address = master;
1092 if (master)
1093 {
1094 // catchup with new master
1095 peer_send_message(master, C_LASTSEEN, config->cluster_seq_number, NULL, 0);
1096
1097 // delay next election
1098 config->cluster_last_hb = TIME;
1099 }
1100
1101 // run election (or reset "probed" if master was set)
1102 cluster_check_master();
1103 return 0;
1104 }
1105
1106 /* Handle the slave updating the byte counters for the master. */
1107 //
1108 // Note that we don't mark the session as dirty; We rely on
1109 // the slow table walk to propogate this back out to the slaves.
1110 //
1111 static int cluster_handle_bytes(uint8_t *data, int size)
1112 {
1113 bytest *b;
1114
1115 b = (bytest *) data;
1116
1117 LOG(3, 0, 0, "Got byte counter update (size %d)\n", size);
1118
1119 /* Loop around, adding the byte
1120 counts to each of the sessions. */
1121
1122 while (size >= sizeof(*b) ) {
1123 if (b->sid > MAXSESSION) {
1124 LOG(0, 0, 0, "Got C_BYTES with session #%d!\n", b->sid);
1125 return -1; /* Abort processing */
1126 }
1127
1128 session[b->sid].pin += b->pin;
1129 session[b->sid].pout += b->pout;
1130
1131 increment_counter(&session[b->sid].cin, &session[b->sid].cin_wrap, b->cin);
1132 increment_counter(&session[b->sid].cout, &session[b->sid].cout_wrap, b->cout);
1133
1134 session[b->sid].cin_delta += b->cin;
1135 session[b->sid].cout_delta += b->cout;
1136
1137 if (b->cin)
1138 session[b->sid].last_packet = time_now; // Reset idle timer!
1139
1140 size -= sizeof(*b);
1141 ++b;
1142 }
1143
1144 if (size != 0)
1145 LOG(0, 0, 0, "Got C_BYTES with %d bytes of trailing junk!\n", size);
1146
1147 return size;
1148 }
1149
1150 //
1151 // Handle receiving a session structure in a heartbeat packet.
1152 //
1153 static int cluster_recv_session(int more, uint8_t *p)
1154 {
1155 if (more >= MAXSESSION) {
1156 LOG(0, 0, 0, "DANGER: Received a heartbeat session id > MAXSESSION!\n");
1157 return -1;
1158 }
1159
1160 if (session[more].tunnel == T_UNDEF) {
1161 if (config->cluster_iam_uptodate) { // Sanity.
1162 LOG(0, 0, 0, "I thought I was uptodate but I just found an undefined session!\n");
1163 } else {
1164 --config->cluster_undefined_sessions;
1165 }
1166 }
1167
1168 load_session(more, (sessiont *) p); // Copy session into session table..
1169
1170 LOG(5, more, 0, "Received session update (%d undef)\n", config->cluster_undefined_sessions);
1171
1172 if (!config->cluster_iam_uptodate)
1173 cluster_uptodate(); // Check to see if we're up to date.
1174
1175 return 0;
1176 }
1177
1178 static int cluster_recv_tunnel(int more, uint8_t *p)
1179 {
1180 if (more >= MAXTUNNEL) {
1181 LOG(0, 0, 0, "DANGER: Received a tunnel session id > MAXTUNNEL!\n");
1182 return -1;
1183 }
1184
1185 if (tunnel[more].state == TUNNELUNDEF) {
1186 if (config->cluster_iam_uptodate) { // Sanity.
1187 LOG(0, 0, 0, "I thought I was uptodate but I just found an undefined tunnel!\n");
1188 } else {
1189 --config->cluster_undefined_tunnels;
1190 }
1191 }
1192
1193 memcpy(&tunnel[more], p, sizeof(tunnel[more]) );
1194
1195 //
1196 // Clear tunnel control messages. These are dynamically allocated.
1197 // If we get unlucky, this may cause the tunnel to drop!
1198 //
1199 tunnel[more].controls = tunnel[more].controle = NULL;
1200 tunnel[more].controlc = 0;
1201
1202 LOG(5, 0, more, "Received tunnel update\n");
1203
1204 if (!config->cluster_iam_uptodate)
1205 cluster_uptodate(); // Check to see if we're up to date.
1206
1207 return 0;
1208 }
1209
1210
1211 // pre v5 heartbeat session structure
1212 struct oldsession {
1213 sessionidt next;
1214 sessionidt far;
1215 tunnelidt tunnel;
1216 in_addr_t ip;
1217 int ip_pool_index;
1218 unsigned long unique_id;
1219 uint16_t nr;
1220 uint16_t ns;
1221 uint32_t magic;
1222 uint32_t cin, cout;
1223 uint32_t pin, pout;
1224 uint32_t total_cin;
1225 uint32_t total_cout;
1226 uint32_t id;
1227 uint16_t throttle_in;
1228 uint16_t throttle_out;
1229 clockt opened;
1230 clockt die;
1231 time_t last_packet;
1232 in_addr_t dns1, dns2;
1233 routet route[MAXROUTE];
1234 uint16_t radius;
1235 uint16_t mru;
1236 uint16_t tbf_in;
1237 uint16_t tbf_out;
1238 uint8_t l2tp_flags;
1239 uint8_t reserved_old_snoop;
1240 uint8_t walled_garden;
1241 uint8_t flags1;
1242 char random_vector[MAXTEL];
1243 int random_vector_length;
1244 char user[129];
1245 char called[MAXTEL];
1246 char calling[MAXTEL];
1247 uint32_t tx_connect_speed;
1248 uint32_t rx_connect_speed;
1249 uint32_t flags;
1250 #define SF_IPCP_ACKED 1 // Has this session seen an IPCP Ack?
1251 #define SF_LCP_ACKED 2 // LCP negotiated
1252 #define SF_CCP_ACKED 4 // CCP negotiated
1253 in_addr_t snoop_ip;
1254 uint16_t snoop_port;
1255 uint16_t sid;
1256 uint8_t filter_in;
1257 uint8_t filter_out;
1258 char reserved[18];
1259 };
1260
1261 static uint8_t *convert_session(struct oldsession *old)
1262 {
1263 static sessiont new;
1264 int i;
1265
1266 memset(&new, 0, sizeof(new));
1267
1268 new.next = old->next;
1269 new.far = old->far;
1270 new.tunnel = old->tunnel;
1271 new.l2tp_flags = old->l2tp_flags;
1272 new.ip = old->ip;
1273 new.ip_pool_index = old->ip_pool_index;
1274 new.unique_id = old->unique_id;
1275 new.nr = old->nr;
1276 new.ns = old->ns;
1277 new.magic = old->magic;
1278 new.pin = old->pin;
1279 new.pout = old->pout;
1280 new.cin = old->total_cin;
1281 new.cout = old->total_cout;
1282 new.cin_delta = old->cin;
1283 new.cout_delta = old->cout;
1284 new.throttle_in = old->throttle_in;
1285 new.throttle_out = old->throttle_out;
1286 new.filter_in = old->filter_in;
1287 new.filter_out = old->filter_out;
1288 new.mru = old->mru;
1289 new.opened = old->opened;
1290 new.die = old->die;
1291 new.last_packet = old->last_packet;
1292 new.dns1 = old->dns1;
1293 new.dns2 = old->dns2;
1294 new.tbf_in = old->tbf_in;
1295 new.tbf_out = old->tbf_out;
1296 new.random_vector_length = old->random_vector_length;
1297 new.tx_connect_speed = old->tx_connect_speed;
1298 new.rx_connect_speed = old->rx_connect_speed;
1299 new.snoop_ip = old->snoop_ip;
1300 new.snoop_port = old->snoop_port;
1301 new.walled_garden = old->walled_garden;
1302
1303 memcpy(new.random_vector, old->random_vector, sizeof(new.random_vector));
1304 memcpy(new.user, old->user, sizeof(new.user));
1305 memcpy(new.called, old->called, sizeof(new.called));
1306 memcpy(new.calling, old->calling, sizeof(new.calling));
1307
1308 for (i = 0; i < MAXROUTE; i++)
1309 memcpy(&new.route[i], &old->route[i], sizeof(new.route[i]));
1310
1311 if (new.opened)
1312 {
1313 new.ppp.phase = Establish;
1314 if (old->flags & (SF_IPCP_ACKED|SF_LCP_ACKED))
1315 {
1316 new.ppp.phase = Network;
1317 new.ppp.lcp = Opened;
1318 new.ppp.ipcp = (old->flags & SF_IPCP_ACKED) ? Opened : Starting;
1319 new.ppp.ccp = (old->flags & SF_CCP_ACKED) ? Opened : Stopped;
1320 }
1321
1322 // no PPPv6 in old session
1323 new.ppp.ipv6cp = Stopped;
1324 }
1325
1326 return (uint8_t *) &new;
1327 }
1328
1329 //
1330 // Process a heartbeat..
1331 //
1332 // v3: added interval, timeout
1333 // v4: added table_version
1334 // v5: added ipv6, re-ordered session structure
1335 static int cluster_process_heartbeat(uint8_t *data, int size, int more, uint8_t *p, in_addr_t addr)
1336 {
1337 heartt *h;
1338 int s = size - (p-data);
1339 int i, type;
1340 int hb_ver = more;
1341
1342 #if HB_VERSION != 5
1343 # error "need to update cluster_process_heartbeat()"
1344 #endif
1345
1346 // we handle versions 3 through 5
1347 if (hb_ver < 3 || hb_ver > HB_VERSION) {
1348 LOG(0, 0, 0, "Received a heartbeat version that I don't support (%d)!\n", hb_ver);
1349 return -1; // Ignore it??
1350 }
1351
1352 // Ok. It's a heartbeat packet from a cluster master!
1353 if (s < sizeof(*h))
1354 goto shortpacket;
1355
1356 h = (heartt *) p;
1357 p += sizeof(*h);
1358 s -= sizeof(*h);
1359
1360 if (h->clusterid != config->bind_address)
1361 return -1; // It's not part of our cluster.
1362
1363 if (config->cluster_iam_master) { // Sanity...
1364 // Note that this MUST match the election process above!
1365
1366 LOG(0, 0, 0, "I just got a heartbeat from master %s, but _I_ am the master!\n", fmtaddr(addr, 0));
1367 if (!h->basetime) {
1368 LOG(0, 0, 0, "Heartbeat with zero basetime! Ignoring\n");
1369 return -1; // Skip it.
1370 }
1371
1372 if (hb_ver >= 4) {
1373 if (h->table_version > config->cluster_table_version) {
1374 LOG(0, 0, 0, "They've seen more state changes (%" PRIu64 " vs my %" PRIu64 ") so I'm gone!\n",
1375 h->table_version, config->cluster_table_version);
1376
1377 kill(0, SIGTERM);
1378 exit(1);
1379 }
1380 if (h->table_version < config->cluster_table_version)
1381 return -1;
1382 }
1383
1384 if (basetime > h->basetime) {
1385 LOG(0, 0, 0, "They're an older master than me so I'm gone!\n");
1386 kill(0, SIGTERM);
1387 exit(1);
1388 }
1389
1390 if (basetime < h->basetime)
1391 return -1;
1392
1393 if (my_address < addr) { // Tie breaker.
1394 LOG(0, 0, 0, "They're a higher IP address than me, so I'm gone!\n");
1395 kill(0, SIGTERM);
1396 exit(1);
1397 }
1398
1399 //
1400 // Send it a unicast heartbeat to see give it a chance to die.
1401 // NOTE: It's actually safe to do seq-number - 1 without checking
1402 // for wrap around.
1403 //
1404 cluster_catchup_slave(config->cluster_seq_number - 1, addr);
1405
1406 return -1; // Skip it.
1407 }
1408
1409 //
1410 // Try and guard against a stray master appearing.
1411 //
1412 // Ignore heartbeats received from another master before the
1413 // timeout (less a smidgen) for the old master has elapsed.
1414 //
1415 // Note that after a clean failover, the cluster_master_address
1416 // is cleared, so this doesn't run.
1417 //
1418 if (config->cluster_master_address && addr != config->cluster_master_address) {
1419 LOG(0, 0, 0, "Ignoring stray heartbeat from %s, current master %s has not yet timed out (last heartbeat %.1f seconds ago).\n",
1420 fmtaddr(addr, 0), fmtaddr(config->cluster_master_address, 1),
1421 0.1 * (TIME - config->cluster_last_hb));
1422 return -1; // ignore
1423 }
1424
1425 if (config->cluster_seq_number == -1) // Don't have one. Just align to the master...
1426 config->cluster_seq_number = h->seq;
1427
1428 config->cluster_last_hb = TIME; // Reset to ensure that we don't become master!!
1429 config->cluster_last_hb_ver = hb_ver; // remember what cluster version the master is using
1430
1431 if (config->cluster_seq_number != h->seq) { // Out of sequence heartbeat!
1432 static int lastseen_seq = 0;
1433 static time_t lastseen_time = 0;
1434
1435 // limit to once per second for a particular seq#
1436 int ask = (config->cluster_seq_number != lastseen_seq || time_now != lastseen_time);
1437
1438 LOG(1, 0, 0, "HB: Got seq# %d but was expecting %d. %s.\n",
1439 h->seq, config->cluster_seq_number,
1440 ask ? "Asking for resend" : "Ignoring");
1441
1442 if (ask)
1443 {
1444 lastseen_seq = config->cluster_seq_number;
1445 lastseen_time = time_now;
1446 peer_send_message(addr, C_LASTSEEN, config->cluster_seq_number, NULL, 0);
1447 }
1448
1449 config->cluster_last_hb = TIME; // Reset to ensure that we don't become master!!
1450
1451 // Just drop the packet. The master will resend it as part of the catchup.
1452
1453 return 0;
1454 }
1455 // Save the packet in our buffer.
1456 // This is needed in case we become the master.
1457 config->cluster_seq_number = (h->seq+1)%HB_MAX_SEQ;
1458 i = h->seq % HB_HISTORY_SIZE;
1459 past_hearts[i].seq = h->seq;
1460 past_hearts[i].size = size;
1461 memcpy(&past_hearts[i].data, data, size); // Save it.
1462
1463
1464 // Check that we don't have too many undefined sessions, and
1465 // that the free session pointer is correct.
1466 cluster_check_sessions(h->highsession, h->freesession, h->hightunnel);
1467
1468 if (h->interval != config->cluster_hb_interval)
1469 {
1470 LOG(2, 0, 0, "Master set ping/heartbeat interval to %u (was %u)\n",
1471 h->interval, config->cluster_hb_interval);
1472
1473 config->cluster_hb_interval = h->interval;
1474 }
1475
1476 if (h->timeout != config->cluster_hb_timeout)
1477 {
1478 LOG(2, 0, 0, "Master set heartbeat timeout to %u (was %u)\n",
1479 h->timeout, config->cluster_hb_timeout);
1480
1481 config->cluster_hb_timeout = h->timeout;
1482 }
1483
1484 // Ok. process the packet...
1485 while ( s > 0) {
1486
1487 type = *((uint32_t *) p);
1488 p += sizeof(uint32_t);
1489 s -= sizeof(uint32_t);
1490
1491 more = *((uint32_t *) p);
1492 p += sizeof(uint32_t);
1493 s -= sizeof(uint32_t);
1494
1495 switch (type) {
1496 case C_CSESSION: { // Compressed session structure.
1497 uint8_t c[ sizeof(sessiont) + 2];
1498 int size;
1499 uint8_t *orig_p = p;
1500
1501 size = rle_decompress((uint8_t **) &p, s, c, sizeof(c) );
1502 s -= (p - orig_p);
1503
1504 // session struct changed with v5
1505 if (hb_ver < 5)
1506 {
1507 if (size != sizeof(struct oldsession)) {
1508 LOG(0, 0, 0, "DANGER: Received a v%d CSESSION that didn't decompress correctly!\n", hb_ver);
1509 // Now what? Should exit! No-longer up to date!
1510 break;
1511 }
1512 cluster_recv_session(more, convert_session((struct oldsession *) c));
1513 break;
1514 }
1515
1516 if (size != sizeof(sessiont) ) { // Ouch! Very very bad!
1517 LOG(0, 0, 0, "DANGER: Received a CSESSION that didn't decompress correctly!\n");
1518 // Now what? Should exit! No-longer up to date!
1519 break;
1520 }
1521
1522 cluster_recv_session(more, c);
1523 break;
1524 }
1525 case C_SESSION:
1526 if (hb_ver < 5)
1527 {
1528 if (s < sizeof(struct oldsession))
1529 goto shortpacket;
1530
1531 cluster_recv_session(more, convert_session((struct oldsession *) p));
1532
1533 p += sizeof(struct oldsession);
1534 s -= sizeof(struct oldsession);
1535 break;
1536 }
1537
1538 if ( s < sizeof(session[more]))
1539 goto shortpacket;
1540
1541 cluster_recv_session(more, p);
1542
1543 p += sizeof(session[more]);
1544 s -= sizeof(session[more]);
1545 break;
1546
1547 case C_CTUNNEL: { // Compressed tunnel structure.
1548 uint8_t c[ sizeof(tunnelt) + 2];
1549 int size;
1550 uint8_t *orig_p = p;
1551
1552 size = rle_decompress((uint8_t **) &p, s, c, sizeof(c));
1553 s -= (p - orig_p);
1554
1555 if (size != sizeof(tunnelt) ) { // Ouch! Very very bad!
1556 LOG(0, 0, 0, "DANGER: Received a CSESSION that didn't decompress correctly!\n");
1557 // Now what? Should exit! No-longer up to date!
1558 break;
1559 }
1560
1561 cluster_recv_tunnel(more, c);
1562 break;
1563
1564 }
1565 case C_TUNNEL:
1566 if ( s < sizeof(tunnel[more]))
1567 goto shortpacket;
1568
1569 cluster_recv_tunnel(more, p);
1570
1571 p += sizeof(tunnel[more]);
1572 s -= sizeof(tunnel[more]);
1573 break;
1574 default:
1575 LOG(0, 0, 0, "DANGER: I received a heartbeat element where I didn't understand the type! (%d)\n", type);
1576 return -1; // can't process any more of the packet!!
1577 }
1578 }
1579
1580 if (config->cluster_master_address != addr)
1581 {
1582 LOG(0, 0, 0, "My master just changed from %s to %s!\n",
1583 fmtaddr(config->cluster_master_address, 0), fmtaddr(addr, 1));
1584
1585 config->cluster_master_address = addr;
1586 }
1587
1588 config->cluster_last_hb = TIME; // Successfully received a heartbeat!
1589 config->cluster_table_version = h->table_version;
1590 return 0;
1591
1592 shortpacket:
1593 LOG(0, 0, 0, "I got an incomplete heartbeat packet! This means I'm probably out of sync!!\n");
1594 return -1;
1595 }
1596
1597 //
1598 // We got a packet on the cluster port!
1599 // Handle pings, lastseens, and heartbeats!
1600 //
1601 int processcluster(uint8_t *data, int size, in_addr_t addr)
1602 {
1603 int type, more;
1604 uint8_t *p = data;
1605 int s = size;
1606
1607 if (addr == my_address)
1608 return -1; // Ignore it. Something looped back the multicast!
1609
1610 LOG(5, 0, 0, "Process cluster: %d bytes from %s\n", size, fmtaddr(addr, 0));
1611
1612 if (s <= 0) // Any data there??
1613 return -1;
1614
1615 if (s < 8)
1616 goto shortpacket;
1617
1618 type = *((uint32_t *) p);
1619 p += sizeof(uint32_t);
1620 s -= sizeof(uint32_t);
1621
1622 more = *((uint32_t *) p);
1623 p += sizeof(uint32_t);
1624 s -= sizeof(uint32_t);
1625
1626 switch (type)
1627 {
1628 case C_PING: // Update the peers table.
1629 return cluster_add_peer(addr, more, (pingt *) p, s);
1630
1631 case C_MASTER: // Our master is wrong
1632 return cluster_set_master(addr, more);
1633
1634 case C_LASTSEEN: // Catch up a slave (slave missed a packet).
1635 return cluster_catchup_slave(more, addr);
1636
1637 case C_FORWARD: // Forwarded control packet. pass off to processudp.
1638 case C_FORWARD_DAE: // Forwarded DAE packet. pass off to processdae.
1639 if (!config->cluster_iam_master)
1640 {
1641 LOG(0, 0, 0, "I'm not the master, but I got a C_FORWARD_%s from %s?\n",
1642 type == C_FORWARD_DAE ? "_DAE" : "", fmtaddr(addr, 0));
1643
1644 return -1;
1645 }
1646 else
1647 {
1648 struct sockaddr_in a;
1649 a.sin_addr.s_addr = more;
1650
1651 a.sin_port = *(int *) p;
1652 s -= sizeof(int);
1653 p += sizeof(int);
1654
1655 LOG(4, 0, 0, "Got a forwarded %spacket... (%s:%d)\n",
1656 type == C_FORWARD_DAE ? "DAE " : "", fmtaddr(more, 0), a.sin_port);
1657
1658 STAT(recv_forward);
1659 if (type == C_FORWARD_DAE)
1660 processdae(p, s, &a, sizeof(a));
1661 else
1662 processudp(p, s, &a);
1663
1664 return 0;
1665 }
1666
1667 case C_THROTTLE: { // Receive a forwarded packet from a slave.
1668 if (!config->cluster_iam_master) {
1669 LOG(0, 0, 0, "I'm not the master, but I got a C_THROTTLE from %s?\n", fmtaddr(addr, 0));
1670 return -1;
1671 }
1672
1673 tbf_queue_packet(more, p, s); // The TBF id tells wether it goes in or out.
1674 return 0;
1675 }
1676 case C_GARDEN:
1677 // Receive a walled garden packet from a slave.
1678 if (!config->cluster_iam_master) {
1679 LOG(0, 0, 0, "I'm not the master, but I got a C_GARDEN from %s?\n", fmtaddr(addr, 0));
1680 return -1;
1681 }
1682
1683 tun_write(p, s);
1684 return 0;
1685
1686 case C_BYTES:
1687 if (!config->cluster_iam_master) {
1688 LOG(0, 0, 0, "I'm not the master, but I got a C_BYTES from %s?\n", fmtaddr(addr, 0));
1689 return -1;
1690 }
1691
1692 return cluster_handle_bytes(p, s);
1693
1694 case C_KILL: // The master asked us to die!? (usually because we're too out of date).
1695 if (config->cluster_iam_master) {
1696 LOG(0, 0, 0, "_I_ am master, but I received a C_KILL from %s! (Seq# %d)\n", fmtaddr(addr, 0), more);
1697 return -1;
1698 }
1699 if (more != config->cluster_seq_number) {
1700 LOG(0, 0, 0, "The master asked us to die but the seq number didn't match!?\n");
1701 return -1;
1702 }
1703
1704 if (addr != config->cluster_master_address) {
1705 LOG(0, 0, 0, "Received a C_KILL from %s which doesn't match config->cluster_master_address (%s)\n",
1706 fmtaddr(addr, 0), fmtaddr(config->cluster_master_address, 1));
1707 // We can only warn about it. The master might really have switched!
1708 }
1709
1710 LOG(0, 0, 0, "Received a valid C_KILL: I'm going to die now.\n");
1711 kill(0, SIGTERM);
1712 exit(0); // Lets be paranoid;
1713 return -1; // Just signalling the compiler.
1714
1715 case C_HEARTBEAT:
1716 LOG(4, 0, 0, "Got a heartbeat from %s\n", fmtaddr(addr, 0));
1717 return cluster_process_heartbeat(data, size, more, p, addr);
1718
1719 default:
1720 LOG(0, 0, 0, "Strange type packet received on cluster socket (%d)\n", type);
1721 return -1;
1722 }
1723 return 0;
1724
1725 shortpacket:
1726 LOG(0, 0, 0, "I got a _short_ cluster heartbeat packet! This means I'm probably out of sync!!\n");
1727 return -1;
1728 }
1729
1730 //====================================================================================================
1731
1732 int cmd_show_cluster(struct cli_def *cli, char *command, char **argv, int argc)
1733 {
1734 int i;
1735
1736 if (CLI_HELP_REQUESTED)
1737 return CLI_HELP_NO_ARGS;
1738
1739 cli_print(cli, "Cluster status : %s", config->cluster_iam_master ? "Master" : "Slave" );
1740 cli_print(cli, "My address : %s", fmtaddr(my_address, 0));
1741 cli_print(cli, "VIP address : %s", fmtaddr(config->bind_address, 0));
1742 cli_print(cli, "Multicast address: %s", fmtaddr(config->cluster_address, 0));
1743 cli_print(cli, "Multicast i'face : %s", config->cluster_interface);
1744
1745 if (!config->cluster_iam_master) {
1746 cli_print(cli, "My master : %s (last heartbeat %.1f seconds old)",
1747 config->cluster_master_address
1748 ? fmtaddr(config->cluster_master_address, 0)
1749 : "Not defined",
1750 0.1 * (TIME - config->cluster_last_hb));
1751 cli_print(cli, "Uptodate : %s", config->cluster_iam_uptodate ? "Yes" : "No");
1752 cli_print(cli, "Table version # : %" PRIu64, config->cluster_table_version);
1753 cli_print(cli, "Next sequence number expected: %d", config->cluster_seq_number);
1754 cli_print(cli, "%d sessions undefined of %d", config->cluster_undefined_sessions, config->cluster_highest_sessionid);
1755 cli_print(cli, "%d tunnels undefined of %d", config->cluster_undefined_tunnels, config->cluster_highest_tunnelid);
1756 } else {
1757 cli_print(cli, "Table version # : %" PRIu64, config->cluster_table_version);
1758 cli_print(cli, "Next heartbeat # : %d", config->cluster_seq_number);
1759 cli_print(cli, "Highest session : %d", config->cluster_highest_sessionid);
1760 cli_print(cli, "Highest tunnel : %d", config->cluster_highest_tunnelid);
1761 cli_print(cli, "%d changes queued for sending", config->cluster_num_changes);
1762 }
1763 cli_print(cli, "%d peers.", num_peers);
1764
1765 if (num_peers)
1766 cli_print(cli, "%20s %10s %8s", "Address", "Basetime", "Age");
1767 for (i = 0; i < num_peers; ++i) {
1768 cli_print(cli, "%20s %10u %8d", fmtaddr(peers[i].peer, 0),
1769 peers[i].basetime, TIME - peers[i].timestamp);
1770 }
1771 return CLI_OK;
1772 }
1773
1774 //
1775 // Simple run-length-encoding compression.
1776 // Format is
1777 // 1 byte < 128 = count of non-zero bytes following. // Not legal to be zero.
1778 // n non-zero bytes;
1779 // or
1780 // 1 byte > 128 = (count - 128) run of zero bytes. //
1781 // repeat.
1782 // count == 0 indicates end of compressed stream.
1783 //
1784 // Compress from 'src' into 'dst'. return number of bytes
1785 // used from 'dst'.
1786 // Updates *src_p to indicate 1 past last bytes used.
1787 //
1788 // We could get an extra byte in the zero runs by storing (count-1)
1789 // but I'm playing it safe.
1790 //
1791 // Worst case is a 50% expansion in space required (trying to
1792 // compress { 0x00, 0x01 } * N )
1793 static int rle_compress(uint8_t **src_p, int ssize, uint8_t *dst, int dsize)
1794 {
1795 int count;
1796 int orig_dsize = dsize;
1797 uint8_t *x, *src;
1798 src = *src_p;
1799
1800 while (ssize > 0 && dsize > 2) {
1801 count = 0;
1802 x = dst++; --dsize; // Reserve space for count byte..
1803
1804 if (*src) { // Copy a run of non-zero bytes.
1805 while (*src && count < 127 && ssize > 0 && dsize > 1) { // Count number of non-zero bytes.
1806 *dst++ = *src++;
1807 --dsize; --ssize;
1808 ++count;
1809 }
1810 *x = count; // Store number of non-zero bytes. Guarenteed to be non-zero!
1811
1812 } else { // Compress a run of zero bytes.
1813 while (*src == 0 && count < 127 && ssize > 0) {
1814 ++src;
1815 --ssize;
1816 ++count;
1817 }
1818 *x = count | 0x80 ;
1819 }
1820 }
1821
1822 *dst++ = 0x0; // Add Stop byte.
1823 --dsize;
1824
1825 *src_p = src;
1826 return (orig_dsize - dsize);
1827 }
1828
1829 //
1830 // Decompress the buffer into **p.
1831 // 'psize' is the size of the decompression buffer available.
1832 //
1833 // Returns the number of bytes decompressed.
1834 //
1835 // Decompresses from '*src_p' into 'dst'.
1836 // Return the number of dst bytes used.
1837 // Updates the 'src_p' pointer to point to the
1838 // first un-used byte.
1839 static int rle_decompress(uint8_t **src_p, int ssize, uint8_t *dst, int dsize)
1840 {
1841 int count;
1842 int orig_dsize = dsize;
1843 uint8_t *src = *src_p;
1844
1845 while (ssize >0 && dsize > 0) { // While there's more to decompress, and there's room in the decompress buffer...
1846 count = *src++; --ssize; // get the count byte from the source.
1847 if (count == 0x0) // End marker reached? If so, finish.
1848 break;
1849
1850 if (count & 0x80) { // Decompress a run of zeros
1851 for (count &= 0x7f ; count > 0 && dsize > 0; --count) {
1852 *dst++ = 0x0;
1853 --dsize;
1854 }
1855 } else { // Copy run of non-zero bytes.
1856 for ( ; count > 0 && ssize && dsize; --count) { // Copy non-zero bytes across.
1857 *dst++ = *src++;
1858 --ssize; --dsize;
1859 }
1860 }
1861 }
1862 *src_p = src;
1863 return (orig_dsize - dsize);
1864 }