1 // L2TPNS Clustering Stuff
10 #include <sys/socket.h>
11 #include <netinet/in.h>
12 #include <arpa/inet.h>
13 #include <sys/ioctl.h>
29 * All cluster packets have the same format.
31 * One or more instances of
33 * a 32 bit 'extra' data dependant on the 'type'.
34 * zero or more bytes of structure data, dependant on the type.
39 extern int cluster_sockfd
; // The filedescriptor for the cluster communications port.
41 in_addr_t my_address
= 0; // The network address of my ethernet port.
42 static int walk_session_number
= 0; // The next session to send when doing the slow table walk.
43 static int walk_bundle_number
= 0; // The next bundle to send when doing the slow table walk.
44 static int walk_tunnel_number
= 0; // The next tunnel to send when doing the slow table walk.
45 int forked
= 0; // Sanity check: CLI must not diddle with heartbeat table
47 #define MAX_HEART_SIZE (8192) // Maximum size of heartbeat packet. Must be less than max IP packet size :)
48 #define MAX_CHANGES (MAX_HEART_SIZE/(sizeof(sessiont) + sizeof(int) ) - 2) // Assumes a session is the biggest type!
53 } cluster_changes
[MAX_CHANGES
]; // Queue of changed structures that need to go out when next heartbeat.
58 uint8_t data
[MAX_HEART_SIZE
];
59 } past_hearts
[HB_HISTORY_SIZE
]; // Ring buffer of heartbeats that we've recently sent out. Needed so
60 // we can re-transmit if needed.
67 } peers
[CLUSTER_MAX_SIZE
]; // List of all the peers we've heard from.
68 static int num_peers
; // Number of peers in list.
70 static int rle_decompress(uint8_t **src_p
, int ssize
, uint8_t *dst
, int dsize
);
71 static int rle_compress(uint8_t **src_p
, int ssize
, uint8_t *dst
, int dsize
);
74 // Create a listening socket
76 // This joins the cluster multi-cast group.
80 struct sockaddr_in addr
;
81 struct sockaddr_in interface_addr
;
86 config
->cluster_undefined_sessions
= MAXSESSION
-1;
87 config
->cluster_undefined_bundles
= MAXBUNDLE
-1;
88 config
->cluster_undefined_tunnels
= MAXTUNNEL
-1;
90 if (!config
->cluster_address
)
92 if (!*config
->cluster_interface
)
95 cluster_sockfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
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
));
103 opt
= fcntl(cluster_sockfd
, F_GETFL
, 0);
104 fcntl(cluster_sockfd
, F_SETFL
, opt
| O_NONBLOCK
);
106 if (bind(cluster_sockfd
, (void *) &addr
, sizeof(addr
)) < 0)
108 LOG(0, 0, 0, "Failed to bind cluster socket: %s\n", strerror(errno
));
112 strcpy(ifr
.ifr_name
, config
->cluster_interface
);
113 if (ioctl(cluster_sockfd
, SIOCGIFADDR
, &ifr
) < 0)
115 LOG(0, 0, 0, "Failed to get interface address for (%s): %s\n", config
->cluster_interface
, strerror(errno
));
119 memcpy(&interface_addr
, &ifr
.ifr_addr
, sizeof(interface_addr
));
120 my_address
= interface_addr
.sin_addr
.s_addr
;
122 // Join multicast group.
123 mreq
.imr_multiaddr
.s_addr
= config
->cluster_address
;
124 mreq
.imr_interface
= interface_addr
.sin_addr
;
127 opt
= 0; // Turn off multicast loopback.
128 setsockopt(cluster_sockfd
, IPPROTO_IP
, IP_MULTICAST_LOOP
, &opt
, sizeof(opt
));
130 if (config
->cluster_mcast_ttl
!= 1)
133 if (config
->cluster_mcast_ttl
> 0)
134 ttl
= config
->cluster_mcast_ttl
< 256 ? config
->cluster_mcast_ttl
: 255;
136 setsockopt(cluster_sockfd
, IPPROTO_IP
, IP_MULTICAST_TTL
, &ttl
, sizeof(ttl
));
139 if (setsockopt(cluster_sockfd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
, &mreq
, sizeof(mreq
)) < 0)
141 LOG(0, 0, 0, "Failed to setsockopt (join mcast group): %s\n", strerror(errno
));
145 if (setsockopt(cluster_sockfd
, IPPROTO_IP
, IP_MULTICAST_IF
, &interface_addr
, sizeof(interface_addr
)) < 0)
147 LOG(0, 0, 0, "Failed to setsockopt (set mcast interface): %s\n", strerror(errno
));
151 config
->cluster_last_hb
= TIME
;
152 config
->cluster_seq_number
= -1;
154 return cluster_sockfd
;
159 // Send a chunk of data to the entire cluster (usually via the multicast
163 static int cluster_send_data(void *data
, int datalen
)
165 struct sockaddr_in addr
= {0};
167 if (!cluster_sockfd
) return -1;
168 if (!config
->cluster_address
) return 0;
170 addr
.sin_addr
.s_addr
= config
->cluster_address
;
171 addr
.sin_port
= htons(CLUSTERPORT
);
172 addr
.sin_family
= AF_INET
;
174 LOG(5, 0, 0, "Cluster send data: %d bytes\n", datalen
);
176 if (sendto(cluster_sockfd
, data
, datalen
, MSG_NOSIGNAL
, (void *) &addr
, sizeof(addr
)) < 0)
178 LOG(0, 0, 0, "sendto: %s\n", strerror(errno
));
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!
190 static void add_type(uint8_t **p
, int type
, int more
, uint8_t *data
, int size
)
192 *((uint32_t *) (*p
)) = type
;
193 *p
+= sizeof(uint32_t);
195 *((uint32_t *)(*p
)) = more
;
196 *p
+= sizeof(uint32_t);
198 if (data
&& size
> 0) {
199 memcpy(*p
, data
, size
);
204 // advertise our presence via BGP or gratuitous ARP
205 static void advertise_routes(void)
209 bgp_enable_routing(1);
212 if (config
->send_garp
)
213 send_garp(config
->bind_address
); // Start taking traffic.
216 // withdraw our routes (BGP only)
217 static void withdraw_routes(void)
221 bgp_enable_routing(0);
225 static void cluster_uptodate(void)
227 if (config
->cluster_iam_uptodate
)
230 if (config
->cluster_undefined_sessions
|| config
->cluster_undefined_tunnels
|| config
->cluster_undefined_bundles
)
233 config
->cluster_iam_uptodate
= 1;
235 LOG(0, 0, 0, "Now uptodate with master.\n");
240 // Send a unicast UDP packet to a peer with 'data' as the
243 static int peer_send_data(in_addr_t peer
, uint8_t *data
, int size
)
245 struct sockaddr_in addr
= {0};
247 if (!cluster_sockfd
) return -1;
248 if (!config
->cluster_address
) return 0;
253 addr
.sin_addr
.s_addr
= peer
;
254 addr
.sin_port
= htons(CLUSTERPORT
);
255 addr
.sin_family
= AF_INET
;
257 LOG_HEX(5, "Peer send", data
, size
);
259 if (sendto(cluster_sockfd
, data
, size
, MSG_NOSIGNAL
, (void *) &addr
, sizeof(addr
)) < 0)
261 LOG(0, 0, 0, "sendto: %s\n", strerror(errno
));
269 // Send a structured message to a peer with a single element of type 'type'.
271 static int peer_send_message(in_addr_t peer
, int type
, int more
, uint8_t *data
, int size
)
273 uint8_t buf
[65536]; // Vast overkill.
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
);
279 return peer_send_data(peer
, buf
, (p
-buf
) );
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
)
285 uint8_t buf
[65536]; // Vast overkill.
288 if (!config
->cluster_master_address
) // No election has been held yet. Just skip it.
291 LOG(4, 0, 0, "Forwarding packet from %s to master (size %d)\n", fmtaddr(addr
, 0), size
);
294 add_type(&p
, type
, addr
, (uint8_t *) &port
, sizeof(port
)); // ick. should be uint16_t
295 memcpy(p
, data
, size
);
298 return peer_send_data(config
->cluster_master_address
, buf
, (p
- buf
));
302 // Forward a state changing packet to the master.
304 // The master just processes the payload as if it had
305 // received it off the tun device.
307 int master_forward_packet(uint8_t *data
, int size
, in_addr_t addr
, int port
)
309 return _forward_packet(data
, size
, addr
, port
, C_FORWARD
);
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
)
315 return _forward_packet(data
, size
, addr
, port
, C_FORWARD_DAE
);
319 // Forward a throttled packet to the master for handling.
321 // The master just drops the packet into the appropriate
322 // token bucket queue, and lets normal processing take care
325 int master_throttle_packet(int tbfid
, uint8_t *data
, int size
)
327 uint8_t buf
[65536]; // Vast overkill.
330 if (!config
->cluster_master_address
) // No election has been held yet. Just skip it.
333 LOG(4, 0, 0, "Throttling packet master (size %d, tbfid %d)\n", size
, tbfid
);
335 add_type(&p
, C_THROTTLE
, tbfid
, data
, size
);
337 return peer_send_data(config
->cluster_master_address
, buf
, (p
-buf
) );
342 // Forward a walled garden packet to the master for handling.
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)
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
)
352 uint8_t buf
[65536]; // Vast overkill.
355 if (!config
->cluster_master_address
) // No election has been held yet. Just skip it.
358 LOG(4, 0, 0, "Walled garden packet to master (size %d)\n", size
);
360 add_type(&p
, C_GARDEN
, s
, data
, size
);
362 return peer_send_data(config
->cluster_master_address
, buf
, (p
-buf
));
367 // Forward a MPPP packet to the master for handling.
369 // (Note that this must be called with the tun header
370 // as the start of the data).
371 // (i.e. this routine writes to data[-8]).
372 int master_forward_mppp_packet(sessionidt s
, uint8_t *data
, int size
)
374 uint8_t *p
= data
- (2 * sizeof(uint32_t));
377 if (!config
->cluster_master_address
) // No election has been held yet. Just skip it.
380 LOG(4, 0, 0, "Forward MPPP packet to master (size %d)\n", size
);
382 add_type(&p
, C_MPPP_FORWARD
, s
, NULL
, 0);
384 return peer_send_data(config
->cluster_master_address
, psave
, size
+ (2 * sizeof(uint32_t)));
389 // Send a chunk of data as a heartbeat..
390 // We save it in the history buffer as we do so.
392 static void send_heartbeat(int seq
, uint8_t *data
, int size
)
396 if (size
> sizeof(past_hearts
[0].data
))
398 LOG(0, 0, 0, "Tried to heartbeat something larger than the maximum packet!\n");
402 i
= seq
% HB_HISTORY_SIZE
;
403 past_hearts
[i
].seq
= seq
;
404 past_hearts
[i
].size
= size
;
405 memcpy(&past_hearts
[i
].data
, data
, size
); // Save it.
406 cluster_send_data(data
, size
);
410 // Send an 'i am alive' message to every machine in the cluster.
412 void cluster_send_ping(time_t basetime
)
414 uint8_t buff
[100 + sizeof(pingt
)];
418 if (config
->cluster_iam_master
&& basetime
) // We're heartbeating so no need to ping.
421 LOG(5, 0, 0, "Sending cluster ping...\n");
424 x
.addr
= config
->bind_address
;
425 x
.undef
= config
->cluster_undefined_sessions
+ config
->cluster_undefined_tunnels
+ config
->cluster_undefined_bundles
;
426 x
.basetime
= basetime
;
428 add_type(&p
, C_PING
, basetime
, (uint8_t *) &x
, sizeof(x
));
429 cluster_send_data(buff
, (p
-buff
) );
433 // Walk the session counters looking for non-zero ones to send
434 // to the master. We send up to 600 of them at one time.
435 // We examine a maximum of 3000 sessions.
436 // (50k max session should mean that we normally
437 // examine the entire session table every 25 seconds).
439 #define MAX_B_RECS (600)
440 void master_update_counts(void)
443 bytest b
[MAX_B_RECS
+1];
445 if (config
->cluster_iam_master
) // Only happens on the slaves.
448 if (!config
->cluster_master_address
) // If we don't have a master, skip it for a while.
451 i
= MAX_B_RECS
* 5; // Examine max 3000 sessions;
452 if (config
->cluster_highest_sessionid
> i
)
453 i
= config
->cluster_highest_sessionid
;
455 for ( c
= 0; i
> 0 ; --i
) {
456 // Next session to look at.
457 walk_session_number
++;
458 if ( walk_session_number
> config
->cluster_highest_sessionid
)
459 walk_session_number
= 1;
461 if (!sess_local
[walk_session_number
].cin
&& !sess_local
[walk_session_number
].cout
)
462 continue; // Unchanged. Skip it.
464 b
[c
].sid
= walk_session_number
;
465 b
[c
].pin
= sess_local
[walk_session_number
].pin
;
466 b
[c
].pout
= sess_local
[walk_session_number
].pout
;
467 b
[c
].cin
= sess_local
[walk_session_number
].cin
;
468 b
[c
].cout
= sess_local
[walk_session_number
].cout
;
471 sess_local
[walk_session_number
].pin
= sess_local
[walk_session_number
].pout
= 0;
472 sess_local
[walk_session_number
].cin
= sess_local
[walk_session_number
].cout
= 0;
474 if (++c
> MAX_B_RECS
) // Send a max of 600 elements in a packet.
478 if (!c
) // Didn't find any that changes. Get out of here!
482 // Forward the data to the master.
483 LOG(4, 0, 0, "Sending byte counters to master (%d elements)\n", c
);
484 peer_send_message(config
->cluster_master_address
, C_BYTES
, c
, (uint8_t *) &b
, sizeof(b
[0]) * c
);
489 // On the master, check how our slaves are going. If
490 // one of them's not up-to-date we'll heartbeat faster.
491 // If we don't have any of them, then we need to turn
492 // on our own packet handling!
494 void cluster_check_slaves(void)
497 static int have_peers
= 0;
498 int had_peers
= have_peers
;
501 if (!config
->cluster_iam_master
)
502 return; // Only runs on the master...
504 config
->cluster_iam_uptodate
= 1; // cleared in loop below
506 for (i
= have_peers
= 0; i
< num_peers
; i
++)
508 if ((peers
[i
].timestamp
+ config
->cluster_hb_timeout
) < t
)
509 continue; // Stale peer! Skip them.
511 if (!peers
[i
].basetime
)
512 continue; // Shutdown peer! Skip them.
514 if (peers
[i
].uptodate
)
517 config
->cluster_iam_uptodate
= 0; // Start fast heartbeats
520 // in a cluster, withdraw/add routes when we get a peer/lose peers
521 if (have_peers
!= had_peers
)
523 if (had_peers
< config
->cluster_master_min_adv
&&
524 have_peers
>= config
->cluster_master_min_adv
)
527 else if (had_peers
>= config
->cluster_master_min_adv
&&
528 have_peers
< config
->cluster_master_min_adv
)
534 // Check that we have a master. If it's been too
535 // long since we heard from a master then hold an election.
537 void cluster_check_master(void)
539 int i
, count
, high_unique_id
= 0;
542 static int probed
= 0;
545 if (config
->cluster_iam_master
)
546 return; // Only runs on the slaves...
548 // If the master is late (missed 2 hearbeats by a second and a
549 // hair) it may be that the switch has dropped us from the
550 // multicast group, try unicasting probes to the master
551 // which will hopefully respond with a unicast heartbeat that
552 // will allow us to limp along until the querier next runs.
553 if (config
->cluster_master_address
554 && TIME
> (config
->cluster_last_hb
+ 2 * config
->cluster_hb_interval
+ 11))
556 if (!probed
|| (TIME
> (probed
+ 2 * config
->cluster_hb_interval
)))
559 LOG(1, 0, 0, "Heartbeat from master %.1fs late, probing...\n",
560 0.1 * (TIME
- (config
->cluster_last_hb
+ config
->cluster_hb_interval
)));
562 peer_send_message(config
->cluster_master_address
,
563 C_LASTSEEN
, config
->cluster_seq_number
, NULL
, 0);
565 } else { // We got a recent heartbeat; reset the probe flag.
569 if (TIME
< (config
->cluster_last_hb
+ config
->cluster_hb_timeout
))
570 return; // Everything's ok!
572 config
->cluster_last_hb
= TIME
+ 1; // Just the one election thanks.
573 config
->cluster_master_address
= 0;
575 LOG(0, 0, 0, "Master timed out! Holding election...\n");
577 // In the process of shutting down, can't be master
581 for (i
= have_peers
= 0; i
< num_peers
; i
++)
583 if ((peers
[i
].timestamp
+ config
->cluster_hb_timeout
) < t
)
584 continue; // Stale peer! Skip them.
586 if (!peers
[i
].basetime
)
587 continue; // Shutdown peer! Skip them.
589 if (peers
[i
].basetime
< basetime
) {
590 LOG(1, 0, 0, "Expecting %s to become master\n", fmtaddr(peers
[i
].peer
, 0));
591 return; // They'll win the election. Get out of here.
594 if (peers
[i
].basetime
== basetime
&&
595 peers
[i
].peer
> my_address
) {
596 LOG(1, 0, 0, "Expecting %s to become master\n", fmtaddr(peers
[i
].peer
, 0));
597 return; // They'll win the election. Wait for them to come up.
600 if (peers
[i
].uptodate
)
604 // Wow. it's been ages since I last heard a heartbeat
605 // and I'm better than an of my peers so it's time
606 // to become a master!!!
608 config
->cluster_iam_master
= 1;
610 LOG(0, 0, 0, "I am declaring myself the master!\n");
612 if (have_peers
< config
->cluster_master_min_adv
)
617 if (config
->cluster_seq_number
== -1)
618 config
->cluster_seq_number
= 0;
621 // Go through and mark all the tunnels as defined.
622 // Count the highest used tunnel number as well.
624 config
->cluster_highest_tunnelid
= 0;
625 for (i
= 0; i
< MAXTUNNEL
; ++i
) {
626 if (tunnel
[i
].state
== TUNNELUNDEF
)
627 tunnel
[i
].state
= TUNNELFREE
;
629 if (tunnel
[i
].state
!= TUNNELFREE
&& i
> config
->cluster_highest_tunnelid
)
630 config
->cluster_highest_tunnelid
= i
;
634 // Go through and mark all the bundles as defined.
635 // Count the highest used bundle number as well.
637 config
->cluster_highest_bundleid
= 0;
638 for (i
= 0; i
< MAXBUNDLE
; ++i
) {
639 if (bundle
[i
].state
== BUNDLEUNDEF
)
640 bundle
[i
].state
= BUNDLEFREE
;
642 if (bundle
[i
].state
!= BUNDLEFREE
&& i
> config
->cluster_highest_bundleid
)
643 config
->cluster_highest_bundleid
= i
;
647 // Go through and mark all the sessions as being defined.
648 // reset the idle timeouts.
649 // add temporary byte counters to permanent ones.
650 // Re-string the free list.
651 // Find the ID of the highest session.
654 config
->cluster_highest_sessionid
= 0;
655 for (i
= 0, count
= 0; i
< MAXSESSION
; ++i
) {
656 if (session
[i
].tunnel
== T_UNDEF
) {
657 session
[i
].tunnel
= T_FREE
;
661 if (!session
[i
].opened
) { // Unused session. Add to free list.
662 memset(&session
[i
], 0, sizeof(session
[i
]));
663 session
[i
].tunnel
= T_FREE
;
664 session
[last_free
].next
= i
;
670 // Reset idle timeouts..
671 session
[i
].last_packet
= session
[i
].last_data
= time_now
;
673 // Reset die relative to our uptime rather than the old master's
674 if (session
[i
].die
) session
[i
].die
= TIME
;
676 // Accumulate un-sent byte/packet counters.
677 increment_counter(&session
[i
].cin
, &session
[i
].cin_wrap
, sess_local
[i
].cin
);
678 increment_counter(&session
[i
].cout
, &session
[i
].cout_wrap
, sess_local
[i
].cout
);
679 session
[i
].cin_delta
+= sess_local
[i
].cin
;
680 session
[i
].cout_delta
+= sess_local
[i
].cout
;
682 session
[i
].pin
+= sess_local
[i
].pin
;
683 session
[i
].pout
+= sess_local
[i
].pout
;
685 sess_local
[i
].cin
= sess_local
[i
].cout
= 0;
686 sess_local
[i
].pin
= sess_local
[i
].pout
= 0;
688 sess_local
[i
].radius
= 0; // Reset authentication as the radius blocks aren't up to date.
690 if (session
[i
].unique_id
>= high_unique_id
) // This is different to the index into the session table!!!
691 high_unique_id
= session
[i
].unique_id
+1;
693 session
[i
].tbf_in
= session
[i
].tbf_out
= 0; // Remove stale pointers from old master.
694 throttle_session(i
, session
[i
].throttle_in
, session
[i
].throttle_out
);
696 config
->cluster_highest_sessionid
= i
;
699 session
[last_free
].next
= 0; // End of chain.
700 last_id
= high_unique_id
; // Keep track of the highest used session ID.
704 rebuild_address_pool();
706 // If we're not the very first master, this is a big issue!
708 LOG(0, 0, 0, "Warning: Fixed %d uninitialized sessions in becoming master!\n", count
);
710 config
->cluster_undefined_sessions
= 0;
711 config
->cluster_undefined_bundles
= 0;
712 config
->cluster_undefined_tunnels
= 0;
713 config
->cluster_iam_uptodate
= 1; // assume all peers are up-to-date
715 // FIXME. We need to fix up the tunnel control message
716 // queue here! There's a number of other variables we
717 // should also update.
722 // Check that our session table is validly matching what the
723 // master has in mind.
725 // In particular, if we have too many sessions marked 'undefined'
726 // we fix it up here, and we ensure that the 'first free session'
729 static void cluster_check_sessions(int highsession
, int freesession_ptr
, int highbundle
, int hightunnel
)
733 sessionfree
= freesession_ptr
; // Keep the freesession ptr valid.
735 if (config
->cluster_iam_uptodate
)
738 if (highsession
> config
->cluster_undefined_sessions
&& highbundle
> config
->cluster_undefined_bundles
&& hightunnel
> config
->cluster_undefined_tunnels
)
741 // Clear out defined sessions, counting the number of
743 config
->cluster_undefined_sessions
= 0;
744 for (i
= 1 ; i
< MAXSESSION
; ++i
) {
745 if (i
> highsession
) {
746 if (session
[i
].tunnel
== T_UNDEF
) session
[i
].tunnel
= T_FREE
; // Defined.
750 if (session
[i
].tunnel
== T_UNDEF
)
751 ++config
->cluster_undefined_sessions
;
754 // Clear out defined bundles, counting the number of
756 config
->cluster_undefined_bundles
= 0;
757 for (i
= 1 ; i
< MAXBUNDLE
; ++i
) {
758 if (i
> highbundle
) {
759 if (bundle
[i
].state
== BUNDLEUNDEF
) bundle
[i
].state
= BUNDLEFREE
; // Defined.
763 if (bundle
[i
].state
== BUNDLEUNDEF
)
764 ++config
->cluster_undefined_bundles
;
767 // Clear out defined tunnels, counting the number of
769 config
->cluster_undefined_tunnels
= 0;
770 for (i
= 1 ; i
< MAXTUNNEL
; ++i
) {
771 if (i
> hightunnel
) {
772 if (tunnel
[i
].state
== TUNNELUNDEF
) tunnel
[i
].state
= TUNNELFREE
; // Defined.
776 if (tunnel
[i
].state
== TUNNELUNDEF
)
777 ++config
->cluster_undefined_tunnels
;
781 if (config
->cluster_undefined_sessions
|| config
->cluster_undefined_tunnels
|| config
->cluster_undefined_bundles
) {
782 LOG(2, 0, 0, "Cleared undefined sessions/bundles/tunnels. %d sess (high %d), %d bund (high %d), %d tunn (high %d)\n",
783 config
->cluster_undefined_sessions
, highsession
, config
->cluster_undefined_bundles
, highbundle
, config
->cluster_undefined_tunnels
, hightunnel
);
787 // Are we up to date?
789 if (!config
->cluster_iam_uptodate
)
793 static int hb_add_type(uint8_t **p
, int type
, int id
)
796 case C_CSESSION
: { // Compressed C_SESSION.
797 uint8_t c
[sizeof(sessiont
) * 2]; // Bigger than worst case.
798 uint8_t *d
= (uint8_t *) &session
[id
];
802 size
= rle_compress( &d
, sizeof(sessiont
), c
, sizeof(c
) );
804 // Did we compress the full structure, and is the size actually
806 if ( (d
- orig
) == sizeof(sessiont
) && size
< sizeof(sessiont
) ) {
807 add_type(p
, C_CSESSION
, id
, c
, size
);
810 // Failed to compress : Fall through.
813 add_type(p
, C_SESSION
, id
, (uint8_t *) &session
[id
], sizeof(sessiont
));
816 case C_CBUNDLE
: { // Compressed C_BUNDLE
817 uint8_t c
[sizeof(bundlet
) * 2]; // Bigger than worst case.
818 uint8_t *d
= (uint8_t *) &bundle
[id
];
822 size
= rle_compress( &d
, sizeof(bundlet
), c
, sizeof(c
) );
824 // Did we compress the full structure, and is the size actually
826 if ( (d
- orig
) == sizeof(bundlet
) && size
< sizeof(bundlet
) ) {
827 add_type(p
, C_CBUNDLE
, id
, c
, size
);
830 // Failed to compress : Fall through.
834 add_type(p
, C_BUNDLE
, id
, (uint8_t *) &bundle
[id
], sizeof(bundlet
));
837 case C_CTUNNEL
: { // Compressed C_TUNNEL
838 uint8_t c
[sizeof(tunnelt
) * 2]; // Bigger than worst case.
839 uint8_t *d
= (uint8_t *) &tunnel
[id
];
843 size
= rle_compress( &d
, sizeof(tunnelt
), c
, sizeof(c
) );
845 // Did we compress the full structure, and is the size actually
847 if ( (d
- orig
) == sizeof(tunnelt
) && size
< sizeof(tunnelt
) ) {
848 add_type(p
, C_CTUNNEL
, id
, c
, size
);
851 // Failed to compress : Fall through.
854 add_type(p
, C_TUNNEL
, id
, (uint8_t *) &tunnel
[id
], sizeof(tunnelt
));
857 LOG(0, 0, 0, "Found an invalid type in heart queue! (%d)\n", type
);
865 // Send a heartbeat, incidently sending out any queued changes..
867 void cluster_heartbeat()
869 int i
, count
= 0, tcount
= 0, bcount
= 0;
870 uint8_t buff
[MAX_HEART_SIZE
+ sizeof(heartt
) + sizeof(int) ];
874 if (!config
->cluster_iam_master
) // Only the master does this.
877 config
->cluster_table_version
+= config
->cluster_num_changes
;
879 // Fill out the heartbeat header.
880 memset(&h
, 0, sizeof(h
));
882 h
.version
= HB_VERSION
;
883 h
.seq
= config
->cluster_seq_number
;
884 h
.basetime
= basetime
;
885 h
.clusterid
= config
->bind_address
; // Will this do??
886 h
.basetime
= basetime
;
887 h
.highsession
= config
->cluster_highest_sessionid
;
888 h
.freesession
= sessionfree
;
889 h
.hightunnel
= config
->cluster_highest_tunnelid
;
890 h
.highbundle
= config
->cluster_highest_bundleid
;
891 h
.size_sess
= sizeof(sessiont
); // Just in case.
892 h
.size_bund
= sizeof(bundlet
);
893 h
.size_tunn
= sizeof(tunnelt
);
894 h
.interval
= config
->cluster_hb_interval
;
895 h
.timeout
= config
->cluster_hb_timeout
;
896 h
.table_version
= config
->cluster_table_version
;
898 add_type(&p
, C_HEARTBEAT
, HB_VERSION
, (uint8_t *) &h
, sizeof(h
));
900 for (i
= 0; i
< config
->cluster_num_changes
; ++i
) {
901 hb_add_type(&p
, cluster_changes
[i
].type
, cluster_changes
[i
].id
);
904 if (p
> (buff
+ sizeof(buff
))) { // Did we somehow manage to overun the buffer?
905 LOG(0, 0, 0, "FATAL: Overran the heartbeat buffer! This is fatal. Exiting. (size %d)\n", (int) (p
- buff
));
911 // Fill out the packet with sessions from the session table...
912 // (not forgetting to leave space so we can get some tunnels in too )
913 while ( (p
+ sizeof(uint32_t) * 2 + sizeof(sessiont
) * 2 ) < (buff
+ MAX_HEART_SIZE
) ) {
915 if (!walk_session_number
) // session #0 isn't valid.
916 ++walk_session_number
;
918 if (count
>= config
->cluster_highest_sessionid
) // If we're a small cluster, don't go wild.
921 hb_add_type(&p
, C_CSESSION
, walk_session_number
);
922 walk_session_number
= (1+walk_session_number
)%(config
->cluster_highest_sessionid
+1); // +1 avoids divide by zero.
924 ++count
; // Count the number of extra sessions we're sending.
928 // Fill out the packet with tunnels from the tunnel table...
929 // This effectively means we walk the tunnel table more quickly
930 // than the session table. This is good because stuffing up a
931 // tunnel is a much bigger deal than stuffing up a session.
933 while ( (p
+ sizeof(uint32_t) * 2 + sizeof(tunnelt
) ) < (buff
+ MAX_HEART_SIZE
) ) {
935 if (!walk_tunnel_number
) // tunnel #0 isn't valid.
936 ++walk_tunnel_number
;
938 if (tcount
>= config
->cluster_highest_tunnelid
)
941 hb_add_type(&p
, C_CTUNNEL
, walk_tunnel_number
);
942 walk_tunnel_number
= (1+walk_tunnel_number
)%(config
->cluster_highest_tunnelid
+1); // +1 avoids divide by zero.
948 // Fill out the packet with bundles from the bundle table...
949 while ( (p
+ sizeof(uint32_t) * 2 + sizeof(bundlet
) ) < (buff
+ MAX_HEART_SIZE
) ) {
951 if (!walk_bundle_number
) // bundle #0 isn't valid.
952 ++walk_bundle_number
;
954 if (bcount
>= config
->cluster_highest_bundleid
)
957 hb_add_type(&p
, C_CBUNDLE
, walk_bundle_number
);
958 walk_bundle_number
= (1+walk_bundle_number
)%(config
->cluster_highest_bundleid
+1); // +1 avoids divide by zero.
963 // Did we do something wrong?
964 if (p
> (buff
+ sizeof(buff
))) { // Did we somehow manage to overun the buffer?
965 LOG(0, 0, 0, "Overran the heartbeat buffer now! This is fatal. Exiting. (size %d)\n", (int) (p
- buff
));
970 LOG(4, 0, 0, "Sending v%d heartbeat #%d, change #%" PRIu64
" with %d changes "
971 "(%d x-sess, %d x-bundles, %d x-tunnels, %d highsess, %d highbund, %d hightun, size %d)\n",
972 HB_VERSION
, h
.seq
, h
.table_version
, config
->cluster_num_changes
,
973 count
, bcount
, tcount
, config
->cluster_highest_sessionid
, config
->cluster_highest_bundleid
,
974 config
->cluster_highest_tunnelid
, (int) (p
- buff
));
976 config
->cluster_num_changes
= 0;
978 send_heartbeat(h
.seq
, buff
, (p
-buff
) ); // Send out the heartbeat to the cluster, keeping a copy of it.
980 config
->cluster_seq_number
= (config
->cluster_seq_number
+1)%HB_MAX_SEQ
; // Next seq number to use.
984 // A structure of type 'type' has changed; Add it to the queue to send.
986 static int type_changed(int type
, int id
)
990 for (i
= 0 ; i
< config
->cluster_num_changes
; ++i
)
991 if ( cluster_changes
[i
].id
== id
&&
992 cluster_changes
[i
].type
== type
)
993 return 0; // Already marked for change.
995 cluster_changes
[i
].type
= type
;
996 cluster_changes
[i
].id
= id
;
997 ++config
->cluster_num_changes
;
999 if (config
->cluster_num_changes
> MAX_CHANGES
)
1000 cluster_heartbeat(); // flush now
1005 // The deleted session, must be before the new session
1006 int cluster_listinvert_session(int sidnew
, int sidtodel
)
1010 for (i
= 0 ; i
< config
->cluster_num_changes
; ++i
)
1012 if ( cluster_changes
[i
].id
== sidtodel
&& cluster_changes
[i
].type
== C_CSESSION
)
1013 return 0; // Deleted session already before the new session.
1015 if ( cluster_changes
[i
].id
== sidnew
&& cluster_changes
[i
].type
== C_CSESSION
)
1022 for ( ; i
< config
->cluster_num_changes
; ++i
)
1024 if ( cluster_changes
[i
].id
== sidtodel
&& cluster_changes
[i
].type
== C_CSESSION
)
1027 cluster_changes
[i
].id
= sidnew
;
1028 cluster_changes
[inew
].id
= sidtodel
;
1036 // A particular session has been changed!
1037 int cluster_send_session(int sid
)
1039 if (!config
->cluster_iam_master
) {
1040 LOG(0, sid
, 0, "I'm not a master, but I just tried to change a session!\n");
1045 LOG(0, sid
, 0, "cluster_send_session called from child process!\n");
1049 return type_changed(C_CSESSION
, sid
);
1052 // A particular bundle has been changed!
1053 int cluster_send_bundle(int bid
)
1055 if (!config
->cluster_iam_master
) {
1056 LOG(0, 0, bid
, "I'm not a master, but I just tried to change a bundle!\n");
1060 return type_changed(C_CBUNDLE
, bid
);
1063 // A particular tunnel has been changed!
1064 int cluster_send_tunnel(int tid
)
1066 if (!config
->cluster_iam_master
) {
1067 LOG(0, 0, tid
, "I'm not a master, but I just tried to change a tunnel!\n");
1071 return type_changed(C_CTUNNEL
, tid
);
1076 // We're a master, and a slave has just told us that it's
1077 // missed a packet. We'll resend it every packet since
1078 // the last one it's seen.
1080 static int cluster_catchup_slave(int seq
, in_addr_t slave
)
1085 LOG(1, 0, 0, "Slave %s sent LASTSEEN with seq %d\n", fmtaddr(slave
, 0), seq
);
1086 if (!config
->cluster_iam_master
) {
1087 LOG(1, 0, 0, "Got LASTSEEN but I'm not a master! Redirecting it to %s.\n",
1088 fmtaddr(config
->cluster_master_address
, 0));
1090 peer_send_message(slave
, C_MASTER
, config
->cluster_master_address
, NULL
, 0);
1094 diff
= config
->cluster_seq_number
- seq
; // How many packet do we need to send?
1098 if (diff
>= HB_HISTORY_SIZE
) { // Ouch. We don't have the packet to send it!
1099 LOG(0, 0, 0, "A slave asked for message %d when our seq number is %d. Killing it.\n",
1100 seq
, config
->cluster_seq_number
);
1101 return peer_send_message(slave
, C_KILL
, seq
, NULL
, 0);// Kill the slave. Nothing else to do.
1104 LOG(1, 0, 0, "Sending %d catchup packets to slave %s\n", diff
, fmtaddr(slave
, 0) );
1106 // Now resend every packet that it missed, in order.
1107 while (seq
!= config
->cluster_seq_number
) {
1108 s
= seq
% HB_HISTORY_SIZE
;
1109 if (seq
!= past_hearts
[s
].seq
) {
1110 LOG(0, 0, 0, "Tried to re-send heartbeat for %s but %d doesn't match %d! (%d,%d)\n",
1111 fmtaddr(slave
, 0), seq
, past_hearts
[s
].seq
, s
, config
->cluster_seq_number
);
1112 return -1; // What to do here!?
1114 peer_send_data(slave
, past_hearts
[s
].data
, past_hearts
[s
].size
);
1115 seq
= (seq
+1)%HB_MAX_SEQ
; // Increment to next seq number.
1117 return 0; // All good!
1121 // We've heard from another peer! Add it to the list
1122 // that we select from at election time.
1124 static int cluster_add_peer(in_addr_t peer
, time_t basetime
, pingt
*pp
, int size
)
1127 in_addr_t clusterid
;
1130 // Allow for backward compatability.
1131 // Just the ping packet into a new structure to allow
1132 // for the possibility that we might have received
1133 // more or fewer elements than we were expecting.
1134 if (size
> sizeof(p
))
1137 memset( (void *) &p
, 0, sizeof(p
) );
1138 memcpy( (void *) &p
, (void *) pp
, size
);
1141 if (clusterid
!= config
->bind_address
)
1144 LOG(4, 0, 0, "Skipping ping from %s (different cluster)\n", fmtaddr(peer
, 0));
1148 for (i
= 0; i
< num_peers
; ++i
)
1150 if (peers
[i
].peer
!= peer
)
1153 // This peer already exists. Just update the timestamp.
1154 peers
[i
].basetime
= basetime
;
1155 peers
[i
].timestamp
= TIME
;
1156 peers
[i
].uptodate
= !p
.undef
;
1160 // Is this the master shutting down??
1161 if (peer
== config
->cluster_master_address
) {
1162 LOG(3, 0, 0, "Master %s %s\n", fmtaddr(config
->cluster_master_address
, 0),
1163 basetime
? "has restarted!" : "shutting down...");
1165 config
->cluster_master_address
= 0;
1166 config
->cluster_last_hb
= 0; // Force an election.
1167 cluster_check_master();
1172 LOG(4, 0, 0, "Adding %s as a peer\n", fmtaddr(peer
, 0));
1174 // Not found. Is there a stale slot to re-use?
1175 for (i
= 0; i
< num_peers
; ++i
)
1177 if (!peers
[i
].basetime
) // Shutdown
1180 if ((peers
[i
].timestamp
+ config
->cluster_hb_timeout
* 10) < TIME
) // Stale.
1184 if (i
>= CLUSTER_MAX_SIZE
)
1187 LOG(0, 0, 0, "Tried to add %s as a peer, but I already have %d of them!\n", fmtaddr(peer
, 0), i
);
1191 peers
[i
].peer
= peer
;
1192 peers
[i
].basetime
= basetime
;
1193 peers
[i
].timestamp
= TIME
;
1194 peers
[i
].uptodate
= !p
.undef
;
1198 LOG(1, 0, 0, "Added %s as a new peer. Now %d peers\n", fmtaddr(peer
, 0), num_peers
);
1204 // A slave responds with C_MASTER when it gets a message which should have gone to a master.
1205 static int cluster_set_master(in_addr_t peer
, in_addr_t master
)
1207 if (config
->cluster_iam_master
) // Sanity...
1210 LOG(3, 0, 0, "Peer %s set the master to %s...\n", fmtaddr(peer
, 0),
1211 fmtaddr(master
, 1));
1213 config
->cluster_master_address
= master
;
1216 // catchup with new master
1217 peer_send_message(master
, C_LASTSEEN
, config
->cluster_seq_number
, NULL
, 0);
1219 // delay next election
1220 config
->cluster_last_hb
= TIME
;
1223 // run election (or reset "probed" if master was set)
1224 cluster_check_master();
1228 /* Handle the slave updating the byte counters for the master. */
1230 // Note that we don't mark the session as dirty; We rely on
1231 // the slow table walk to propogate this back out to the slaves.
1233 static int cluster_handle_bytes(uint8_t *data
, int size
)
1237 b
= (bytest
*) data
;
1239 LOG(3, 0, 0, "Got byte counter update (size %d)\n", size
);
1241 /* Loop around, adding the byte
1242 counts to each of the sessions. */
1244 while (size
>= sizeof(*b
) ) {
1245 if (b
->sid
> MAXSESSION
) {
1246 LOG(0, 0, 0, "Got C_BYTES with session #%d!\n", b
->sid
);
1247 return -1; /* Abort processing */
1250 session
[b
->sid
].pin
+= b
->pin
;
1251 session
[b
->sid
].pout
+= b
->pout
;
1253 increment_counter(&session
[b
->sid
].cin
, &session
[b
->sid
].cin_wrap
, b
->cin
);
1254 increment_counter(&session
[b
->sid
].cout
, &session
[b
->sid
].cout_wrap
, b
->cout
);
1256 session
[b
->sid
].cin_delta
+= b
->cin
;
1257 session
[b
->sid
].cout_delta
+= b
->cout
;
1260 session
[b
->sid
].last_packet
= session
[b
->sid
].last_data
= time_now
;
1262 session
[b
->sid
].last_data
= time_now
;
1269 LOG(0, 0, 0, "Got C_BYTES with %d bytes of trailing junk!\n", size
);
1275 // Handle receiving a session structure in a heartbeat packet.
1277 static int cluster_recv_session(int more
, uint8_t *p
)
1279 if (more
>= MAXSESSION
) {
1280 LOG(0, 0, 0, "DANGER: Received a heartbeat session id > MAXSESSION!\n");
1284 if (session
[more
].tunnel
== T_UNDEF
) {
1285 if (config
->cluster_iam_uptodate
) { // Sanity.
1286 LOG(0, 0, 0, "I thought I was uptodate but I just found an undefined session!\n");
1288 --config
->cluster_undefined_sessions
;
1292 load_session(more
, (sessiont
*) p
); // Copy session into session table..
1294 LOG(5, more
, 0, "Received session update (%d undef)\n", config
->cluster_undefined_sessions
);
1296 if (!config
->cluster_iam_uptodate
)
1297 cluster_uptodate(); // Check to see if we're up to date.
1302 static int cluster_recv_bundle(int more
, uint8_t *p
)
1304 if (more
>= MAXBUNDLE
) {
1305 LOG(0, 0, 0, "DANGER: Received a bundle id > MAXBUNDLE!\n");
1309 if (bundle
[more
].state
== BUNDLEUNDEF
) {
1310 if (config
->cluster_iam_uptodate
) { // Sanity.
1311 LOG(0, 0, 0, "I thought I was uptodate but I just found an undefined bundle!\n");
1313 --config
->cluster_undefined_bundles
;
1317 memcpy(&bundle
[more
], p
, sizeof(bundle
[more
]) );
1319 LOG(5, 0, more
, "Received bundle update\n");
1321 if (!config
->cluster_iam_uptodate
)
1322 cluster_uptodate(); // Check to see if we're up to date.
1327 static int cluster_recv_tunnel(int more
, uint8_t *p
)
1329 if (more
>= MAXTUNNEL
) {
1330 LOG(0, 0, 0, "DANGER: Received a tunnel session id > MAXTUNNEL!\n");
1334 if (tunnel
[more
].state
== TUNNELUNDEF
) {
1335 if (config
->cluster_iam_uptodate
) { // Sanity.
1336 LOG(0, 0, 0, "I thought I was uptodate but I just found an undefined tunnel!\n");
1338 --config
->cluster_undefined_tunnels
;
1342 memcpy(&tunnel
[more
], p
, sizeof(tunnel
[more
]) );
1345 // Clear tunnel control messages. These are dynamically allocated.
1346 // If we get unlucky, this may cause the tunnel to drop!
1348 tunnel
[more
].controls
= tunnel
[more
].controle
= NULL
;
1349 tunnel
[more
].controlc
= 0;
1351 LOG(5, 0, more
, "Received tunnel update\n");
1353 if (!config
->cluster_iam_uptodate
)
1354 cluster_uptodate(); // Check to see if we're up to date.
1360 // pre v6 heartbeat session structure
1381 uint32_t cin_wrap
, cout_wrap
;
1382 uint32_t cin_delta
, cout_delta
;
1383 uint16_t throttle_in
;
1384 uint16_t throttle_out
;
1390 uint32_t session_timeout
;
1391 uint32_t idle_timeout
;
1394 in_addr_t dns1
, dns2
;
1395 routet route
[MAXROUTE
];
1398 int random_vector_length
;
1399 uint8_t random_vector
[MAXTEL
];
1401 char called
[MAXTEL
];
1402 char calling
[MAXTEL
];
1403 uint32_t tx_connect_speed
;
1404 uint32_t rx_connect_speed
;
1411 uint16_t snoop_port
;
1412 uint8_t walled_garden
;
1413 uint8_t ipv6prefixlen
;
1414 struct in6_addr ipv6route
;
1415 char reserved_3
[11];
1418 static uint8_t *convert_session(struct oldsession
*old
)
1420 static sessiont
new;
1423 memset(&new, 0, sizeof(new));
1425 new.next
= old
->next
;
1427 new.tunnel
= old
->tunnel
;
1428 new.flags
= old
->flags
;
1429 new.ppp
.phase
= old
->ppp
.phase
;
1430 new.ppp
.lcp
= old
->ppp
.lcp
;
1431 new.ppp
.ipcp
= old
->ppp
.ipcp
;
1432 new.ppp
.ipv6cp
= old
->ppp
.ipv6cp
;
1433 new.ppp
.ccp
= old
->ppp
.ccp
;
1435 new.ip_pool_index
= old
->ip_pool_index
;
1436 new.unique_id
= old
->unique_id
;
1437 new.magic
= old
->magic
;
1439 new.pout
= old
->pout
;
1441 new.cout
= old
->cout
;
1442 new.cin_wrap
= old
->cin_wrap
;
1443 new.cout_wrap
= old
->cout_wrap
;
1444 new.cin_delta
= old
->cin_delta
;
1445 new.cout_delta
= old
->cout_delta
;
1446 new.throttle_in
= old
->throttle_in
;
1447 new.throttle_out
= old
->throttle_out
;
1448 new.filter_in
= old
->filter_in
;
1449 new.filter_out
= old
->filter_out
;
1451 new.opened
= old
->opened
;
1453 new.session_timeout
= old
->session_timeout
;
1454 new.idle_timeout
= old
->idle_timeout
;
1455 new.last_packet
= old
->last_packet
;
1456 new.last_data
= old
->last_data
;
1457 new.dns1
= old
->dns1
;
1458 new.dns2
= old
->dns2
;
1459 new.tbf_in
= old
->tbf_in
;
1460 new.tbf_out
= old
->tbf_out
;
1461 new.random_vector_length
= old
->random_vector_length
;
1462 new.tx_connect_speed
= old
->tx_connect_speed
;
1463 new.rx_connect_speed
= old
->rx_connect_speed
;
1464 new.timeout
= old
->timeout
;
1465 new.mrru
= old
->mrru
;
1466 new.mssf
= old
->mssf
;
1467 new.epdis
= old
->epdis
;
1468 new.bundle
= old
->bundle
;
1469 new.snoop_ip
= old
->snoop_ip
;
1470 new.snoop_port
= old
->snoop_port
;
1471 new.walled_garden
= old
->walled_garden
;
1472 new.ipv6prefixlen
= old
->ipv6prefixlen
;
1473 new.ipv6route
= old
->ipv6route
;
1475 memcpy(new.random_vector
, old
->random_vector
, sizeof(new.random_vector
));
1476 memcpy(new.user
, old
->user
, sizeof(new.user
));
1477 memcpy(new.called
, old
->called
, sizeof(new.called
));
1478 memcpy(new.calling
, old
->calling
, sizeof(new.calling
));
1480 for (i
= 0; i
< MAXROUTE
; i
++)
1481 memcpy(&new.route
[i
], &old
->route
[i
], sizeof(new.route
[i
]));
1483 return (uint8_t *) &new;
1487 // Process a heartbeat..
1489 // v6: added RADIUS class attribute, re-ordered session structure
1490 // v7: added tunnelt attribute at the end of struct (tunnelt size change)
1491 static int cluster_process_heartbeat(uint8_t *data
, int size
, int more
, uint8_t *p
, in_addr_t addr
)
1494 int s
= size
- (p
-data
);
1500 # error "need to update cluster_process_heartbeat()"
1504 # error "need to update cluster_process_heartbeat()"
1509 // we handle versions 5 through 7
1510 if (hb_ver
< 5 || hb_ver
> HB_VERSION
) {
1511 LOG(0, 0, 0, "Received a heartbeat version that I don't support (%d)!\n", hb_ver
);
1512 return -1; // Ignore it??
1515 if (size
> sizeof(past_hearts
[0].data
)) {
1516 LOG(0, 0, 0, "Received an oversize heartbeat from %s (%d)!\n", fmtaddr(addr
, 0), size
);
1527 if (h
->clusterid
!= config
->bind_address
)
1528 return -1; // It's not part of our cluster.
1530 if (config
->cluster_iam_master
) { // Sanity...
1531 // Note that this MUST match the election process above!
1533 LOG(0, 0, 0, "I just got a heartbeat from master %s, but _I_ am the master!\n", fmtaddr(addr
, 0));
1535 LOG(0, 0, 0, "Heartbeat with zero basetime! Ignoring\n");
1536 return -1; // Skip it.
1539 if (h
->table_version
> config
->cluster_table_version
) {
1540 LOG(0, 0, 0, "They've seen more state changes (%" PRIu64
" vs my %" PRIu64
") so I'm gone!\n",
1541 h
->table_version
, config
->cluster_table_version
);
1547 if (h
->table_version
< config
->cluster_table_version
)
1550 if (basetime
> h
->basetime
) {
1551 LOG(0, 0, 0, "They're an older master than me so I'm gone!\n");
1556 if (basetime
< h
->basetime
)
1559 if (my_address
< addr
) { // Tie breaker.
1560 LOG(0, 0, 0, "They're a higher IP address than me, so I'm gone!\n");
1566 // Send it a unicast heartbeat to see give it a chance to die.
1567 // NOTE: It's actually safe to do seq-number - 1 without checking
1570 cluster_catchup_slave(config
->cluster_seq_number
- 1, addr
);
1572 return -1; // Skip it.
1576 // Try and guard against a stray master appearing.
1578 // Ignore heartbeats received from another master before the
1579 // timeout (less a smidgen) for the old master has elapsed.
1581 // Note that after a clean failover, the cluster_master_address
1582 // is cleared, so this doesn't run.
1584 if (config
->cluster_master_address
&& addr
!= config
->cluster_master_address
) {
1585 LOG(0, 0, 0, "Ignoring stray heartbeat from %s, current master %s has not yet timed out (last heartbeat %.1f seconds ago).\n",
1586 fmtaddr(addr
, 0), fmtaddr(config
->cluster_master_address
, 1),
1587 0.1 * (TIME
- config
->cluster_last_hb
));
1588 return -1; // ignore
1591 if (config
->cluster_seq_number
== -1) // Don't have one. Just align to the master...
1592 config
->cluster_seq_number
= h
->seq
;
1594 config
->cluster_last_hb
= TIME
; // Reset to ensure that we don't become master!!
1595 config
->cluster_last_hb_ver
= hb_ver
; // remember what cluster version the master is using
1597 if (config
->cluster_seq_number
!= h
->seq
) { // Out of sequence heartbeat!
1598 static int lastseen_seq
= 0;
1599 static time_t lastseen_time
= 0;
1601 // limit to once per second for a particular seq#
1602 int ask
= (config
->cluster_seq_number
!= lastseen_seq
|| time_now
!= lastseen_time
);
1604 LOG(1, 0, 0, "HB: Got seq# %d but was expecting %d. %s.\n",
1605 h
->seq
, config
->cluster_seq_number
,
1606 ask
? "Asking for resend" : "Ignoring");
1610 lastseen_seq
= config
->cluster_seq_number
;
1611 lastseen_time
= time_now
;
1612 peer_send_message(addr
, C_LASTSEEN
, config
->cluster_seq_number
, NULL
, 0);
1615 config
->cluster_last_hb
= TIME
; // Reset to ensure that we don't become master!!
1617 // Just drop the packet. The master will resend it as part of the catchup.
1621 // Save the packet in our buffer.
1622 // This is needed in case we become the master.
1623 config
->cluster_seq_number
= (h
->seq
+1)%HB_MAX_SEQ
;
1624 i
= h
->seq
% HB_HISTORY_SIZE
;
1625 past_hearts
[i
].seq
= h
->seq
;
1626 past_hearts
[i
].size
= size
;
1627 memcpy(&past_hearts
[i
].data
, data
, size
); // Save it.
1630 // Check that we don't have too many undefined sessions, and
1631 // that the free session pointer is correct.
1632 cluster_check_sessions(h
->highsession
, h
->freesession
, h
->highbundle
, h
->hightunnel
);
1634 if (h
->interval
!= config
->cluster_hb_interval
)
1636 LOG(2, 0, 0, "Master set ping/heartbeat interval to %u (was %u)\n",
1637 h
->interval
, config
->cluster_hb_interval
);
1639 config
->cluster_hb_interval
= h
->interval
;
1642 if (h
->timeout
!= config
->cluster_hb_timeout
)
1644 LOG(2, 0, 0, "Master set heartbeat timeout to %u (was %u)\n",
1645 h
->timeout
, config
->cluster_hb_timeout
);
1647 config
->cluster_hb_timeout
= h
->timeout
;
1650 // Ok. process the packet...
1653 type
= *((uint32_t *) p
);
1654 p
+= sizeof(uint32_t);
1655 s
-= sizeof(uint32_t);
1657 more
= *((uint32_t *) p
);
1658 p
+= sizeof(uint32_t);
1659 s
-= sizeof(uint32_t);
1662 case C_CSESSION
: { // Compressed session structure.
1663 uint8_t c
[ sizeof(sessiont
) + 2];
1665 uint8_t *orig_p
= p
;
1667 size
= rle_decompress((uint8_t **) &p
, s
, c
, sizeof(c
) );
1670 // session struct changed with v5
1673 if (size
!= sizeof(struct oldsession
)) {
1674 LOG(0, 0, 0, "DANGER: Received a v%d CSESSION that didn't decompress correctly!\n", hb_ver
);
1675 // Now what? Should exit! No-longer up to date!
1678 cluster_recv_session(more
, convert_session((struct oldsession
*) c
));
1682 if (size
!= sizeof(sessiont
) ) { // Ouch! Very very bad!
1683 LOG(0, 0, 0, "DANGER: Received a CSESSION that didn't decompress correctly!\n");
1684 // Now what? Should exit! No-longer up to date!
1688 cluster_recv_session(more
, c
);
1694 if (s
< sizeof(struct oldsession
))
1697 cluster_recv_session(more
, convert_session((struct oldsession
*) p
));
1699 p
+= sizeof(struct oldsession
);
1700 s
-= sizeof(struct oldsession
);
1704 if ( s
< sizeof(session
[more
]))
1707 cluster_recv_session(more
, p
);
1709 p
+= sizeof(session
[more
]);
1710 s
-= sizeof(session
[more
]);
1713 case C_CTUNNEL
: { // Compressed tunnel structure.
1714 uint8_t c
[ sizeof(tunnelt
) + 2];
1716 uint8_t *orig_p
= p
;
1718 size
= rle_decompress((uint8_t **) &p
, s
, c
, sizeof(c
));
1722 if ( ((hb_ver
>= HB_VERSION
) && (size
!= sizeof(tunnelt
))) ||
1723 ((hb_ver
< HB_VERSION
) && (size
> sizeof(tunnelt
))) )
1725 if (size
!= sizeof(tunnelt
) )
1727 { // Ouch! Very very bad!
1728 LOG(0, 0, 0, "DANGER: Received a CTUNNEL that didn't decompress correctly!\n");
1729 // Now what? Should exit! No-longer up to date!
1733 cluster_recv_tunnel(more
, c
);
1738 if ( s
< sizeof(tunnel
[more
]))
1741 cluster_recv_tunnel(more
, p
);
1743 p
+= sizeof(tunnel
[more
]);
1744 s
-= sizeof(tunnel
[more
]);
1747 case C_CBUNDLE
: { // Compressed bundle structure.
1748 uint8_t c
[ sizeof(bundlet
) + 2];
1750 uint8_t *orig_p
= p
;
1752 size
= rle_decompress((uint8_t **) &p
, s
, c
, sizeof(c
));
1755 if (size
!= sizeof(bundlet
) ) { // Ouch! Very very bad!
1756 LOG(0, 0, 0, "DANGER: Received a CBUNDLE that didn't decompress correctly!\n");
1757 // Now what? Should exit! No-longer up to date!
1761 cluster_recv_bundle(more
, c
);
1766 if ( s
< sizeof(bundle
[more
]))
1769 cluster_recv_bundle(more
, p
);
1771 p
+= sizeof(bundle
[more
]);
1772 s
-= sizeof(bundle
[more
]);
1775 LOG(0, 0, 0, "DANGER: I received a heartbeat element where I didn't understand the type! (%d)\n", type
);
1776 return -1; // can't process any more of the packet!!
1780 if (config
->cluster_master_address
!= addr
)
1782 LOG(0, 0, 0, "My master just changed from %s to %s!\n",
1783 fmtaddr(config
->cluster_master_address
, 0), fmtaddr(addr
, 1));
1785 config
->cluster_master_address
= addr
;
1788 config
->cluster_last_hb
= TIME
; // Successfully received a heartbeat!
1789 config
->cluster_table_version
= h
->table_version
;
1793 LOG(0, 0, 0, "I got an incomplete heartbeat packet! This means I'm probably out of sync!!\n");
1798 // We got a packet on the cluster port!
1799 // Handle pings, lastseens, and heartbeats!
1801 int processcluster(uint8_t *data
, int size
, in_addr_t addr
)
1807 if (addr
== my_address
)
1808 return -1; // Ignore it. Something looped back the multicast!
1810 LOG(5, 0, 0, "Process cluster: %d bytes from %s\n", size
, fmtaddr(addr
, 0));
1812 if (s
<= 0) // Any data there??
1818 type
= *((uint32_t *) p
);
1819 p
+= sizeof(uint32_t);
1820 s
-= sizeof(uint32_t);
1822 more
= *((uint32_t *) p
);
1823 p
+= sizeof(uint32_t);
1824 s
-= sizeof(uint32_t);
1828 case C_PING
: // Update the peers table.
1829 return cluster_add_peer(addr
, more
, (pingt
*) p
, s
);
1831 case C_MASTER
: // Our master is wrong
1832 return cluster_set_master(addr
, more
);
1834 case C_LASTSEEN
: // Catch up a slave (slave missed a packet).
1835 return cluster_catchup_slave(more
, addr
);
1837 case C_FORWARD
: // Forwarded control packet. pass off to processudp.
1838 case C_FORWARD_DAE
: // Forwarded DAE packet. pass off to processdae.
1839 if (!config
->cluster_iam_master
)
1841 LOG(0, 0, 0, "I'm not the master, but I got a C_FORWARD%s from %s?\n",
1842 type
== C_FORWARD_DAE
? "_DAE" : "", fmtaddr(addr
, 0));
1848 struct sockaddr_in a
;
1849 a
.sin_addr
.s_addr
= more
;
1851 a
.sin_port
= *(int *) p
;
1855 LOG(4, 0, 0, "Got a forwarded %spacket... (%s:%d)\n",
1856 type
== C_FORWARD_DAE
? "DAE " : "", fmtaddr(more
, 0), a
.sin_port
);
1859 if (type
== C_FORWARD_DAE
)
1861 struct in_addr local
;
1862 local
.s_addr
= config
->bind_address
? config
->bind_address
: my_address
;
1863 processdae(p
, s
, &a
, sizeof(a
), &local
);
1866 processudp(p
, s
, &a
);
1871 case C_MPPP_FORWARD
:
1872 // Receive a MPPP packet from a slave.
1873 if (!config
->cluster_iam_master
) {
1874 LOG(0, 0, 0, "I'm not the master, but I got a C_MPPP_FORWARD from %s?\n", fmtaddr(addr
, 0));
1881 case C_THROTTLE
: { // Receive a forwarded packet from a slave.
1882 if (!config
->cluster_iam_master
) {
1883 LOG(0, 0, 0, "I'm not the master, but I got a C_THROTTLE from %s?\n", fmtaddr(addr
, 0));
1887 tbf_queue_packet(more
, p
, s
); // The TBF id tells wether it goes in or out.
1891 // Receive a walled garden packet from a slave.
1892 if (!config
->cluster_iam_master
) {
1893 LOG(0, 0, 0, "I'm not the master, but I got a C_GARDEN from %s?\n", fmtaddr(addr
, 0));
1901 if (!config
->cluster_iam_master
) {
1902 LOG(0, 0, 0, "I'm not the master, but I got a C_BYTES from %s?\n", fmtaddr(addr
, 0));
1906 return cluster_handle_bytes(p
, s
);
1908 case C_KILL
: // The master asked us to die!? (usually because we're too out of date).
1909 if (config
->cluster_iam_master
) {
1910 LOG(0, 0, 0, "_I_ am master, but I received a C_KILL from %s! (Seq# %d)\n", fmtaddr(addr
, 0), more
);
1913 if (more
!= config
->cluster_seq_number
) {
1914 LOG(0, 0, 0, "The master asked us to die but the seq number didn't match!?\n");
1918 if (addr
!= config
->cluster_master_address
) {
1919 LOG(0, 0, 0, "Received a C_KILL from %s which doesn't match config->cluster_master_address (%s)\n",
1920 fmtaddr(addr
, 0), fmtaddr(config
->cluster_master_address
, 1));
1921 // We can only warn about it. The master might really have switched!
1924 LOG(0, 0, 0, "Received a valid C_KILL: I'm going to die now.\n");
1926 exit(0); // Lets be paranoid;
1927 return -1; // Just signalling the compiler.
1930 LOG(4, 0, 0, "Got a heartbeat from %s\n", fmtaddr(addr
, 0));
1931 return cluster_process_heartbeat(data
, size
, more
, p
, addr
);
1934 LOG(0, 0, 0, "Strange type packet received on cluster socket (%d)\n", type
);
1940 LOG(0, 0, 0, "I got a _short_ cluster heartbeat packet! This means I'm probably out of sync!!\n");
1944 //====================================================================================================
1946 int cmd_show_cluster(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1950 if (CLI_HELP_REQUESTED
)
1951 return CLI_HELP_NO_ARGS
;
1953 cli_print(cli
, "Cluster status : %s", config
->cluster_iam_master
? "Master" : "Slave" );
1954 cli_print(cli
, "My address : %s", fmtaddr(my_address
, 0));
1955 cli_print(cli
, "VIP address : %s", fmtaddr(config
->bind_address
, 0));
1956 cli_print(cli
, "Multicast address: %s", fmtaddr(config
->cluster_address
, 0));
1957 cli_print(cli
, "Multicast i'face : %s", config
->cluster_interface
);
1959 if (!config
->cluster_iam_master
) {
1960 cli_print(cli
, "My master : %s (last heartbeat %.1f seconds old)",
1961 config
->cluster_master_address
1962 ? fmtaddr(config
->cluster_master_address
, 0)
1964 0.1 * (TIME
- config
->cluster_last_hb
));
1965 cli_print(cli
, "Uptodate : %s", config
->cluster_iam_uptodate
? "Yes" : "No");
1966 cli_print(cli
, "Table version # : %" PRIu64
, config
->cluster_table_version
);
1967 cli_print(cli
, "Next sequence number expected: %d", config
->cluster_seq_number
);
1968 cli_print(cli
, "%d sessions undefined of %d", config
->cluster_undefined_sessions
, config
->cluster_highest_sessionid
);
1969 cli_print(cli
, "%d bundles undefined of %d", config
->cluster_undefined_bundles
, config
->cluster_highest_bundleid
);
1970 cli_print(cli
, "%d tunnels undefined of %d", config
->cluster_undefined_tunnels
, config
->cluster_highest_tunnelid
);
1972 cli_print(cli
, "Table version # : %" PRIu64
, config
->cluster_table_version
);
1973 cli_print(cli
, "Next heartbeat # : %d", config
->cluster_seq_number
);
1974 cli_print(cli
, "Highest session : %d", config
->cluster_highest_sessionid
);
1975 cli_print(cli
, "Highest bundle : %d", config
->cluster_highest_bundleid
);
1976 cli_print(cli
, "Highest tunnel : %d", config
->cluster_highest_tunnelid
);
1977 cli_print(cli
, "%d changes queued for sending", config
->cluster_num_changes
);
1979 cli_print(cli
, "%d peers.", num_peers
);
1982 cli_print(cli
, "%20s %10s %8s", "Address", "Basetime", "Age");
1983 for (i
= 0; i
< num_peers
; ++i
) {
1984 cli_print(cli
, "%20s %10u %8d", fmtaddr(peers
[i
].peer
, 0),
1985 peers
[i
].basetime
, TIME
- peers
[i
].timestamp
);
1991 // Simple run-length-encoding compression.
1993 // 1 byte < 128 = count of non-zero bytes following. // Not legal to be zero.
1994 // n non-zero bytes;
1996 // 1 byte > 128 = (count - 128) run of zero bytes. //
1998 // count == 0 indicates end of compressed stream.
2000 // Compress from 'src' into 'dst'. return number of bytes
2002 // Updates *src_p to indicate 1 past last bytes used.
2004 // We could get an extra byte in the zero runs by storing (count-1)
2005 // but I'm playing it safe.
2007 // Worst case is a 50% expansion in space required (trying to
2008 // compress { 0x00, 0x01 } * N )
2009 static int rle_compress(uint8_t **src_p
, int ssize
, uint8_t *dst
, int dsize
)
2012 int orig_dsize
= dsize
;
2016 while (ssize
> 0 && dsize
> 2) {
2018 x
= dst
++; --dsize
; // Reserve space for count byte..
2020 if (*src
) { // Copy a run of non-zero bytes.
2021 while (*src
&& count
< 127 && ssize
> 0 && dsize
> 1) { // Count number of non-zero bytes.
2026 *x
= count
; // Store number of non-zero bytes. Guarenteed to be non-zero!
2028 } else { // Compress a run of zero bytes.
2029 while (*src
== 0 && count
< 127 && ssize
> 0) {
2038 *dst
++ = 0x0; // Add Stop byte.
2042 return (orig_dsize
- dsize
);
2046 // Decompress the buffer into **p.
2047 // 'psize' is the size of the decompression buffer available.
2049 // Returns the number of bytes decompressed.
2051 // Decompresses from '*src_p' into 'dst'.
2052 // Return the number of dst bytes used.
2053 // Updates the 'src_p' pointer to point to the
2054 // first un-used byte.
2055 static int rle_decompress(uint8_t **src_p
, int ssize
, uint8_t *dst
, int dsize
)
2058 int orig_dsize
= dsize
;
2059 uint8_t *src
= *src_p
;
2061 while (ssize
>0 && dsize
> 0) { // While there's more to decompress, and there's room in the decompress buffer...
2062 count
= *src
++; --ssize
; // get the count byte from the source.
2063 if (count
== 0x0) // End marker reached? If so, finish.
2066 if (count
& 0x80) { // Decompress a run of zeros
2067 for (count
&= 0x7f ; count
> 0 && dsize
> 0; --count
) {
2071 } else { // Copy run of non-zero bytes.
2072 for ( ; count
> 0 && ssize
&& dsize
; --count
) { // Copy non-zero bytes across.
2079 return (orig_dsize
- dsize
);