roll in Michael's "limp along" fix for when a slave drops temporarily from the mcast...
[l2tpns.git] / cluster.c
1 // L2TPNS Clustering Stuff
2
3 char const *cvs_id_cluster = "$Id: cluster.c,v 1.6 2004/07/05 06:54:01 bodea Exp $";
4
5 #include <stdio.h>
6 #include <sys/file.h>
7 #include <sys/stat.h>
8 #include <sys/socket.h>
9 #include <netinet/in.h>
10 #include <arpa/inet.h>
11 #include <sys/ioctl.h>
12 #include <net/if.h>
13 #include <string.h>
14 #include <malloc.h>
15 #include <errno.h>
16 #include <stdlib.h>
17 #include <stdarg.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <libcli.h>
21
22 #include "l2tpns.h"
23 #include "cluster.h"
24 #include "util.h"
25 #include "tbf.h"
26
27 #ifdef BGP
28 #include "bgp.h"
29 #endif
30 /*
31 * All cluster packets have the same format.
32 *
33 * One or more instances of
34 * a 32 bit 'type' id.
35 * a 32 bit 'extra' data dependant on the 'type'.
36 * zero or more bytes of structure data, dependant on the type.
37 *
38 */
39
40 // Module variables.
41 int cluster_sockfd = 0; // The filedescriptor for the cluster communications port.
42
43 ipt my_address = 0; // The network address of my ethernet port.
44 static int walk_session_number = 0; // The next session to send when doing the slow table walk.
45 static int walk_tunnel_number = 0; // The next tunnel to send when doing the slow table walk.
46
47 static int hsess, fsess; // Saved copies of the highest used session id, and the first free one.
48
49 #define MAX_HEART_SIZE (8192) // Maximum size of heartbeat packet. Must be less than max IP packet size :)
50 #define MAX_CHANGES (MAX_HEART_SIZE/(sizeof(sessiont) + sizeof(int) ) - 2) // Assumes a session is the biggest type!
51
52 static struct {
53 int type;
54 int id;
55 } cluster_changes[MAX_CHANGES]; // Queue of changed structures that need to go out when next heartbeat.
56
57 static struct {
58 int seq;
59 int size;
60 char data[MAX_HEART_SIZE];
61 } past_hearts[HB_HISTORY_SIZE]; // Ring buffer of heartbeats that we've recently sent out. Needed so
62 // we can re-transmit if needed.
63
64 static struct {
65 u32 peer;
66 time_t basetime;
67 clockt timestamp;
68 int uptodate;
69 } peers[CLUSTER_MAX_SIZE]; // List of all the peers we've heard from.
70 static int num_peers; // Number of peers in list.
71 static int have_peers; // At least one peer
72
73 int rle_decompress(u8 ** src_p, int ssize, u8 *dst, int dsize);
74 int rle_compress(u8 ** src_p, int ssize, u8 *dst, int dsize);
75
76 //
77 // Create a listening socket
78 //
79 // This joins the cluster multi-cast group.
80 //
81 int cluster_init()
82 {
83 struct sockaddr_in addr;
84 struct sockaddr_in interface_addr;
85 struct ip_mreq mreq;
86 struct ifreq ifr;
87 int opt = 0;
88
89 config->cluster_undefined_sessions = MAXSESSION-1;
90 config->cluster_undefined_tunnels = MAXTUNNEL-1;
91
92 if (!config->cluster_address)
93 return 0;
94 if (!*config->cluster_interface)
95 return 0;
96
97 cluster_sockfd = socket(AF_INET, SOCK_DGRAM, UDP);
98
99 memset(&addr, 0, sizeof(addr));
100 addr.sin_family = AF_INET;
101 addr.sin_port = htons(CLUSTERPORT);
102 addr.sin_addr.s_addr = INADDR_ANY;
103 setsockopt(cluster_sockfd, SOL_SOCKET, SO_REUSEADDR, &addr, sizeof(addr));
104
105 if (bind(cluster_sockfd, (void *) &addr, sizeof(addr)) < 0)
106 {
107 log(0, 0, 0, 0, "Failed to bind cluster socket: %s\n", strerror(errno));
108 return -1;
109 }
110
111 strcpy(ifr.ifr_name, config->cluster_interface);
112 if (ioctl(cluster_sockfd, SIOCGIFADDR, &ifr) < 0) {
113 log(0, 0, 0, 0, "Failed to get interface address for (%s): %s\n", config->cluster_interface, strerror(errno));
114 return -1;
115 }
116
117 memcpy(&interface_addr, &ifr.ifr_addr, sizeof(interface_addr) );
118 my_address = interface_addr.sin_addr.s_addr;
119
120 // Join multicast group.
121 mreq.imr_multiaddr.s_addr = config->cluster_address;
122 mreq.imr_interface = interface_addr.sin_addr;
123
124
125 opt = 0; // Turn off multicast loopback.
126 setsockopt(cluster_sockfd, IPPROTO_IP, IP_MULTICAST_LOOP, &opt, sizeof(opt));
127
128 if (setsockopt(cluster_sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) < 0) {
129 log(0, 0, 0, 0, "Failed to setsockopt (join mcast group): %s\n", strerror(errno));
130 return -1;
131 }
132
133 if (setsockopt (cluster_sockfd, IPPROTO_IP, IP_MULTICAST_IF, &interface_addr, sizeof(interface_addr)) < 0) {
134 log(0, 0, 0, 0, "Failed to setsockopt (set mcast interface): %s\n", strerror(errno));
135 return -1;
136 }
137
138 config->cluster_last_hb = TIME;
139 config->cluster_seq_number = -1;
140
141 return cluster_sockfd;
142 }
143
144
145 //
146 // Send a chunk of data to the entire cluster (usually via the multicast
147 // address ).
148 //
149
150 int cluster_send_data(void *data, int datalen)
151 {
152 struct sockaddr_in addr = {0};
153
154 if (!cluster_sockfd) return -1;
155 if (!config->cluster_address) return 0;
156
157 addr.sin_addr.s_addr = config->cluster_address;
158 addr.sin_port = htons(CLUSTERPORT);
159 addr.sin_family = AF_INET;
160
161 // log_hex(4, "Cluster send", data, datalen); // VERY big data packets. How about we don't..
162
163 log(5,0,0,0, "Cluster send data: %d bytes\n", datalen);
164
165 if (sendto(cluster_sockfd, data, datalen, MSG_NOSIGNAL, (void *) &addr, sizeof(addr)) < 0)
166 {
167 log(0, 0, 0, 0, "sendto: %s\n", strerror(errno));
168 return -1;
169 }
170
171 return 0;
172 }
173
174 //
175 // Add a chunk of data to a heartbeat packet.
176 // Maintains the format. Assumes that the caller
177 // has passed in a big enough buffer!
178 //
179 static void add_type(char ** p, int type, int more, char * data, int size)
180 {
181 * ( (u32*)(*p) ) = type;
182 *p += sizeof(u32);
183
184 * ( (u32*)(*p) ) = more;
185 *p += sizeof(u32);
186
187 if (data && size > 0) {
188 memcpy(*p, data, size);
189 (*p) += size;
190 }
191 }
192
193 void cluster_uptodate(void)
194 {
195 if (config->cluster_iam_uptodate)
196 return;
197
198 if (config->cluster_undefined_sessions || config->cluster_undefined_tunnels)
199 return;
200
201 config->cluster_iam_uptodate = 1;
202
203 log(0,0,0,0, "Now uptodate with master.\n");
204
205 // If we're not a master, or if we have no slaves
206 // then start taking traffic..
207 if (!config->cluster_iam_master || !have_peers)
208 {
209 #ifdef BGP
210 if (bgp_configured)
211 bgp_enable_routing(1);
212 else
213 #endif /* BGP */
214 if (config->send_garp)
215 send_garp(config->bind_address); // Start taking traffic.
216 }
217 }
218
219 //
220 // Send a unicast UDP packet to a peer with 'data' as the
221 // contents.
222 //
223 int peer_send_data(u32 peer, char * data, int size)
224 {
225 struct sockaddr_in addr = {0};
226
227 if (!cluster_sockfd) return -1;
228 if (!config->cluster_address) return 0;
229
230 if (!peer) // Odd??
231 return -1;
232
233 addr.sin_addr.s_addr = peer;
234 addr.sin_port = htons(CLUSTERPORT);
235 addr.sin_family = AF_INET;
236
237 log_hex(5, "Peer send", data, size);
238
239 if (sendto(cluster_sockfd, data, size, MSG_NOSIGNAL, (void *) &addr, sizeof(addr)) < 0)
240 {
241 log(0, 0, 0, 0, "sendto: %s\n", strerror(errno));
242 return -1;
243 }
244
245 return 0;
246 }
247
248 //
249 // Send a structured message to a peer with a single element of type 'type'.
250 //
251 int peer_send_message(u32 peer, int type, int more, char * data, int size)
252 {
253 char buf[65536]; // Vast overkill.
254 char * p = buf;
255
256 log(4,0,0,0, "Sending message to peer (type %d, more %d, size %d)\n", type, more, size);
257 add_type(&p, type, more, data, size);
258
259 return peer_send_data(peer, buf, (p-buf) );
260 }
261
262 //
263 // Forward a state changing packet to the master.
264 //
265 // The master just processes the payload as if it had
266 // received it off the tap device.
267 //
268 int master_forward_packet(char * data, int size, u32 addr, int port)
269 {
270 char buf[65536]; // Vast overkill.
271 char * p = buf;
272
273 if (!config->cluster_master_address) // No election has been held yet. Just skip it.
274 return -1;
275
276 log(4,0,0,0, "Forwarding packet from %s to master (size %d)\n", inet_toa(addr), size);
277
278 STAT(c_forwarded);
279 add_type(&p, C_FORWARD, addr, (char*) &port, sizeof(port) );
280 memcpy(p, data, size);
281 p += size;
282
283 return peer_send_data(config->cluster_master_address, buf, (p-buf) );
284
285 }
286
287 //
288 // Forward a throttled packet to the master for handling.
289 //
290 // The master just drops the packet into the appropriate
291 // token bucket queue, and lets normal processing take care
292 // of it.
293 //
294 int master_throttle_packet(int tbfid, char * data, int size)
295 {
296 char buf[65536]; // Vast overkill.
297 char * p = buf;
298
299 if (!config->cluster_master_address) // No election has been held yet. Just skip it.
300 return -1;
301
302 log(4,0,0,0, "Throttling packet master (size %d, tbfid %d)\n", size, tbfid);
303
304 add_type(&p, C_THROTTLE, tbfid, data, size);
305
306 return peer_send_data(config->cluster_master_address, buf, (p-buf) );
307
308 }
309
310 //
311 // Forward a walled garden packet to the master for handling.
312 //
313 // The master just writes the packet straight to the tun
314 // device (where is will normally loop through the
315 // firewall rules, and come back in on the tun device)
316 //
317 // (Note that this must be called with the tun header
318 // as the start of the data).
319 int master_garden_packet(sessionidt s, char *data, int size)
320 {
321 char buf[65536]; // Vast overkill.
322 char *p = buf;
323
324 if (!config->cluster_master_address) // No election has been held yet. Just skip it.
325 return -1;
326
327 log(4,0,0,0, "Walled garden packet to master (size %d)\n", size);
328
329 add_type(&p, C_GARDEN, s, data, size);
330
331 return peer_send_data(config->cluster_master_address, buf, (p-buf));
332
333 }
334
335 //
336 // Send a chunk of data as a heartbeat..
337 // We save it in the history buffer as we do so.
338 //
339 static void send_heartbeat(int seq, char * data, int size)
340 {
341 int i;
342
343 if (size > sizeof(past_hearts[0].data)) {
344 log(0,0,0,0, "Tried to heartbeat something larger than the maximum packet!\n");
345 kill(0, SIGTERM);
346 exit(1);
347 }
348 i = seq % HB_HISTORY_SIZE;
349 past_hearts[i].seq = seq;
350 past_hearts[i].size = size;
351 memcpy(&past_hearts[i].data, data, size); // Save it.
352 cluster_send_data(data, size);
353 }
354
355 //
356 // Send an 'i am alive' message to every machine in the cluster.
357 //
358 void cluster_send_ping(time_t basetime)
359 {
360 char buff[100 + sizeof(pingt)];
361 char *p = buff;
362 pingt x;
363
364 if (config->cluster_iam_master && basetime) // We're heartbeating so no need to ping.
365 return;
366
367 log(5,0,0,0, "Sending cluster ping...\n");
368
369 x.ver = 1;
370 x.addr = config->bind_address;
371 x.undef = config->cluster_undefined_sessions + config->cluster_undefined_tunnels;
372 x.basetime = basetime;
373
374 add_type(&p, C_PING, basetime, (char *) &x, sizeof(x));
375 cluster_send_data(buff, (p-buff) );
376 }
377
378 //
379 // Walk the session counters looking for non-zero ones to send
380 // to the master. We send up to 100 of them at one time.
381 // We examine a maximum of 2000 sessions.
382 // (50k max session should mean that we normally
383 // examine the entire session table every 25 seconds).
384
385 #define MAX_B_RECS (400)
386 void master_update_counts(void)
387 {
388 int i, c;
389 bytest b[MAX_B_RECS+1];
390
391 if (config->cluster_iam_master) // Only happens on the slaves.
392 return;
393
394 if (!config->cluster_master_address) // If we don't have a master, skip it for a while.
395 return;
396
397 i = MAX_B_RECS * 5; // Examine max 2000 sessions;
398 if (config->cluster_highest_sessionid > i)
399 i = config->cluster_highest_sessionid;
400
401 for ( c = 0; i > 0 ; --i) {
402 // Next session to look at.
403 walk_session_number++;
404 if ( walk_session_number > config->cluster_highest_sessionid)
405 walk_session_number = 1;
406
407 if (!sess_count[walk_session_number].cin && !sess_count[walk_session_number].cout)
408 continue; // Unused. Skip it.
409
410 b[c].sid = walk_session_number;
411 b[c].in = sess_count[walk_session_number].cin;
412 b[c].out = sess_count[walk_session_number].cout;
413
414 if (++c > MAX_B_RECS) // Send a max of 400 elements in a packet.
415 break;
416
417 // Reset counters.
418 sess_count[walk_session_number].cin = sess_count[walk_session_number].cout = 0;
419 }
420
421 if (!c) // Didn't find any that changes. Get out of here!
422 return;
423
424
425 // Forward the data to the master.
426 log(4,0,0,0, "Sending byte counters to master (%d elements)\n", c);
427 peer_send_message(config->cluster_master_address, C_BYTES, c, (char*) &b, sizeof(b[0]) * c);
428 return;
429 }
430
431 //
432 // Check that we have a master. If it's been too
433 // long since we heard from a master then hold an election.
434 //
435 void cluster_check_master(void)
436 {
437 int i, count, tcount, high_sid = 0;
438 int last_free = 0;
439 int had_peers = have_peers;
440 clockt t = TIME;
441 static int probed = 0;
442
443 // Is the master late? If so, try probing it...
444 if (TIME > (config->cluster_last_hb + config->cluster_hb_timeout/8 + 11)) {
445 if (!probed) {
446 if (config->cluster_master_address) {
447 peer_send_message(config->cluster_master_address,
448 C_LASTSEEN, config->cluster_seq_number, NULL, 0);
449 probed = 1;
450 }
451 }
452 } else { // We got a recent heartbeat; reset the probe flag.
453 probed = 0;
454 }
455
456 if (TIME < (config->cluster_last_hb + config->cluster_hb_timeout) )
457 return; // Everything's ok. return.
458
459 if (!config->cluster_iam_master)
460 log(0,0,0,0, "Master timed out! Holding election...\n");
461
462 config->cluster_last_hb = TIME + 1;
463
464 for (i = have_peers = 0; i < num_peers ; ++i) {
465 if ((peers[i].timestamp + config->cluster_hb_timeout) < t)
466 continue; // Stale peer! Skip them.
467
468 if (!peers[i].basetime)
469 continue; // Shutdown peer! Skip them.
470
471 have_peers = 1;
472 if (peers[i].basetime < basetime) {
473 log(1,0,0,0, "Expecting %s to become master\n", inet_toa(peers[i].peer) );
474 return; // They'll win the election. Get out of here.
475 }
476
477 if (peers[i].basetime == basetime &&
478 peers[i].peer > my_address) {
479 log(1,0,0,0, "Expecting %s to become master\n", inet_toa(peers[i].peer) );
480 return; // They'll win the election. Wait for them to come up.
481 }
482 }
483
484 if (config->cluster_iam_master) // If we're the master, we've already won
485 {
486 #ifdef BGP
487 // master lost all slaves, need to handle traffic ourself
488 if (bgp_configured && had_peers && !have_peers)
489 bgp_enable_routing(1);
490 #endif /* BGP */
491 return;
492 }
493
494 // Wow. it's been ages since I last heard a heartbeat
495 // and I'm better than an of my peers so it's time
496 // to become a master!!!
497
498 config->cluster_iam_master = 1;
499 config->cluster_master_address = 0;
500
501 log(0,0,0,0, "I am declaring myself the master!\n");
502
503 #ifdef BGP
504 if (bgp_configured && have_peers)
505 bgp_enable_routing(0); /* stop handling traffic */
506 #endif /* BGP */
507
508 if (config->cluster_seq_number == -1)
509 config->cluster_seq_number = 0;
510
511 //
512 // Go through and mark all the tunnels as defined.
513 // Count the highest used tunnel number as well.
514 //
515 config->cluster_highest_tunnelid = 0;
516 for (i = 0, tcount = 0; i < MAXTUNNEL; ++i) {
517 if (tunnel[i].state == TUNNELUNDEF)
518 tunnel[i].state = TUNNELFREE;
519
520 if (tunnel[i].state != TUNNELFREE && i > config->cluster_highest_tunnelid)
521 config->cluster_highest_tunnelid = i;
522 }
523
524 //
525 // Go through and mark all the sessions as being defined.
526 // reset the idle timeouts.
527 // add temporary byte counters to permanent ones.
528 // Re-string the free list.
529 // Find the ID of the highest session.
530 last_free = 0;
531 high_sid = 0;
532 config->cluster_highest_sessionid = 0;
533 for (i = 0, count = 0; i < MAXSESSION; ++i) {
534 if (session[i].tunnel == T_UNDEF) {
535 session[i].tunnel = T_FREE;
536 ++count;
537 }
538
539 if (session[i].tunnel == T_FREE) { // Unused session. Add to free list.
540 session[last_free].next = i;
541 session[i].next = 0;
542 last_free = i;
543 }
544
545 // Reset all the idle timeouts..
546 session[i].last_packet = time_now;
547
548 // Accumulate un-sent byte counters.
549 session[i].cin += sess_count[i].cin;
550 session[i].cout += sess_count[i].cout;
551 session[i].total_cin += sess_count[i].cin;
552 session[i].total_cout += sess_count[i].cout;
553
554 sess_count[i].cin = sess_count[i].cout = 0;
555
556 session[i].radius = 0; // Reset authentication as the radius blocks aren't up to date.
557
558 if (session[i].sid >= high_sid) // This is different to the index into the session table!!!
559 high_sid = session[i].sid+1;
560
561
562 session[i].tbf_in = session[i].tbf_out = 0; // Remove stale pointers from old master.
563 throttle_session(i, session[i].throttle);
564
565 // I'm unsure about this. --mo
566 // It's potentially a good thing, but it could send a
567 // LOT of packets.
568 // if (session[i].throttle)
569 // cluster_send_session(s); // Tell the slaves about the new tbf indexes.
570
571 if (session[i].tunnel != T_FREE && i > config->cluster_highest_sessionid)
572 config->cluster_highest_sessionid = i;
573
574 }
575
576 session[last_free].next = 0; // End of chain.
577 last_sid = high_sid; // Keep track of the highest used session ID.
578
579 become_master();
580
581 rebuild_address_pool();
582
583 // If we're not the very first master, this is a big issue!
584 if(count>0)
585 log(0,0,0,0, "Warning: Fixed %d uninitialized sessions in becoming master!\n", count);
586
587 config->cluster_undefined_sessions = 0;
588 config->cluster_undefined_tunnels = 0;
589
590 //
591 // FIXME. We need to fix up the tunnel control message
592 // queue here! There's a number of other variables we
593 // should also update.
594 cluster_uptodate();
595 }
596
597
598 //
599 // Check that our session table is validly matching what the
600 // master has in mind.
601 //
602 // In particular, if we have too many sessions marked 'undefined'
603 // we fix it up here, and we ensure that the 'first free session'
604 // pointer is valid.
605 //
606 static void cluster_check_sessions(int highsession, int freesession_ptr, int hightunnel)
607 {
608 int i;
609
610 sessionfree = freesession_ptr; // Keep the freesession ptr valid.
611
612 if (config->cluster_iam_uptodate)
613 return;
614
615 if (highsession > config->cluster_undefined_sessions && hightunnel > config->cluster_undefined_tunnels)
616 return;
617
618 // Clear out defined sessions, counting the number of
619 // undefs remaining.
620 config->cluster_undefined_sessions = 0;
621 for (i = 1 ; i < MAXSESSION; ++i) {
622 if (i > highsession) {
623 session[i].tunnel = 0; // Defined.
624 continue;
625 }
626 if (session[i].tunnel != T_UNDEF)
627 continue;
628 ++config->cluster_undefined_sessions;
629 }
630
631 // Clear out defined tunnels, counting the number of
632 // undefs remaining.
633 config->cluster_undefined_tunnels = 0;
634 for (i = 1 ; i < MAXTUNNEL; ++i) {
635 if (i > hightunnel) {
636 tunnel[i].state = TUNNELFREE; // Defined.
637 continue;
638 }
639 if (tunnel[i].state != TUNNELUNDEF)
640 continue;
641 ++config->cluster_undefined_tunnels;
642 }
643
644
645 if (config->cluster_undefined_sessions || config->cluster_undefined_tunnels) {
646 log(2,0,0,0, "Cleared undefined sessions/tunnels. %d sess (high %d), %d tunn (high %d)\n",
647 config->cluster_undefined_sessions, highsession, config->cluster_undefined_tunnels, hightunnel);
648 return;
649 }
650
651 // Are we up to date?
652
653 if (!config->cluster_iam_uptodate)
654 cluster_uptodate();
655 }
656
657 int hb_add_type(char **p, int type, int id)
658 {
659 switch (type) {
660 case C_CSESSION: { // Compressed C_SESSION.
661 u8 c[sizeof(sessiont) * 2]; // Bigger than worst case.
662 u8 *d = (u8 *) &session[id];
663 u8 *orig = d;
664 int size;
665
666 size = rle_compress( &d, sizeof(sessiont), c, sizeof(c) );
667
668 // Did we compress the full structure, and is the size actually
669 // reduced??
670 if ( (d - orig) == sizeof(sessiont) && size < sizeof(sessiont) ) {
671 add_type(p, C_CSESSION, id, (char*) c, size);
672 break;
673 }
674 // Failed to compress : Fall through.
675 }
676 case C_SESSION: add_type(p, C_SESSION, id,
677 (char*) &session[id], sizeof(sessiont));
678 break;
679
680 case C_CTUNNEL: { // Compressed C_TUNNEL
681 u8 c[sizeof(tunnelt) * 2]; // Bigger than worst case.
682 u8 *d = (u8 *) &tunnel[id];
683 u8 *orig = d;
684 int size;
685
686 size = rle_compress( &d, sizeof(tunnelt), c, sizeof(c) );
687
688 // Did we compress the full structure, and is the size actually
689 // reduced??
690 if ( (d - orig) == sizeof(tunnelt) && size < sizeof(tunnelt) ) {
691 add_type(p, C_CTUNNEL, id, c, size);
692 break;
693 }
694 // Failed to compress : Fall through.
695 }
696 case C_TUNNEL: add_type(p, C_TUNNEL, id,
697 (char*) &tunnel[id], sizeof(tunnelt));
698 break;
699 default:
700 log(0,0,0,0, "Found an invalid type in heart queue! (%d)\n", type);
701 kill(0, SIGTERM);
702 }
703 return 0;
704 }
705
706 //
707 // Send a heartbeat, incidently sending out any queued changes..
708 //
709 void cluster_heartbeat(int highsession, int freesession, int hightunnel)
710 {
711 int i, count = 0, tcount = 0;
712 char buff[MAX_HEART_SIZE + sizeof(heartt) + sizeof(int) ];
713 heartt h;
714 char * p = buff;
715
716 if (!config->cluster_iam_master) // Only the master does this.
717 return;
718
719 hsess = highsession;
720 fsess = freesession;
721 // Fill out the heartbeat header.
722 h.version = HB_VERSION;
723 h.seq = config->cluster_seq_number;
724 h.basetime = basetime;
725 h.clusterid = config->bind_address; // Will this do??
726 h.basetime = basetime;
727 h.highsession = highsession;
728 h.freesession = freesession;
729 h.hightunnel = hightunnel;
730 h.size_sess = sizeof(sessiont); // Just in case.
731 h.size_tunn = sizeof(tunnelt);
732
733 add_type(&p, C_HEARTBEAT, HB_VERSION, (char*) &h, sizeof(h) );
734
735 for (i = 0; i < config->cluster_num_changes; ++i) {
736 hb_add_type(&p, cluster_changes[i].type, cluster_changes[i].id);
737 }
738
739 if (p > (buff + sizeof(buff))) { // Did we somehow manage to overun the buffer?
740 log(0,0,0,0, "FATAL: Overran the heartbeat buffer! This is fatal. Exiting. (size %d)\n", p - buff);
741 kill(0, SIGTERM);
742 }
743
744 //
745 // Fill out the packet with sessions from the session table...
746 // (not forgetting to leave space so we can get some tunnels in too )
747 while ( (p + sizeof(u32) * 2 + sizeof(sessiont) * 2 ) < (buff + MAX_HEART_SIZE) ) {
748
749 if (!walk_session_number) // session #0 isn't valid.
750 ++walk_session_number;
751
752 if (count >= highsession) // If we're a small cluster, don't go wild.
753 break;
754
755 hb_add_type(&p, C_CSESSION, walk_session_number);
756 walk_session_number = (1+walk_session_number)%(highsession+1); // +1 avoids divide by zero.
757
758 ++count; // Count the number of extra sessions we're sending.
759 }
760
761 //
762 // Fill out the packet with tunnels from the tunnel table...
763 // This effectively means we walk the tunnel table more quickly
764 // than the session table. This is good because stuffing up a
765 // tunnel is a much bigger deal than stuffing up a session.
766 //
767 while ( (p + sizeof(u32) * 2 + sizeof(tunnelt) ) < (buff + MAX_HEART_SIZE) ) {
768
769 if (!walk_tunnel_number) // tunnel #0 isn't valid.
770 ++walk_tunnel_number;
771
772 if (tcount >= config->cluster_highest_tunnelid)
773 break;
774
775 hb_add_type(&p, C_CTUNNEL, walk_tunnel_number);
776 walk_tunnel_number = (1+walk_tunnel_number)%(config->cluster_highest_tunnelid+1); // +1 avoids divide by zero.
777
778 ++tcount;
779 }
780
781 //
782 // Did we do something wrong?
783 if (p > (buff + sizeof(buff))) { // Did we somehow manage to overun the buffer?
784 log(0,0,0,0, "Overran the heartbeat buffer now! This is fatal. Exiting. (size %d)\n", p - buff);
785 kill(0, SIGTERM);
786 }
787
788 log(3,0,0,0, "Sending heartbeat #%d with %d changes (%d x-sess, %d x-tunnels, %d highsess, %d hightun size %d)\n",
789 h.seq, config->cluster_num_changes, count, tcount, config->cluster_highest_sessionid,
790 config->cluster_highest_tunnelid, (p-buff));
791
792 config->cluster_num_changes = 0;
793
794 send_heartbeat(h.seq, buff, (p-buff) ); // Send out the heartbeat to the cluster, keeping a copy of it.
795
796 config->cluster_seq_number = (config->cluster_seq_number+1)%HB_MAX_SEQ; // Next seq number to use.
797 }
798
799 //
800 // A structure of type 'type' has changed; Add it to the queue to send.
801 //
802 int type_changed(int type, int id)
803 {
804 int i;
805
806 for (i = 0 ; i < config->cluster_num_changes ; ++i)
807 if ( cluster_changes[i].id == id &&
808 cluster_changes[i].type == type)
809 return 0; // Already marked for change.
810
811 cluster_changes[i].type = type;
812 cluster_changes[i].id = id;
813 ++config->cluster_num_changes;
814
815 if (config->cluster_num_changes > MAX_CHANGES)
816 cluster_heartbeat(config->cluster_highest_sessionid, fsess, config->cluster_highest_tunnelid);
817
818 return 1;
819 }
820
821
822 // A particular session has been changed!
823 int cluster_send_session(int sid)
824 {
825 if (!config->cluster_iam_master) {
826 log(0,0,sid,0, "I'm not a master, but I just tried to change a session!\n");
827 return -1;
828 }
829
830 return type_changed(C_CSESSION, sid);
831 }
832
833 // A particular tunnel has been changed!
834 int cluster_send_tunnel(int tid)
835 {
836 if (!config->cluster_iam_master) {
837 log(0,0,0,tid, "I'm not a master, but I just tried to change a tunnel!\n");
838 return -1;
839 }
840
841 return type_changed(C_CTUNNEL, tid);
842 }
843
844
845 //
846 // We're a master, and a slave has just told us that it's
847 // missed a packet. We'll resend it every packet since
848 // the last one it's seen.
849 //
850 int cluster_catchup_slave(int seq, u32 slave)
851 {
852 int s;
853 int diff;
854
855 log(1,0,0,0, "Slave %s sent LASTSEEN with seq %d\n", inet_toa(slave), seq);
856
857 diff = config->cluster_seq_number - seq; // How many packet do we need to send?
858 if (diff < 0)
859 diff += HB_MAX_SEQ;
860
861 if (diff >= HB_HISTORY_SIZE) { // Ouch. We don't have the packet to send it!
862 log(0,0,0,0, "A slaved asked for message %d when our seq number is %d. Killing it.\n",
863 seq, config->cluster_seq_number);
864 return peer_send_message(slave, C_KILL, seq, NULL, 0);// Kill the slave. Nothing else to do.
865 }
866
867 // Now resend every packet that it missed, in order.
868 while (seq != config->cluster_seq_number) {
869 s = seq%HB_HISTORY_SIZE;
870 if (seq != past_hearts[s].seq) {
871 log(0,0,0,0, "Tried to re-send heartbeat for %s but %d doesn't match %d! (%d,%d)\n",
872 inet_toa(slave), seq, past_hearts[s].seq, s, config->cluster_seq_number);
873 return -1; // What to do here!?
874 }
875 peer_send_data(slave, past_hearts[s].data, past_hearts[s].size);
876 seq = (seq+1)%HB_MAX_SEQ; // Increment to next seq number.
877 }
878 return 0; // All good!
879 }
880
881 //
882 // We've heard from another peer! Add it to the list
883 // that we select from at election time.
884 //
885 int cluster_add_peer(u32 peer, time_t basetime, pingt *p)
886 {
887 int i;
888 u32 clusterid;
889
890 clusterid = p->addr;
891 if (clusterid != config->bind_address)
892 {
893 // Is this for us?
894 log(4,0,0,0, "Skipping ping from %s (different cluster)\n", inet_toa(peer));
895 return 0;
896 }
897
898 // Is this the master shutting down??
899 if (peer == config->cluster_master_address && !basetime) {
900 config->cluster_master_address = 0;
901 config->cluster_last_hb = 0; // Force an election.
902 cluster_check_master();
903 return 0;
904 }
905
906 for (i = 0; i < num_peers ; ++i)
907 {
908 if (peers[i].peer != peer)
909 continue;
910
911 // This peer already exists. Just update the timestamp.
912 peers[i].basetime = basetime;
913 peers[i].timestamp = TIME;
914 break;
915 }
916
917 if (i >= num_peers)
918 {
919 log(4,0,0,0, "Adding %s as a peer\n", inet_toa(peer));
920
921 // Not found. Is there a stale slot to re-use?
922 for (i = 0; i < num_peers ; ++i)
923 {
924 if (peers[i].peer != peer)
925 continue;
926 if ((peers[i].timestamp + config->cluster_hb_timeout * 10) < TIME) // Stale.
927 break;
928 }
929
930 if (i >= CLUSTER_MAX_SIZE)
931 {
932 // Too many peers!!
933 log(0,0,0,0, "Tried to add %s as a peer, but I already have %d of them!\n", inet_toa(peer), i);
934 return -1;
935 }
936
937 peers[i].peer = peer;
938 peers[i].basetime = basetime;
939 peers[i].timestamp = TIME;
940 if (i == num_peers)
941 ++num_peers;
942
943 log(1,0,0,0, "Added %s as a new peer. Now %d peers\n", inet_toa(peer), num_peers);
944 }
945
946 #ifdef BGP
947 /* drop routes if we've now got a peer */
948 if (bgp_configured && config->cluster_iam_master && !have_peers)
949 bgp_enable_routing(0);
950 #endif /* BGP */
951
952 have_peers = 1;
953
954 return 1;
955 }
956
957 /* Handle the slave updating the byte counters for the master. */
958 //
959 // Note that we don't mark the session as dirty; We rely on
960 // the slow table walk to propogate this back out to the slaves.
961 //
962 int cluster_handle_bytes(char * data, int size)
963 {
964 bytest * b;
965
966 b = (bytest*) data;
967
968 log(3,0,0,0, "Got byte counter update (size %d)\n", size);
969
970 /* Loop around, adding the byte
971 counts to each of the sessions. */
972
973 while (size >= sizeof(*b) ) {
974 if (b->sid > MAXSESSION) {
975 log(0,0,0,0, "Got C_BYTES with session #%d!\n", b->sid);
976 return -1; /* Abort processing */
977 }
978
979 session[b->sid].total_cin += b->in;
980 session[b->sid].total_cout += b->out;
981
982 session[b->sid].cin += b->in;
983 session[b->sid].cout += b->out;
984 session[b->sid].last_packet = time_now; // Reset idle timer!
985
986 size -= sizeof(*b);
987 ++b;
988 }
989
990 if (size != 0)
991 log(0,0,0,0, "Got C_BYTES with %d bytes of trailing junk!\n", size);
992
993 return size;
994 }
995
996 //
997 // Handle receiving a session structure in a heartbeat packet.
998 //
999 static int cluster_recv_session(int more , u8 * p)
1000 {
1001 if (more >= MAXSESSION) {
1002 log(0,0,0,0, "DANGER: Received a heartbeat session id > MAXSESSION!\n");
1003 return -1;
1004 }
1005
1006 if (session[more].tunnel == T_UNDEF) {
1007 if (config->cluster_iam_uptodate) { // Sanity.
1008 log(0,0,0,0, "I thought I was uptodate but I just found an undefined session!\n");
1009 } else {
1010 --config->cluster_undefined_sessions;
1011 }
1012 }
1013
1014 load_session(more, (sessiont*) p); // Copy session into session table..
1015
1016 log(5,0,more,0, "Received session update (%d undef)\n", config->cluster_undefined_sessions);
1017
1018 if (!config->cluster_iam_uptodate)
1019 cluster_uptodate(); // Check to see if we're up to date.
1020 return 0;
1021 }
1022
1023 static int cluster_recv_tunnel(int more, u8 *p)
1024 {
1025 if (more >= MAXTUNNEL) {
1026 log(0,0,0,0, "DANGER: Received a tunnel session id > MAXTUNNEL!\n");
1027 return -1;
1028 }
1029
1030 if (tunnel[more].state == TUNNELUNDEF) {
1031 if (config->cluster_iam_uptodate) { // Sanity.
1032 log(0,0,0,0, "I thought I was uptodate but I just found an undefined tunnel!\n");
1033 } else {
1034 --config->cluster_undefined_tunnels;
1035 }
1036 }
1037
1038 memcpy(&tunnel[more], p, sizeof(tunnel[more]) );
1039
1040 //
1041 // Clear tunnel control messages. These are dynamically allocated.
1042 // If we get unlucky, this may cause the tunnel to drop!
1043 //
1044 tunnel[more].controls = tunnel[more].controle = NULL;
1045 tunnel[more].controlc = 0;
1046
1047 log(5,0,0,more, "Received tunnel update\n");
1048
1049 if (!config->cluster_iam_uptodate)
1050 cluster_uptodate(); // Check to see if we're up to date.
1051
1052 return 0;
1053 }
1054
1055
1056 //
1057 // Process a version one heartbeat..
1058 //
1059 static int cluster_process_heartbeat_v2(u8 * data, int size, int more, u8 * p, u32 addr)
1060 {
1061 heartt * h;
1062 int s = size - (p-data);
1063 int i, type;
1064
1065 if (more != HB_VERSION) {
1066 log(0,0,0,0, "Received a heartbeat version that I don't understand!\n");
1067 return -1; // Ignore it??
1068 }
1069 // Ok. It's a heartbeat packet from a cluster master!
1070 if (s < sizeof(*h))
1071 goto shortpacket;
1072
1073
1074 h = (heartt*) p;
1075 p += sizeof(*h);
1076 s -= sizeof(*h);
1077
1078 if (h->clusterid != config->bind_address)
1079 return -1; // It's not part of our cluster.
1080
1081 if (config->cluster_iam_master) { // Sanity...
1082 // Note that this MUST match the election process above!
1083
1084 log(0,0,0,0, "I just got a packet claiming to be from a master but _I_ am the master!\n");
1085 if (!h->basetime) {
1086 log(0,0,0,0, "Heartbeat from addr %s with zero basetime!\n", inet_toa(addr) );
1087 return -1; // Skip it.
1088 }
1089 if (basetime > h->basetime) {
1090 log(0,0,0,0, "They're (%s) an older master than me so I'm gone!\n", inet_toa(addr));
1091 kill(0, SIGTERM);
1092 exit(1);
1093 }
1094 if (basetime == h->basetime && my_address < addr) { // Tie breaker.
1095 log(0,0,0,0, "They're a higher IP address than me, so I'm gone!\n");
1096 kill(0, SIGTERM);
1097 exit(1);
1098 }
1099 return -1; // Skip it.
1100 }
1101
1102 if (config->cluster_seq_number == -1) // Don't have one. Just align to the master...
1103 config->cluster_seq_number = h->seq;
1104
1105 config->cluster_last_hb = TIME; // Reset to ensure that we don't become master!!
1106
1107 if (config->cluster_seq_number != h->seq) { // Out of sequence heartbeat!
1108 log(1,0,0,0, "HB: Got seq# %d but was expecting %d. asking for resend.\n", h->seq, config->cluster_seq_number);
1109
1110 peer_send_message(addr, C_LASTSEEN, config->cluster_seq_number, NULL, 0);
1111
1112 config->cluster_last_hb = TIME; // Reset to ensure that we don't become master!!
1113
1114 // Just drop the packet. The master will resend it as part of the catchup.
1115
1116 return 0;
1117 }
1118 // Save the packet in our buffer.
1119 // This is needed in case we become the master.
1120 config->cluster_seq_number = (h->seq+1)%HB_MAX_SEQ;
1121 i = h->seq % HB_HISTORY_SIZE;
1122 past_hearts[i].seq = h->seq;
1123 past_hearts[i].size = size;
1124 memcpy(&past_hearts[i].data, data, size); // Save it.
1125
1126
1127 // Check that we don't have too many undefined sessions, and
1128 // that the free session pointer is correct.
1129 cluster_check_sessions(h->highsession, h->freesession, h->hightunnel);
1130
1131 // Ok. process the packet...
1132 while ( s > 0) {
1133
1134 type = * ((u32*) p);
1135 p += sizeof(u32);
1136 s -= sizeof(u32);
1137
1138 more = * ((u32*) p);
1139 p += sizeof(u32);
1140 s -= sizeof(u32);
1141
1142 switch (type) {
1143 case C_CSESSION: { // Compressed session structure.
1144 u8 c [ sizeof(sessiont) + 2];
1145 int size;
1146 u8 * orig_p = p;
1147
1148 size = rle_decompress((u8 **) &p, s, c, sizeof(c) );
1149 s -= (p - orig_p);
1150
1151 if (size != sizeof(sessiont) ) { // Ouch! Very very bad!
1152 log(0,0,0,0, "DANGER: Received a CSESSION that didn't decompress correctly!\n");
1153 // Now what? Should exit! No-longer up to date!
1154 break;
1155 }
1156
1157 cluster_recv_session(more, c);
1158 break;
1159 }
1160 case C_SESSION:
1161 if ( s < sizeof(session[more]))
1162 goto shortpacket;
1163
1164 cluster_recv_session(more, p);
1165
1166 p += sizeof(session[more]);
1167 s -= sizeof(session[more]);
1168 break;
1169
1170 case C_CTUNNEL: { // Compressed tunnel structure.
1171 u8 c [ sizeof(tunnelt) + 2];
1172 int size;
1173 u8 * orig_p = p;
1174
1175 size = rle_decompress( (u8 **) &p, s, c, sizeof(c) );
1176 s -= (p - orig_p);
1177
1178 if (size != sizeof(tunnelt) ) { // Ouch! Very very bad!
1179 log(0,0,0,0, "DANGER: Received a CSESSION that didn't decompress correctly!\n");
1180 // Now what? Should exit! No-longer up to date!
1181 break;
1182 }
1183
1184 cluster_recv_tunnel(more, c);
1185 break;
1186
1187 }
1188 case C_TUNNEL:
1189 if ( s < sizeof(tunnel[more]))
1190 goto shortpacket;
1191
1192 cluster_recv_tunnel(more, p);
1193
1194 p += sizeof(tunnel[more]);
1195 s -= sizeof(tunnel[more]);
1196 break;
1197 default:
1198 log(0,0,0,0, "DANGER: I received a heartbeat element where I didn't understand the type! (%d)\n", type);
1199 return -1; // can't process any more of the packet!!
1200 }
1201 }
1202 if (config->cluster_master_address != addr)
1203 {
1204 char *str;
1205 str = strdup(inet_toa(config->cluster_master_address));
1206 log(0,0,0,0, "My master just changed from %s to %s!\n", str, inet_toa(addr));
1207 if (str) free(str);
1208 }
1209
1210 config->cluster_master_address = addr;
1211 config->cluster_last_hb = TIME; // Successfully received a heartbeat!
1212 return 0;
1213
1214 shortpacket:
1215 log(0,0,0,0, "I got an incomplete heartbeat packet! This means I'm probably out of sync!!\n");
1216 return -1;
1217 }
1218
1219 //
1220 // We got a packet on the cluster port!
1221 // Handle pings, lastseens, and heartbeats!
1222 //
1223 int processcluster(char * data, int size, u32 addr)
1224 {
1225 int type, more;
1226 char * p = data;
1227 int s = size;
1228
1229 if (addr == my_address)
1230 return -1; // Ignore it. Something looped back the multicast!
1231
1232 log(5,0,0,0, "Process cluster: %d bytes from %s\n", size, inet_toa(addr));
1233
1234 if (s <= 0) // Any data there??
1235 return -1;
1236
1237 if (s < 8)
1238 goto shortpacket;
1239
1240 type = * ((u32*) p);
1241 p += sizeof(u32);
1242 s -= sizeof(u32);
1243
1244 more = * ((u32*) p);
1245 p += sizeof(u32);
1246 s -= sizeof(u32);
1247
1248 switch (type) {
1249 case C_PING: // Update the peers table.
1250 return cluster_add_peer(addr, more, (pingt*)p);
1251
1252 case C_LASTSEEN: // Catch up a slave (slave missed a packet).
1253 return cluster_catchup_slave(more, addr);
1254
1255 case C_FORWARD: { // Forwarded control packet. pass off to processudp.
1256 struct sockaddr_in a;
1257 a.sin_addr.s_addr = more;
1258
1259 a.sin_port = * (int*) p;
1260 s -= sizeof(int);
1261 p += sizeof(int);
1262
1263 if (!config->cluster_iam_master) { // huh?
1264 log(0,0,0,0, "I'm not the master, but I got a C_FORWARD from %s?\n", inet_toa(addr));
1265 return -1;
1266 }
1267
1268 log(4,0,0,0, "Got a forwarded packet... (%s:%d)\n", inet_toa(more), a.sin_port);
1269 STAT(recv_forward);
1270 processudp(p, s, &a);
1271 return 0;
1272 }
1273 case C_THROTTLE: { // Receive a forwarded packet from a slave.
1274 if (!config->cluster_iam_master) {
1275 log(0,0,0,0, "I'm not the master, but I got a C_THROTTLE from %s?\n", inet_toa(addr));
1276 return -1;
1277 }
1278
1279 tbf_queue_packet(more, p, s); // The TBF id tells wether it goes in or out.
1280 return 0;
1281 }
1282 case C_GARDEN:
1283 // Receive a walled garden packet from a slave.
1284 if (!config->cluster_iam_master) {
1285 log(0,0,0,0, "I'm not the master, but I got a C_GARDEN from %s?\n", inet_toa(addr));
1286 return -1;
1287 }
1288
1289 tun_write(p, s);
1290 return 0;
1291
1292 case C_BYTES:
1293 return cluster_handle_bytes(p, s);
1294
1295 case C_KILL: // The master asked us to die!? (usually because we're too out of date).
1296 if (config->cluster_iam_master) {
1297 log(0,0,0,0, "_I_ am master, but I received a C_KILL from %s! (Seq# %d)\n", inet_toa(addr), more);
1298 return -1;
1299 }
1300 if (more != config->cluster_seq_number) {
1301 log(0,0,0,0, "The master asked us to die but the seq number didn't match!?\n");
1302 return -1;
1303 }
1304
1305 if (addr != config->cluster_master_address) {
1306 log(0,0,0,0, "Received a C_KILL from %s which doesn't match config->cluster_master_address (%x)\n",
1307 inet_toa(addr), config->cluster_master_address);
1308 // We can only warn about it. The master might really have switched!
1309 }
1310
1311 log(0,0,0,0, "Received a valid C_KILL: I'm going to die now.\n");
1312 kill(0, SIGTERM);
1313 exit(0); // Lets be paranoid;
1314 return -1; // Just signalling the compiler.
1315
1316 case C_HEARTBEAT:
1317 log(4,0,0,0, "Got a heartbeat from %s\n", inet_toa(addr));
1318
1319 return cluster_process_heartbeat_v2(data, size, more, p, addr);
1320
1321 default:
1322 log(0,0,0,0, "Strange type packet received on cluster socket (%d)\n", type);
1323 return -1;
1324 }
1325 return 0;
1326 shortpacket:
1327 log(0,0,0,0, "I got an cluster heartbeat packet! This means I'm probably out of sync!!\n");
1328 return -1;
1329 }
1330
1331 //====================================================================================================
1332
1333 int cmd_show_cluster(struct cli_def *cli, char *command, char **argv, int argc)
1334 {
1335 int i;
1336
1337 if (CLI_HELP_REQUESTED)
1338 return CLI_HELP_NO_ARGS;
1339
1340 cli_print(cli, "Cluster status : %s", config->cluster_iam_master ? "Master" : "Slave" );
1341 cli_print(cli, "My address : %s", inet_toa(my_address));
1342 cli_print(cli, "VIP address : %s", inet_toa(config->bind_address));
1343 cli_print(cli, "Multicast address: %s", inet_toa(config->cluster_address));
1344 cli_print(cli, "Multicast i'face : %s", config->cluster_interface);
1345
1346 if (!config->cluster_iam_master) {
1347 cli_print(cli, "My master : %s (last heartbeat %.1f seconds old)",
1348 config->cluster_master_address ? inet_toa(config->cluster_master_address) : "Not defined",
1349 0.1 * (TIME - config->cluster_last_hb));
1350 cli_print(cli, "Uptodate : %s", config->cluster_iam_uptodate ? "Yes" : "No");
1351 cli_print(cli, "Next sequence number expected: %d", config->cluster_seq_number);
1352 cli_print(cli, "%d sessions undefined of %d", config->cluster_undefined_sessions, config->cluster_highest_sessionid);
1353 cli_print(cli, "%d tunnels undefined of %d", config->cluster_undefined_tunnels, config->cluster_highest_tunnelid);
1354 } else {
1355 cli_print(cli, "Next heartbeat # : %d", config->cluster_seq_number);
1356 cli_print(cli, "Highest session : %d", config->cluster_highest_sessionid);
1357 cli_print(cli, "Highest tunnel : %d", config->cluster_highest_tunnelid);
1358 cli_print(cli, "%d changes queued for sending", config->cluster_num_changes);
1359 }
1360 cli_print(cli, "%d peers.", num_peers);
1361
1362 if (num_peers)
1363 cli_print(cli, "%20s %10s %8s", "Address", "Basetime", "Age");
1364 for (i = 0; i < num_peers; ++i) {
1365 cli_print(cli, "%20s %10d %8d", inet_toa(peers[i].peer),
1366 peers[i].basetime, TIME - peers[i].timestamp);
1367 }
1368 return CLI_OK;
1369 }
1370
1371 //
1372 // Simple run-length-encoding compression.
1373 // Format is
1374 // 1 byte < 128 = count of non-zero bytes following. // Not legal to be zero.
1375 // n non-zero bytes;
1376 // or
1377 // 1 byte > 128 = (count - 128) run of zero bytes. //
1378 // repeat.
1379 // count == 0 indicates end of compressed stream.
1380 //
1381 // Compress from 'src' into 'dst'. return number of bytes
1382 // used from 'dst'.
1383 // Updates *src_p to indicate 1 past last bytes used.
1384 //
1385 // We could get an extra byte in the zero runs by storing (count-1)
1386 // but I'm playing it safe.
1387 //
1388 // Worst case is a 50% expansion in space required (trying to
1389 // compress { 0x00, 0x01 } * N )
1390 int rle_compress(u8 ** src_p, int ssize, u8 *dst, int dsize)
1391 {
1392 int count;
1393 int orig_dsize = dsize;
1394 u8 * x,*src;
1395 src = *src_p;
1396
1397 while (ssize > 0 && dsize > 2) {
1398 count = 0;
1399 x = dst++; --dsize; // Reserve space for count byte..
1400
1401 if (*src) { // Copy a run of non-zero bytes.
1402 while (*src && count < 127 && ssize > 0 && dsize > 1) { // Count number of non-zero bytes.
1403 *dst++ = *src++;
1404 --dsize; --ssize;
1405 ++count;
1406 }
1407 *x = count; // Store number of non-zero bytes. Guarenteed to be non-zero!
1408
1409 } else { // Compress a run of zero bytes.
1410 while (*src == 0 && count < 127 && ssize > 0) {
1411 ++src;
1412 --ssize;
1413 ++count;
1414 }
1415 *x = count | 0x80 ;
1416 }
1417 }
1418
1419 *dst++ = 0x0; // Add Stop byte.
1420 --dsize;
1421
1422 *src_p = src;
1423 return (orig_dsize - dsize);
1424 }
1425
1426 //
1427 // Decompress the buffer into **p.
1428 // 'psize' is the size of the decompression buffer available.
1429 //
1430 // Returns the number of bytes decompressed.
1431 //
1432 // Decompresses from '*src_p' into 'dst'.
1433 // Return the number of dst bytes used.
1434 // Updates the 'src_p' pointer to point to the
1435 // first un-used byte.
1436 int rle_decompress(u8 ** src_p, int ssize, u8 *dst, int dsize)
1437 {
1438 int count;
1439 int orig_dsize = dsize;
1440 char * src = *src_p;
1441
1442 while (ssize >0 && dsize > 0) { // While there's more to decompress, and there's room in the decompress buffer...
1443 count = *src++; --ssize; // get the count byte from the source.
1444 if (count == 0x0) // End marker reached? If so, finish.
1445 break;
1446
1447 if (count & 0x80) { // Decompress a run of zeros
1448 for (count &= 0x7f ; count > 0 && dsize > 0; --count) {
1449 *dst++ = 0x0;
1450 --dsize;
1451 }
1452 } else { // Copy run of non-zero bytes.
1453 for ( ; count > 0 && ssize && dsize; --count) { // Copy non-zero bytes across.
1454 *dst++ = *src++;
1455 --ssize; --dsize;
1456 }
1457 }
1458 }
1459 *src_p = src;
1460 return (orig_dsize - dsize);
1461 }