timekoin /v1.9/peerlist.php

Language PHP Lines 790
MD5 Hash 75e563f8a57b0265bad18c4bffab34ca Estimated Cost $14,284 (why?)
Repository https://bitbucket.org/rev22/timekoin.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
<?PHP
include 'configuration.php';
include 'function.php';
set_time_limit(60);
//***********************************************************************************
//***********************************************************************************
if(PEERLIST_DISABLED == TRUE || TIMEKOIN_DISABLED == TRUE)
{
	// This has been disabled
	exit;
}
//***********************************************************************************
//***********************************************************************************
// Open connection to database
mysql_connect(MYSQL_IP,MYSQL_USERNAME,MYSQL_PASSWORD);
mysql_select_db(MYSQL_DATABASE);

// Check for banned IP address
$ip = mysql_result(mysql_query("SELECT * FROM `ip_banlist` WHERE `ip` = '" . $_SERVER['REMOTE_ADDR'] . "' LIMIT 1"),0,0);

if(empty($ip) == FALSE)
{
	// Sorry, your IP address has been banned :(
	exit;
}
//***********************************************************************************
//***********************************************************************************
// Answer poll challenge
if($_GET["action"] == "poll" && empty($_GET["challenge"]) == FALSE)
{
	echo hash('crc32', intval($_GET["challenge"]));

	// Check if Ambient Peer Restart is enabled (randomize to avoid DB spamming)
	if(rand(1,30) == 15)
	{
		$allow_ambient_peer_restart = mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'allow_ambient_peer_restart' LIMIT 1"),0,"field_data");

		if($allow_ambient_peer_restart == 1 && $allow_ambient_peer_restart !== FALSE) // Check against DB failure also
		{
			// Check to make sure Timekoin has not be stopped for any unknown reason
			$script_loop_active = mysql_result(mysql_query("SELECT * FROM `main_loop_status` WHERE `field_name` = 'main_heartbeat_active' LIMIT 1"),0,"field_data");			
			$script_last_heartbeat = mysql_result(mysql_query("SELECT * FROM `main_loop_status` WHERE `field_name` = 'main_last_heartbeat' LIMIT 1"),0,"field_data");

			if($script_loop_active > 0)
			{
				// Main should still be active
				if((time() - $script_last_heartbeat) > 30) // Greater than triple the loop time, something is wrong
				{
					// Main stop was unexpected
					write_log("Main Timekoin Processor has Failed, going to try an Ambient Peer Restart", "PL");

					// Database Initialization
					initialization_database();

					mysql_query("UPDATE `main_loop_status` SET `field_data` = '" . time() . "' WHERE `main_loop_status`.`field_name` = 'main_last_heartbeat' LIMIT 1");

					// Set loop at active now
					mysql_query("UPDATE `main_loop_status` SET `field_data` = '1' WHERE `main_loop_status`.`field_name` = 'main_heartbeat_active' LIMIT 1");

					source_bg('main.php');

					activate(TIMEKOINSYSTEM, 1); // In case this was disabled from a emergency stop call in the server GUI				
				}
			}

			// Check watchdog script to make sure it is still running
			$script_loop_active = mysql_result(mysql_query("SELECT * FROM `main_loop_status` WHERE `field_name` = 'watchdog_heartbeat_active' LIMIT 1"),0,"field_data");
			$script_last_heartbeat = mysql_result(mysql_query("SELECT * FROM `main_loop_status` WHERE `field_name` = 'watchdog_last_heartbeat' LIMIT 1"),0,"field_data");

			if($script_loop_active > 0)
			{
				// Watchdog should still be active
				if((time() - $script_last_heartbeat) > 60) // Greater than double the loop time, something is wrong
				{
					// Watchdog stop was unexpected
					write_log("Watchdog has Failed, going to try an Ambient Peer Restart", "PL");

					mysql_query("UPDATE `main_loop_status` SET `field_data` = '" . time() . "' WHERE `main_loop_status`.`field_name` = 'watchdog_last_heartbeat' LIMIT 1");

					// Set loop at active now
					mysql_query("UPDATE `main_loop_status` SET `field_data` = '1' WHERE `main_loop_status`.`field_name` = 'watchdog_heartbeat_active' LIMIT 1");

					source_bg('watchdog.php', TRUE);
				}
			}
		} // End Ambient Peer Restart Active Check
	} // End Randomize Check

	// Log inbound IP activity
	mysql_query("INSERT INTO `ip_activity` (`timestamp` ,`ip`, `attribute`)VALUES ('" . time() . "', '" . $_SERVER['REMOTE_ADDR'] . "', 'PL')");
	exit;
}
//***********************************************************************************
//***********************************************************************************
// Answer poll challenge
if($_GET["action"] == "polltime")
{
	echo time();
	
	// Log inbound IP activity
	mysql_query("INSERT INTO `ip_activity` (`timestamp` ,`ip`, `attribute`)VALUES ('" . time() . "', '" . $_SERVER['REMOTE_ADDR'] . "', 'PL')");
	exit;
}
//***********************************************************************************
//***********************************************************************************
// Answer a request to see our new/active peer list (Random 10 from new peer list, Random 5 from active peer list)
if($_GET["action"] == "new_peers")
{
	$allow_lan_peers = intval(mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'allow_LAN_peers' LIMIT 1"),0,"field_data"));

	// Only show peers that have less than 10 poll failures
	$sql = "SELECT * FROM `new_peers_list` WHERE `poll_failures` < 10 ORDER BY RAND() LIMIT 10";

	$sql_result = mysql_query($sql);
	$sql_num_results = mysql_num_rows($sql_result);

	$peer_counter = 1;

	for ($i = 0; $i < $sql_num_results; $i++)
	{
		$sql_row = mysql_fetch_array($sql_result);

		$ip_address = $sql_row["IP_Address"];
		$domain = $sql_row["domain"];
		$subfolder = $sql_row["subfolder"];
		$port_number = $sql_row["port_number"];

		// Check for non-private IP range
		if(is_private_ip($ip_address, $allow_lan_peers) == FALSE)
		{
			echo "-----IP$peer_counter=$ip_address-----domain$peer_counter=$domain-----subfolder$peer_counter=$subfolder-----port_number$peer_counter=$port_number-----";
			$peer_counter++;
		}
	}

	$sql = "SELECT * FROM `active_peer_list` ORDER BY RAND() LIMIT 5";

	$sql_result = mysql_query($sql);
	$sql_num_results = mysql_num_rows($sql_result);

	for ($i = 0; $i < $sql_num_results; $i++)
	{
		$sql_row = mysql_fetch_array($sql_result);

		$ip_address = $sql_row["IP_Address"];
		$domain = $sql_row["domain"];
		$subfolder = $sql_row["subfolder"];
		$port_number = $sql_row["port_number"];

		// Check for non-private IP range
		if(is_private_ip($ip_address, $allow_lan_peers) == FALSE)
		{		
			echo "-----IP$peer_counter=$ip_address-----domain$peer_counter=$domain-----subfolder$peer_counter=$subfolder-----port_number$peer_counter=$port_number-----";
			$peer_counter++;
		}
	}

	// Log inbound IP activity
	mysql_query("INSERT INTO `ip_activity` (`timestamp` ,`ip`, `attribute`)VALUES ('" . time() . "', '" . $_SERVER['REMOTE_ADDR'] . "', 'PL')");
	exit;
}
//***********************************************************************************
//***********************************************************************************
// Answer join request
if($_GET["action"] == "join")
{
	$max_active_peers = mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'max_active_peers' LIMIT 1"),0,"field_data");

	// How many active peers do we have?
	$sql = "SELECT * FROM `active_peer_list`";
	$active_peers = mysql_num_rows(mysql_query($sql));

	if($active_peers >= $max_active_peers)
	{
		// Server is full for active peers
		echo "FULL";
	}
	else
	{
		// Server has room for another peer
		echo "OK";
	}

	// Log inbound IP activity
	mysql_query("INSERT INTO `ip_activity` (`timestamp` ,`ip`, `attribute`)VALUES ('" . time() . "', '" . $_SERVER['REMOTE_ADDR'] . "', 'PL')");
	exit;
}
//***********************************************************************************
//***********************************************************************************
// Answer exchange request
if($_GET["action"] == "exchange")
{
	$allow_lan_peers = intval(mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'allow_LAN_peers' LIMIT 1"),0,"field_data"));
	$max_active_peers = mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'max_active_peers' LIMIT 1"),0,"field_data");

	// How many active peers do we have?
	$sql = "SELECT * FROM `active_peer_list`";
	$active_peers = mysql_num_rows(mysql_query($sql));

	if($active_peers >= $max_active_peers)
	{
		// Server is full for active peers
		echo "FULL";
	}
	else
	{
		// Server has room for another peer
		$my_server_domain = mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'server_domain' LIMIT 1"),0,"field_data");
		$my_server_subfolder = mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'server_subfolder' LIMIT 1"),0,"field_data");
		$my_server_port_number = mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'server_port_number' LIMIT 1"),0,"field_data");

		$ip_address = $_SERVER['REMOTE_ADDR'];
		$domain = filter_sql($_GET["domain"]);
		$subfolder = filter_sql($_GET["subfolder"]);
		$port_number = intval($_GET["port_number"]);

		// Check to make sure that this peer is not already in our active peer list
		$duplicate_check1 = mysql_result(mysql_query("SELECT * FROM `active_peer_list` WHERE `IP_Address` = '$ip_address' LIMIT 1"),0,"join_peer_list");
		$duplicate_check2 = mysql_result(mysql_query("SELECT * FROM `active_peer_list` WHERE `domain` LIKE '$domain' LIMIT 1"),0,"join_peer_list");

		if(empty($ip_address) == TRUE)
		{
			//Don't have an IP address, check for duplicate domain
			if(empty($duplicate_check2) == TRUE)
			{
				if($my_server_domain == $domain)
				{
					$duplicate_peer = TRUE;
				}
				else
				{
					// Neither IP nor Domain exist
					$duplicate_peer = FALSE;
				}
			}
			else
			{
				$duplicate_peer = TRUE;
			}
		}
		else
		{
			// Using IP only, is there a duplicate
			if(empty($duplicate_check1) == TRUE)
			{
				if($my_server_domain == $domain  || empty($duplicate_check2) == FALSE)
				{
					$duplicate_peer = TRUE;
				}
				else
				{
					// Check for non-private IP range
					if(is_private_ip($ip_address, $allow_lan_peers) == FALSE)
					{
						// Neither IP nor Domain exist
						$duplicate_peer = FALSE;
					}
					else
					{
						$duplicate_peer = TRUE;
					}
				}
			}
			else
			{
				$duplicate_peer = TRUE;
			}
		}

		if($duplicate_peer == FALSE)
		{
			if(empty($domain) == FALSE)
			{
				//Assign by domain only if one is included, instead of having both IP and Domain at the same time.
				$ip_address = NULL;
			}
			
			$sql = "INSERT INTO `active_peer_list` (`IP_Address` ,`domain` ,`subfolder` ,`port_number` ,`last_heartbeat` ,`join_peer_list` ,`failed_sent_heartbeat`)
	VALUES ('$ip_address', '$domain', '$subfolder', '$port_number', '" . time() . "', '" . time() . "', '0');";		

			if(mysql_query($sql) == TRUE)
			{
				// Exchange was saved, now output our peer information
				echo "-----status=OK-----domain=$my_server_domain-----subfolder=$my_server_subfolder-----port_number=$my_server_port_number-----";
			}
			else
			{
				// Could not save peer, report error problem
				echo "-----status=FAILED-----domain";
			}
		}
		else
		{
			// Already in our list, might be a re-connect, so give the other peer the OK
			echo "-----status=OK-----domain=$my_server_domain-----subfolder=$my_server_subfolder-----port_number=$my_server_port_number-----";
		}
	}

	// Log inbound IP activity
	mysql_query("INSERT INTO `ip_activity` (`timestamp` ,`ip`, `attribute`)VALUES ('" . time() . "', '" . $_SERVER['REMOTE_ADDR'] . "', 'PL')");
	exit;
}
//***********************************************************************************
//***********************************************************************************
$loop_active = mysql_result(mysql_query("SELECT * FROM `main_loop_status` WHERE `field_name` = 'peerlist_heartbeat_active' LIMIT 1"),0,"field_data");

// Check if loop is already running
if($loop_active == 0)
{
	// Set the working status of 1
	$sql = "UPDATE `main_loop_status` SET `field_data` = '1' WHERE `main_loop_status`.`field_name` = 'peerlist_heartbeat_active' LIMIT 1";
	mysql_query($sql);
}
else
{
	// Loop called while still working
	exit;
}
//***********************************************************************************
//***********************************************************************************
ini_set('user_agent', 'Timekoin Server (Peerlist) v' . TIMEKOIN_VERSION);
ini_set('default_socket_timeout', 3); // Timeout for request in seconds
$context = stream_context_create(array('http' => array('header'=>'Connection: close'))); // Force close socket after complete
$max_active_peers = mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'max_active_peers' LIMIT 1"),0,"field_data");
$max_new_peers = mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'max_new_peers' LIMIT 1"),0,"field_data");
$allow_lan_peers = intval(mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'allow_LAN_peers' LIMIT 1"),0,"field_data"));

// How many active peers do we have?
$sql = "SELECT * FROM `active_peer_list`";
$active_peers = mysql_num_rows(mysql_query($sql));

$sql = "SELECT * FROM `new_peers_list`";
$new_peers = mysql_num_rows(mysql_query($sql));

if($active_peers == 0 && $new_peers == 0)
{
	// No active or new peers to poll from, start with the first contact servers
	// and copy them to the new peer list
	$sql = "SELECT * FROM `options` WHERE `field_name` = 'first_contact_server'";

	$sql_result = mysql_query($sql);
	$sql_num_results = mysql_num_rows($sql_result);

	// First Contact Server Format
	//---ip=192.168.0.1---domain=timekoin.com---subfolder=timekoin---port=80---end
	for ($i = 0; $i < $sql_num_results; $i++)
	{
		$sql_row = mysql_fetch_array($sql_result);
		
		$peer_ip = find_string("---ip=", "---domain", $sql_row["field_data"]);
		$peer_domain = find_string("---domain=", "---subfolder", $sql_row["field_data"]);
		$peer_subfolder = find_string("---subfolder=", "---port", $sql_row["field_data"]);
		$peer_port_number = find_string("---port=", "---end", $sql_row["field_data"]);

		// Insert into database as first contact server(s)
		$sql = "INSERT INTO `active_peer_list` (`IP_Address` ,`domain` ,`subfolder` ,`port_number` ,`last_heartbeat`, `join_peer_list`, `failed_sent_heartbeat`)
		VALUES ('$peer_ip', '$peer_domain', '$peer_subfolder', '$peer_port_number', UNIX_TIMESTAMP(), UNIX_TIMESTAMP(), '0');";

		mysql_query($sql);
	}	
}

if($active_peers < $max_active_peers)
{
	//Start polling peers from the new peers list
	$sql = "SELECT * FROM `new_peers_list` ORDER BY RAND() LIMIT 10";
	$sql_result = mysql_query($sql);
	$sql_num_results = mysql_num_rows($sql_result);

	$my_server_domain = mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'server_domain' LIMIT 1"),0,"field_data");
	$my_server_subfolder = mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'server_subfolder' LIMIT 1"),0,"field_data");
	$my_server_port_number = mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'server_port_number' LIMIT 1"),0,"field_data");

	// Peer difference
	$peer_difference_count = $max_active_peers - $active_peers;

	for ($i = 0; $i < $sql_num_results; $i++)
	{
		$sql_row = mysql_fetch_array($sql_result);
		$ip_address = $sql_row["IP_Address"];
		$domain = $sql_row["domain"];
		$subfolder = $sql_row["subfolder"];
		$port_number = $sql_row["port_number"];
		$poll_failures = $sql_row["poll_failures"];

		// Check to make sure that this peer is not already in our active peer list
		$duplicate_check1 = mysql_result(mysql_query("SELECT * FROM `active_peer_list` WHERE `IP_Address` = '$ip_address' LIMIT 1"),0,"join_peer_list");
		$duplicate_check2 = mysql_result(mysql_query("SELECT * FROM `active_peer_list` WHERE `domain` LIKE '$domain' LIMIT 1"),0,"join_peer_list");

		if(empty($ip_address) == TRUE)
		{
			//Don't have an IP address, check for duplicate domain or my own domain
			if(empty($duplicate_check2) == TRUE && $my_server_domain != $domain)
			{
				// Neither IP nor Domain exist
				$duplicate_peer = FALSE;
			}
			else
			{
				$duplicate_peer = TRUE;
			}
		}
		else
		{
			// Check for non-private IP range
			if(is_private_ip($ip_address, $allow_lan_peers) == FALSE)
			{
				// Using IP only, is there a duplicate IP or Domain
				if(empty($duplicate_check1) == TRUE && empty($duplicate_check2) == TRUE)
				{
					$duplicate_peer = FALSE;
				}
				else
				{
					$duplicate_peer = TRUE;
				}
			}
			else
			{
				// Filter private IP ranges
				$duplicate_peer = TRUE;
			}
		}

		if($duplicate_peer == FALSE)
		{
			//Send a challenge hash to see if a timekoin server is active
			$poll_challenge = rand(1, 999999);
			$hash_solution = hash('crc32', $poll_challenge);

			if(empty($domain) == TRUE)
			{
				$site_address = $ip_address;
			}
			else
			{
				$site_address = $domain;
			}

			if($port_number == 443)
			{
				$ssl = "s";
			}
			else
			{
				$ssl = NULL;
			}

			//Use site address to poll
			$poll_peer = filter_sql(file_get_contents("http$ssl://$site_address:$port_number/$subfolder/peerlist.php?action=poll&challenge=$poll_challenge", FALSE, $context, NULL, 10));

			if($poll_peer == $hash_solution)
			{
				//Got a response from an active Timekoin server

				// Ask to be added to the other server's peerlist
				$poll_peer = filter_sql(file_get_contents("http$ssl://$site_address:$port_number/$subfolder/peerlist.php?action=join", FALSE, $context, NULL, 10));

				if($poll_peer == "OK")
				{
					// Add this peer to the active list
					$poll_peer = filter_sql(file_get_contents("http$ssl://$site_address:$port_number/$subfolder/peerlist.php?action=exchange&domain=$my_server_domain&subfolder=$my_server_subfolder&port_number=$my_server_port_number", FALSE, $context, NULL, 512));

					$exchange_status = find_string("-----status=", "-----domain", $poll_peer);

					if($exchange_status == "OK")
					{
						// Insert this peer into our active peer table
						$peer_domain = find_string("-----domain=", "-----subfolder", $poll_peer);
						$peer_subfolder = find_string("-----subfolder=", "-----port_number", $poll_peer);
						$peer_port_number = find_string("-----port_number=", "-----", $poll_peer);

						$peer_port_number = intval($peer_port_number);

						// Save only domain name if both IP and Domain exist
						if(empty($peer_domain) == FALSE)
						{
							$ip_address = NULL;
						}

						// Store new peer in active list
						$sql = "INSERT INTO `active_peer_list` (`IP_Address` ,`domain` ,`subfolder` ,`port_number` ,`last_heartbeat` ,`join_peer_list` ,`failed_sent_heartbeat`)
				VALUES ('$ip_address', '$peer_domain', '$peer_subfolder', '$peer_port_number', '" . time() . "', '" . time() . "', '0');";		

						if(mysql_query($sql) == TRUE)
						{
							// Subtract 1 from the peer difference count
							$peer_difference_count--;
						}
					}
					else if($exchange_status == "FULL")
					{
						// Server is full already
					}
				}
				else
				{
					// Server is either full or not responding, record polling failure
					$poll_failures++;

					$sql = "UPDATE `new_peers_list` SET `poll_failures` = '$poll_failures' WHERE `IP_Address` = '$ip_address' AND `domain` = '$domain' AND `subfolder` = '$subfolder' AND `port_number` = $port_number LIMIT 1";
					mysql_query($sql);
				}
			}
			else
			{
				//No response, record polling failure for future reference
				$poll_failures++;

				$sql = "UPDATE `new_peers_list` SET `poll_failures` = '$poll_failures' WHERE `IP_Address` = '$ip_address' AND `domain` = '$domain' AND `subfolder` = '$subfolder' AND `port_number` = $port_number LIMIT 1";
				mysql_query($sql);
			}

		} // End Duplicate Peer Check
		else
		{
			// Active response will remove poll failures
			if($poll_failures > 0)
			{
				$poll_failures--;

				$sql = "UPDATE `new_peers_list` SET `poll_failures` = '$poll_failures' WHERE `IP_Address` = '$ip_address' AND `domain` = '$domain' AND `subfolder` = '$subfolder' AND `port_number` = $port_number LIMIT 1";
				mysql_query($sql);
			}
		}

		// Clean up active peer list by removing those that have no responded for over 30 poll attempts
		if($poll_failures >= 30)
		{
			// Server has been offline too long, remove it from the active peers list
			$sql = "DELETE FROM `new_peers_list` WHERE `IP_Address` = '$ip_address' AND `domain` = '$domain' AND `subfolder` = '$subfolder' AND `port_number` = $port_number LIMIT 1";
			mysql_query($sql);
		}

		// Check to see if enough peers have been added
		if($peer_difference_count <= 0)
		{
			// Break out of loop
			break;
		}

	} // End For Loop

} // End Active vs Max Peer Check

//***********************************************************************************
//***********************************************************************************
// Add more peers to the new peers list to satisfy new peer limit

// How many new peers do we have?
$sql = "SELECT * FROM `new_peers_list`";
$new_peers_numbers = mysql_num_rows(mysql_query($sql));

if($new_peers_numbers < $max_new_peers && rand(1,3) == 2)//Randomize a little to avoid spamming for new peers
{
	$my_server_domain = mysql_result(mysql_query("SELECT * FROM `options` WHERE `field_name` = 'server_domain' LIMIT 1"),0,"field_data");

	// Add more possible peers to the new peer list by polling what the active peers have
	$sql = "SELECT * FROM `active_peer_list`";
	$sql_result = mysql_query($sql);
	$sql_num_results = mysql_num_rows($sql_result);

	$new_peer_difference = $max_new_peers - $new_peers_numbers;

	for ($i = 0; $i < $sql_num_results; $i++)
	{
		$sql_row = mysql_fetch_array($sql_result);
		
		$ip_address = $sql_row["IP_Address"];
		$domain = $sql_row["domain"];
		$subfolder = $sql_row["subfolder"];
		$port_number = $sql_row["port_number"];

		if(empty($domain) == TRUE)
		{
			$site_address = $ip_address;
		}
		else
		{
			$site_address = $domain;
		}

		if($port_number == 443)
		{
			$ssl = "s";
		}
		else
		{
			$ssl = NULL;
		}

		//Use site address name to poll
		$poll_peer = filter_sql(file_get_contents("http$ssl://$site_address:$port_number/$subfolder/peerlist.php?action=new_peers", FALSE, $context, NULL, 10000));

		$peer_counter = 1; // Reset peer counter

		while($peer_counter <= 15) // Max response is 15 peers at any one time
		{
			$peer_IP = NULL;
			$peer_domain = NULL;
			$peer_subfolder = NULL;
			$peer_port_number = NULL;
			
			// Sort Data
			$peer_IP = find_string("-----IP$peer_counter=", "-----domain$peer_counter", $poll_peer);
			$peer_domain = find_string("-----domain$peer_counter=", "-----subfolder$peer_counter", $poll_peer);
			$peer_subfolder = find_string("-----subfolder$peer_counter=", "-----port_number$peer_counter", $poll_peer);
			$peer_port_number = find_string("-----port_number$peer_counter=", "-----", $poll_peer);

			if(empty($peer_port_number) == TRUE && empty($peer_subfolder) == TRUE)
			{
				// No more peers, end this loop early
				break;
			}			

			// Check to make sure that this peer is not already in our new peer list
			$duplicate_check1 = mysql_result(mysql_query("SELECT * FROM `new_peers_list` WHERE `IP_Address` = '$peer_IP' LIMIT 1"),0,"port_number");
			$duplicate_check2 = mysql_result(mysql_query("SELECT * FROM `new_peers_list` WHERE `domain` LIKE '$peer_domain' LIMIT 1"),0,"port_number");

			if(empty($peer_IP) == TRUE)
			{
				//Don't have an IP address, check for duplicate domain
				if(empty($duplicate_check2) == TRUE)
				{
					if($my_server_domain == $peer_domain)
					{
						$duplicate_peer = TRUE;
					}
					else
					{
						// Neither IP nor Domain exist
						$duplicate_peer = FALSE;
					}
				}
				else
				{
					$duplicate_peer = TRUE;
				}
			}
			else
			{
				// Using IP only, is there a duplicate
				if(empty($duplicate_check1) == TRUE)
				{
					if($my_server_domain == $peer_domain || empty($duplicate_check2) == FALSE)
					{
						$duplicate_peer = TRUE;
					}
					else
					{
						// Check for non-private IP range
						if(is_private_ip($peer_IP, $allow_lan_peers) == FALSE)
						{
							// Neither IP nor Domain exist
							$duplicate_peer = FALSE;
						}
						else
						{
							$duplicate_peer = TRUE;
						}
					}
				}
				else
				{
					$duplicate_peer = TRUE;
				}
			}

			if($duplicate_peer == FALSE)
			{
				// Save only domain name if both IP and Domain exist
				if(empty($peer_domain) == FALSE)
				{
					$peer_IP = NULL;
				}				
				
				// This is a fresh new peer, add it to the database list
				$sql = "INSERT INTO `new_peers_list` (`IP_Address` ,`domain` ,`subfolder` ,`port_number` ,`poll_failures`)
		VALUES ('$peer_IP', '$peer_domain', '$peer_subfolder', '$peer_port_number', '0');";

				if(mysql_query($sql) == TRUE)
				{
					// Subtract one from total left to find
					$new_peer_difference--;
				}
			}

			if($new_peer_difference <= 0)
			{
				// Enough new peers saved, break out of while loop early
				break;
			}

			$peer_counter++;
		} // End While loop check

		if($new_peer_difference <= 0)
		{
			// Enough new peers saved, break out of for loop early
			break;
		}

	} // End For loop check

} // End New Peers vs Max New Peers check

//***********************************************************************************
//***********************************************************************************
// Send a heartbeat to all peers in our list to make sure they are still online
	$sql = "SELECT * FROM `active_peer_list`";

	$sql_result = mysql_query($sql);
	$sql_num_results = mysql_num_rows($sql_result);

	for ($i = 0; $i < $sql_num_results; $i++)
	{
		$sql_row = mysql_fetch_array($sql_result);

		$ip_address = $sql_row["IP_Address"];
		$domain = $sql_row["domain"];
		$subfolder = $sql_row["subfolder"];
		$port_number = $sql_row["port_number"];
		$last_heartbeat = $sql_row["last_heartbeat"];
		$join_peer_list = $sql_row["join_peer_list"];
		$failed_sent_heartbeat = $sql_row["failed_sent_heartbeat"];

		//Send a challenge hash to see if a timekoin server is active
		$poll_challenge = rand(1, 999999);
		$hash_solution = hash('crc32', $poll_challenge);

		if(empty($domain) == TRUE)
		{
			$site_address = $ip_address;
		}
		else
		{
			$site_address = $domain;
		}

		if($port_number == 443)
		{
			$ssl = "s";
		}
		else
		{
			$ssl = NULL;
		}

		if(rand(1,3) == 2)// Randomize to avoid spamming
		{
			//Send out poll request
			$poll_peer = filter_sql(file_get_contents("http$ssl://$site_address:$port_number/$subfolder/peerlist.php?action=poll&challenge=$poll_challenge", FALSE, $context, NULL, 10));

			if($poll_peer == $hash_solution)
			{
				//Got a response from an active Timekoin server
				$sql = "UPDATE `active_peer_list` SET `last_heartbeat` = '" . time() . "' WHERE `IP_Address` = '$ip_address' AND `domain` = '$domain' AND `subfolder` = '$subfolder' AND `port_number` = $port_number LIMIT 1";
				mysql_query($sql);
			}		
			else
			{
				//No response, record polling failure for future reference
				$failed_sent_heartbeat++;

				$sql = "UPDATE `active_peer_list` SET `failed_sent_heartbeat` = '$failed_sent_heartbeat' WHERE `IP_Address` = '$ip_address' AND `domain` = '$domain' AND `subfolder` = '$subfolder' AND `port_number` = $port_number LIMIT 1";
				mysql_query($sql);
			}
		}

		// Clean up active peer list by removing those that have no responded for over 5 minutes
		if((time() - $last_heartbeat) > 300 && $join_peer_list != 0)
		{
			// Server has been offline too long, remove it from the active peers list
			$sql = "DELETE FROM `active_peer_list` WHERE `IP_Address` = '$ip_address' AND `domain` = '$domain' AND `subfolder` = '$subfolder' AND `port_number` = $port_number AND `join_peer_list` = $join_peer_list LIMIT 1";
			mysql_query($sql);
		}

	} // End for Loop
//***********************************************************************************
//***********************************************************************************
// Script finished, set status to 0
$sql = "UPDATE `main_loop_status` SET `field_data` = '0' WHERE `main_loop_status`.`field_name` = 'peerlist_heartbeat_active' LIMIT 1";
mysql_query($sql);

// Record when this script finished
$sql = "UPDATE `main_loop_status` SET `field_data` = '" . time() . "' WHERE `main_loop_status`.`field_name` = 'peerlist_last_heartbeat' LIMIT 1";
mysql_query($sql);

?>
Back to Top