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