pingPublicPeers 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/env php
  2. <?php
  3. define('FNAME', 'publicPeers.json');
  4. define('CACHE', 3600); // COMMENT: cache time in seconds for ping
  5. // clone or update peers repo
  6. if (file_exists('peers'))
  7. passthru('cd peers; git pull; cd ..');
  8. else
  9. passthru('git clone "https://github.com/hyperboria/peers.git"');
  10. // get peers and ping
  11. require_once 'publicKey2ipv6.php';
  12. $data = json_decode(@file_get_contents(FNAME), true);
  13. if (!$data) $data = [];
  14. foreach(get_files('peers') as $fname)
  15. {
  16. $st = file_get_contents($fname);
  17. parse($st);
  18. }
  19. function get_files($dir)
  20. {
  21. ob_start();
  22. passthru("find $dir | grep '\.k'");
  23. $st = ob_get_clean();
  24. return explode("\n", trim($st));
  25. }
  26. function parse($st)
  27. {
  28. global $data;
  29. $a = json_decode($st, true);
  30. foreach ($a as $k => $a)
  31. if (time() - @$data[$k]['updated'] > CACHE)
  32. {
  33. $ip = publicKey2ipv6($a['publicKey']);
  34. echo "Ping $ip... ";
  35. exec("ping -c3 -6 -W5 $ip", $out, $res);
  36. $res = $res === 0 ? true : false;
  37. echo $res ? '[ OK ]' : '[FAIL]';
  38. echo "\n";
  39. update($k, $a, $res);
  40. }
  41. }
  42. function update($k, $a, $res)
  43. {
  44. global $data;
  45. $a['updated'] = time();
  46. if ($res) $a['lastseen'] = time();
  47. $data[$k] = $a;
  48. $st = json_encode($data);
  49. $st = str_replace('},"', "},\n\"", $st);
  50. if ($st)
  51. file_put_contents(FNAME, $st);
  52. }