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