Browse Source

php for web server

master
kanoi 11 years ago
parent
commit
c6d9e0b8b3
  1. 269
      pool/base.php
  2. 127
      pool/db.php
  3. 62
      pool/index.php
  4. 351
      pool/page.php
  5. 13
      pool/page_help.php
  6. 17
      pool/page_index.php
  7. 43
      pool/page_payments.php
  8. 128
      pool/page_reg.php
  9. 30
      pool/param.php
  10. 163
      pool/socket.php

269
pool/base.php

@ -0,0 +1,269 @@
<?php
#
include_once('page.php');
#
global $dbg, $dbgstr;
$dbg = false;
$dbgstr = '';
#
function adddbg($str)
{
global $dbg, $dbgstr;
if ($dbg === true)
{
if ($dbgstr != '')
$dbgstr .= "\n";
$dbgstr .= $str;
}
}
#
function btcfmt($amt)
{
$amt /= 100000000;
return number_format($amt, 8);
}
#
function emailStr($str)
{
$all = '/[^A-Za-z0-9_+\.@-]/'; // no space = trim
$beg = '/^[\.@+-]+/';
$fin = '/[\.@+_-]+$/';
return preg_replace(array($all,$beg,$fin), '', $str);
}
#
function loginStr($str)
{
$all = '/[^!-~]/'; // no spaces
return preg_replace($all, '', $str);
}
#
function trn($str)
{
$rep = str_replace(array('<', '>'), array('&lt;', '&gt;'), $str);
return $rep;
}
#
function htmler($str)
{
$srch = array('<','>',"\r\n","\n","\r");
$rep = array('&lt;','&gt;','<br>','<br>','<br>');
return str_replace($srch, $rep, $str);
}
#
function cvtdbg()
{
global $dbg, $dbgstr;
if ($dbg === false || $dbgstr == '')
$rep = '';
else
$rep = htmler($dbgstr).'<br>';
return $rep;
}
#
function safeinput($txt, $len = 1024, $lf = true)
{
$ret = trim($txt);
if ($ret != '')
{
if ($lf === true)
$ret = preg_replace("/[^ -~\r\n]/", '', $ret);
else
$ret = preg_replace('/[^ -~]/', '', $ret);
if ($len > 0)
$ret = substr($ret, 0, $len);
}
return trim($ret);
}
#
function safetext($txt, $len = 1024)
{
$tmp = substr($txt, 0, $len);
$res = '';
for ($i = 0; $i < strlen($tmp); $i++)
{
$ch = substr($tmp, $i, 1);
if ($ch >= ' ' && $ch <= '~')
$res .= $ch;
else
{
$c = ord($ch);
$res .= sprintf('0x%02x', $c);
}
}
if (strlen($txt) > $len)
$res .= '...';
return $res;
}
#
function dbd($data)
{
return "<font color=red size=+10><br>Web site is currently down</font>";
}
#
function dbdown()
{
gopage(NULL, 'dbd', NULL, '', true, false);
}
#
function f404($data)
{
return "<font color=red size=+10><br>404</font>";
}
#
function do404()
{
gopage(NULL, 'f404', NULL, '', true, false);
}
#
function showPage($page, $menu, $name)
{
# If you are doing development, use without '@'
# Then switch to '@' when finished
# @include_once("page_$page.php");
include_once("page_$page.php");
$fun = 'show_' . $page;
if (function_exists($fun))
$fun($menu, $name);
else
do404();
}
#
function showIndex()
{
showPage('index', NULL, '');
}
#
function offline()
{
if (file_exists('./maintenance.txt'))
{
$ip = $_SERVER['REMOTE_ADDR'];
if ($ip != '192.168.7.74')
gopage(NULL, file_get_contents('./maintenance.txt'), NULL, '', false, false);
}
}
#
offline();
#
session_start();
#
include_once('db.php');
#
function validUserPass($user, $pass)
{
$rep = checkpass($user, $pass);
$ans = repDecode($rep);
usleep(100000); // Max 10x per second
if ($ans['STATUS'] == 'ok')
{
$key = 'ckp'.rand(1000000,9999999);
$_SESSION['ckpkey'] = $key;
$_SESSION[$key] = array('who' => $user, 'id' => $user);
}
}
#
function logout()
{
if (isset($_SESSION['ckpkey']))
{
$key = $_SESSION['ckpkey'];
if (isset($_SESSION[$key]))
unset($_SESSION[$key]);
unset($_SESSION['ckpkey']);
}
}
#
function requestRegister()
{
$reg = getparam('Register', false);
if ($reg !== NULL)
{
logout();
return true;
}
return false;
}
#
function tryLogInOut()
{
// If already logged in, it will ignore User/Pass
if (isset($_SESSION['ckpkey']))
{
$logout = getparam('Logout', false);
if (!nuem($logout) && $logout == 'Logout')
logout();
}
else
{
$user = getparam('User', false);
if ($user !== NULL)
$user = loginStr($user);
if (nuem($user))
return;
$pass = getparam('Pass', false);
if (nuem($pass))
return;
$login = getparam('Login', false);
if (nuem($login))
return;
validUserPass($user, $pass);
}
}
#
function validate()
{
$who = '';
$whoid = '';
if (!isset($_SESSION['ckpkey']))
return false;
$key = $_SESSION['ckpkey'];
if (!isset($_SESSION[$key]))
{
logout();
return array(false, NULL);
}
if (!isset($_SESSION[$key]['who']))
{
logout();
return array(false, NULL);
}
$who = $_SESSION[$key]['who'];
if (!isset($_SESSION[$key]['id']))
{
logout();
return array(false, NULL);
}
$whoid = $_SESSION[$key]['id'];
return array($who, $whoid);
}
#
function loggedIn()
{
list($who, $whoid) = validate();
if ($who == false)
return false;
return true;
}
#
?>

127
pool/db.php

@ -0,0 +1,127 @@
<?php
#
include_once('socket.php');
include_once('base.php');
#
global $send_sep, $fld_sep, $val_sep;
$send_sep = '.';
$fld_sep = Chr(0x2);
$val_sep = '=';
#
function myhash($str)
{
return strtolower(hash('sha256', $str));
}
#
function repDecode($rep)
{
global $send_sep, $fld_sep, $val_sep;
$fix = preg_replace("/[\n\r]*$/",'',$rep);
$major = explode($send_sep, $fix, 4);
if (count($major) < 3)
return false;
$ans = array();
if (count($major) > 3)
{
$flds = explode($fld_sep, $major[3]);
foreach ($flds as $fld)
{
if (strlen($fld) > 0)
{
$nameval = explode($val_sep, $fld, 2);
if (count($nameval) > 1)
$ans[$nameval[0]] = $nameval[1];
else
$ans[$nameval[0]] = '';
}
}
}
$ans['ID'] = $major[0];
$ans['STAMP'] = $major[1];
$ans['STATUS'] = $major[2];
return $ans;
}
#
function msgEncode($id, $cmd, $fields)
{
global $send_sep, $fld_sep, $val_sep;
$msg = $id . $send_sep . $cmd;
$first = true;
foreach ($fields as $name => $value)
{
if ($first === true)
{
$msg .= $send_sep;
$first = false;
}
else
$msg .= $fld_sep;
$msg .= $name . $val_sep . $value;
}
return $msg;
}
#
function getStats($user)
{
global $fld_sep;
if ($user === null)
$msg = "s$fld_sep";
else
$msg = "s$fld_sep$user";
return $msg;
}
#
function homeInfo($user)
{
$msg = getStats($user);
/*
$rep = sendsockreply('homeInfo', $msg);
if ($rep === false)
$ans = false;
else
$ans = repDecode($rep);
return $ans;
*/
if ($user !== null)
$uhr = rand(500, 2500);
else
$uhr = 0;
$plb = 1401237522;
$nlb = time() - rand(200,500);
return array('PoolHashRate' => '250', 'PoolLastBlock' => "$plb", 'NetLastBlock' => "$nlb", 'UserHashRate' => "$uhr");
}
#
function checkpass($user, $pass)
{
$passhash = myhash($pass);
$flds = array('username' => $user, 'passwordhash' => $passhash);
$msg = msgEncode('log', 'chkpass', $flds);
$rep = sendsockreply('checkpass', $msg);
if (!$rep)
dbdown();
return $rep;
}
#
function getpayments()
{
list($who, $whoid) = validate();
if ($who == false)
showIndex();
$flds = array('username' => $who);
$msg = msgEncode('pay', 'payments', $flds);
$rep = sendsockreply('getpayments', $msg);
if (!$rep)
dbdown();
return $rep;
}
?>

62
pool/index.php

@ -0,0 +1,62 @@
<?php
#
include_once('param.php');
include_once('base.php');
#
function process($p)
{
$menu = array(
'Home' => array(
'Home' => ''
),
'Account' => array(
'Workers' => 'workers',
'Payments' => 'payments',
'Settings' => 'settings'
),
'Pool' => array(
'Stats' => 'stats'
),
'gap' => NULL,
'Help' => array(
'Help' => 'help'
)
);
$page = '';
$n = '';
foreach ($menu as $item => $options)
if ($options !== NULL)
foreach ($options as $name => $pagename)
if ($pagename === $p)
{
$page = $p;
$n = " - $name";
}
if ($page === '')
showPage('index', $menu, '');
else
showPage($page, $menu, $n);
}
#
function check()
{
tryLogInOut();
$in = loggedIn();
if ($in == false)
{
if (requestRegister() == true)
showPage('reg', NULL, '');
else
showIndex();
}
else
{
$p = getparam('k', true);
process($p);
}
}
#
check();
#
?>

351
pool/page.php

@ -0,0 +1,351 @@
<?php
#
global $site_title;
global $page_title;
global $page_scripts;
#
$site_title = 'CKPool';
$page_title = $site_title;
$page_scripts = '';
#
global $dont_trm;
$dont_trm = false;
#
// work out the page from ?k=page
function getPage()
{
$uri = $_SERVER["REQUEST_URI"];
$names = explode('k=', trim($uri));
if (count($names) < 2)
return '';
$vals = explode('&', trim($names[1]));
if ($count($vals) < 1)
return '';
return trim($vals[0]);
}
#
function addScript($script)
{
global $page_scripts;
if ($script != null and trim($script) != '')
{
if ($page_scripts == '')
$page_scripts = "<script type='text/javascript'><!--\n";
$page_scripts .= trim($script);
}
}
#
function makeLink($page, $rest = '')
{
if ($page != '')
$page = '?k='.$page;
$href = "<a href='index.php$page'";
if ($rest != '')
$href .= " $rest";
$href .= '>';
return $href;
}
#
function dotrm($html, $dontdoit)
{
if ($dontdoit === true)
return $html;
else
return preg_replace('/ *\n */', '', $html);
}
#
function trm($html)
{
global $dont_trm;
return dotrm($html, $dont_trm);
}
#
function trm_force($html)
{
return dotrm($html, false);
}
#
function pghead($script_marker, $name)
{
global $page_title;
$head = "<!DOCTYPE html>\n";
$head .= "<html><head><title>$page_title$name</title><meta content='text/html; charset=iso-8859-1' http-equiv='Content-Type'>";
$head .= "<style type='text/css'>
form {display: inline-block;}
html, body {height: 100%; font-family:Arial, Verdana, sans-serif; font-size:12pt; background-color:#eff; text-align: center;}
.page {min-height: 100%; height: auto !important; height: 100%; margin: 0 auto -50px; position: relative;}
div.jst {color:red; background-color: #ffa; font-weight: font-size: 8; bold; border-style: solid; border-width: 2px; vertical-align: top;}
div.topd {background-color:#cff; border-color: #cff; border-style: solid; border-width: 9px;}
span.topdes {color:blue;}
span.topwho {color:black; font-weight: bold; margin-right: 8px;}
span.topdat {margin-left: 8px; margin-right: 24px; color:green; font-weight: bold;}
span.login {float: right; margin-left: 8px; margin-right: 24px;}
#n42 {margin:0; position: relative; color:#fff; background:#07e;}
#n42 a {color:#fff; text-decoration:none; margin: 4px;}
#n42 td {min-width: 100px; float: left; vertical-align: top; padding: 2px;}
#n42 td.navboxr {float: right;}
#n42 td.nav {position: relative;}
#n42 div.sub {left: 0px; z-index: 42; position: absolute; visibility: hidden;}
#n42 td.ts {border-width: 1px; border-color: #02e; border-style: solid none none none;}
#n42 td.nav:hover {background:#09e;}
#n42 td.nav:hover div.sub {background:#07e; visibility: visible;}
h1 {margin-top: 20px; float:middle; font-size: 20px;}
.foot, .push {height: 50px; font-size: 10pt;}
.title {background-color: #909090;}
.even {background-color: #cccccc;}
.odd {background-color: #a8a8a8;}
.dl {text-align: left; padding: 2px 8px;}
.dr {text-align: right; padding: 2px 8px;}
.dc {text-align: center; padding: 2px 8px;}
</style>\n";
$head .= '<meta name="robots" content="noindex">';
$head .= $script_marker; // where to put the scripts
$head .= '</head>';
return $head;
}
#
function pgtop($dotop, $user, $douser)
{
global $site_title;
$info = homeInfo($user);
$phr = '&nbsp;';
$plb = '&nbsp;';
$nlb = '&nbsp;';
$uhr = '&nbsp;';
if ($info !== false)
{
$now = time();
if (isset($info['PoolHashRate']))
$phr = $info['PoolHashRate'].'TH/s';
if (isset($info['PoolLastBlock']))
{
$sec = $now - $info['PoolLastBlock'];
if ($sec < 60)
$plb = $sec.'s';
else
{
if ($sec < 3600)
{
$min = round($sec / 60);
$plb = $min.'m';
}
else
{
$min = round(($sec % 3600) / 60);
$hr = round($sec / 3600);
$plb = $hr.'h';
if ($min != 0)
$plb .= ' '.$min.'m';
}
}
}
if (isset($info['NetLastBlock']))
{
$sec = $now - $info['NetLastBlock'];
$min = round($sec / 60);
$nlb = $min.'m';
}
if (isset($info['UserHashRate']))
{
$uhr = $info['UserHashRate'];
if ($uhr < 1000)
$uhr .= 'GHs';
else
$uhr = (round($uhr/10)/100).'THs';
}
}
addscript("function jst(){document.getElementById('jst').style.visibility='hidden';}");
$top = "<div class=jst id=jst>&nbsp;Javascript isn't enabled.";
$top .= " You need to enable javascript to use";
$top .= " the $site_title web site.</div>";
$top .= '<div class=topd>';
if ($dotop === true)
{
$top .= '<span class=topdes>CKPool:</span>';
$top .= "<span class=topdat>$phr</span>";
$top .= '<span class=topdes>Pool, Last Block:</span>';
$top .= "<span class=topdat>$plb</span>";
$top .= '<span class=topdes>Network, Last Block:</span>';
$top .= "<span class=topdat>$nlb</span>";
if ($douser === true)
{
$top .= '<span class=login>';
list($who, $whoid) = validate();
if ($who == false)
{
$top .= "
<form action=index.php method=POST>
User: <input type=text name=User size=10 value=''>
Pass: <input type=password name=Pass size=10 value=''>
&nbsp;<input type=submit name=Login value=Login>
&nbsp;<input type=submit name=Register value=Register>
</form>";
}
else
{
$top .= "
<span class=topwho>$who&nbsp;</span>
<span class=topdes>Hash Rate:</span>
<span class=topdat>$uhr</span>
<form action=index.php method=POST>
&nbsp;<input type=submit name=Logout value=Logout>
</form>";
}
$top .= '</span>';
}
}
else
$top .= '&nbsp;';
$top .= '</div>';
return $top;
}
#
function pgmenu($menus)
{
if ($menus == NULL)
$menus = array('Home'=>array('Home'=>''));
// $menus = array('Home'=>array('Home'=>''),'gap'=>NULL,'Help'=>array('Help'=>'help'));
$ret = "\n<table cellpadding=0 cellspacing=0 border=0 width=100% id=n42>";
$ret .= '<tr><td width=100%>';
$ret .= '<table cellpadding=0 cellspacing=0 border=0 width=100%>';
$ret .= '<tr>';
$side = '';
foreach ($menus as $menu => $submenus)
{
if ($menu == 'gap')
{
$side = 'r';
continue;
}
$ret .= "<td class=navbox$side><table cellpadding=0 cellspacing=0 border=0>";
$first = true;
foreach ($submenus as $submenu => $item)
{
if ($first == true)
{
$first = false;
if ($submenu == $menu)
{
$ret .= "<tr><td class=nav>".makeLink($item)."$menu</a>";
$ret .= '<div class=sub><table cellpadding=0 cellspacing=0 border=0 width=100%>';
continue;
}
$ret .= "<tr><td class=nav><a>$menu</a>";
$ret .= '<div class=sub><table cellpadding=0 cellspacing=0 border=0 width=100%>';
}
$ret .= "<tr><td class=ts>".makeLink($item,'class=as')."$submenu</a></td></tr>";
}
$ret .= '</table></div></td></tr></table></td>';
}
$ret .= "</tr></table></td></tr></table>\n";
return $ret;
}
#
function pgbody($menu, $dotop, $user, $douser)
{
$body = '<body onload="jst()">';
$body .= '<div class=page>';
$body .= '<table border=0 cellpadding=0 cellspacing=0 width=100%>';
$body .= '<tr><td><center>';
$body .= '<table border=0 cellpadding=0 cellspacing=0 width=94%>';
$body .= '<tr><td>';
$body .= pgtop($dotop, $user, $douser);
$body .= '</td></tr>';
$body .= '<tr><td>';
$body .= pgmenu($menu);
$body .= '</td></tr>';
$body .= '<tr><td><div align=center>';
return $body;
}
#
function pgfoot()
{
$foot = '</div></td></tr>';
$foot .= '</table>';
$foot .= '</center></td></tr>';
$foot .= '</table>';
$foot .= '<div class=push></div></div>';
$foot .= '<div class=foot><br>Copyright &copy; Kano 2014';
$now = date('Y');
if ($now != '2014')
$foot .= "-$now";
$foot .= '</div>';
$foot .= "</body></html>\n";
return $foot;
}
#
function gopage($data, $page, $menu, $name, $ispage = true, $dotop = true, $douser = true)
{
global $dbg;
global $page_scripts;
$dbg_marker = '[@dbg@]';
$script_marker = '[@scripts@]';
if ($dbg === true)
$pg = $dbg_marker.'<br>';
else
$pg = '';
if ($ispage == true)
$pg .= $page($data);
else
$pg .= $page;
// if (isset($_SESSION['logkey']))
// unset($_SESSION['logkey']);
$head = pghead($script_marker, $name);
$body = pgbody($menu, $dotop, $name, $douser);
$foot = pgfoot();
if ($dbg === true)
$pg = str_replace($dbg_marker, cvtdbg(), $pg);
if ($page_scripts != '')
$page_scripts .= "//-->\n</script>";
$head = str_replace($script_marker, $page_scripts, $head);
$all = $head;
$all .= trm_force($body);
$all .= trm($pg);
$all .= trm_force($foot);
usleep(100000);
echo $all;
exit(0);
}
?>

13
pool/page_help.php

@ -0,0 +1,13 @@
<?php
#
function dohelp($data)
{
return '<h1>Helpless</h1>Helpless';
}
#
function show_help($menu, $name)
{
gopage(NULL, 'dohelp', $menu, $name);
}
#
?>

17
pool/page_index.php

@ -0,0 +1,17 @@
<?php
#
function doindex($data)
{
$pg = '
<h1>CKPool</h1>
Welcome to CKPool the bestest mostest gnarliest poolest in the ...... south.
';
return $pg;
}
#
function show_index($menu, $name)
{
gopage(NULL, 'doindex', $menu, $name);
}
#
?>

43
pool/page_payments.php

@ -0,0 +1,43 @@
<?php
#
function dopayments($data)
{
$pg = '<h1>Payments</h1>';
$rep = getPayments();
$ans = repDecode($rep);
$pg .= "<table callpadding=0 cellspacing=0 border=0>\n";
$pg .= "<tr class=title>";
$pg .= "<td class=dl>Date</td>";
$pg .= "<td class=dl>Address</td>";
$pg .= "<td class=dr>BTC</td>";
$pg .= "</tr>\n";
if ($ans['STATUS'] == 'ok')
{
$count = $ans['rows'];
for ($i = 0; $i < $count; $i++)
{
if (($i % 2) == 0)
$row = 'even';
else
$row = 'odd';
$pg .= "<tr class=$row>";
$pg .= '<td class=dl>'.$ans['paydate'.$i].'</td>';
$pg .= '<td class=dl>'.$ans['payaddress'.$i].'</td>';
$pg .= '<td class=dr>'.btcfmt($ans['amount'.$i]).'</td>';
$pg .= "</tr>\n";
}
}
$pg .= "</table>\n";
return $pg;
}
#
function show_payments($menu, $name)
{
gopage(NULL, 'dopayments', $menu, $name);
}
#
?>

128
pool/page_reg.php

@ -0,0 +1,128 @@
<?php
#
include_once('socket.php');
#
function doreg($data)
{
if (isset($data['user']))
$user = htmlspecialchars($data['user']);
else
$user = '';
if (isset($data['mail']))
$mail = htmlspecialchars($data['mail']);
else
$mail = '';
$pg = '<h1>Register</h1>';
if (isset($data['error']))
$pg .= "<br><b>".$data['error']." - please try again</b><br><br>";
$pg .= "
<form action=index.php method=POST>
<table>
<tr><td class=dr>Username:</td>
<td class=dl><input name=user value=\"$user\"></td></tr>
<tr><td class=dr>Email:</td>
<td class=dl><input name=mail value=\"$mail\"></td></tr>
<tr><td class=dr>Password:</td>
<td class=dl><input type=password name=pass></td></tr>
<tr><td class=dr>Retype Password:</td>
<td class=dl><input type=password name=pass2></td></tr>
<tr><td>&nbsp;</td>
<td class=dl><input type=submit name=Register value=Register></td></tr>
<tr><td colspan=2 class=dc><br><font size=-1>All fields are required</font></td></tr>
</table>
</form>";
return $pg;
}
#
function doreg2($data)
{
$pg = '<h1>Registered</h1>';
$pg .= '<br>You will receive an email shortly to verify your account';
return $pg;
}
#
function safepass($pass)
{
if (strlen($pass) < 6)
return false;
# Invalid characters
$p2 = preg_replace('/[^ -~]/', '', $pass);
if ($p2 != $pass)
return false;
# At least one lowercase
$p2 = preg_replace('/[a-z]/', '', $pass);
if ($p2 == $pass)
return false;
# At least one uppercase
$p2 = preg_replace('/[A-Z]/', '', $pass);
if ($p2 == $pass)
return false;
# At least one digit
$p2 = preg_replace('/[0-9]/', '', $pass);
if ($p2 == $pass)
return false;
return true;
}
#
function show_reg($menu, $name)
{
$user = getparam('user', false);
$mail = getparam('mail', false);
$pass = getparam('pass', false);
$pass2 = getparam('pass2', false);
$data = array();
$ok = true;
if ($user === NULL && $mail === NULL && $pass === NULL && $pass2 === NULL)
$ok = false;
else
{
if ($user !== NULL)
$data['user'] = $user;
else
$ok = false;
if ($mail !== NULL)
$data['mail'] = $mail;
else
$ok = false;
if ($pass === NULL || safepass($pass) !== true)
{
$ok = false;
$data['error'] = "Password is unsafe";
} elseif ($pass2 === NULL || $pass2 != $pass)
{
$ok = false;
$data['error'] = "Passwords don't match";
}
}
if ($ok === true)
{
$passhash = myhash($pass);
$flds = array('username' => $user,
'emailaddress' => $mail,
'passwordhash' => $passhash);
$msg = msgEncode('reg', 'adduser', $flds);
$rep = sendsockreply('show_reg', $msg);
if (!$rep)
dbdown();
$ans = repDecode($rep);
if ($ans['STATUS'] == 'added')
gopage($data, 'doreg2', $menu, $name, true, true, false);
else
$data['error'] = "Invalid details";
}
gopage($data, 'doreg', $menu, $name, true, true, false);
}
#
?>

30
pool/param.php

@ -0,0 +1,30 @@
<?php
#
function nuem($str)
{
if (($str === null) or $str == '')
return true;
else
return false;
}
#
function getparam($name, $both)
{
$a = null;
if (isset($_POST[$name]))
$a = $_POST[$name];
if (($both === true) and ($a === null))
{
if (isset($_GET[$name]))
$a = $_GET[$name];
}
if ($a == '' || $a == null)
return null;
// limit to 1K just to be sure
return substr($a, 0, 1024);
}
#
?>

163
pool/socket.php

@ -0,0 +1,163 @@
<?php
#
# Note that $port in AF_UNIX should be the socket filename
function _getsock($fun, $port, $unix=true)
{
$socket = null;
if ($unix === true)
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
else
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false || $socket === null)
{
$sockerr = socket_strerror(socket_last_error());
$msg = "$fun() _getsock() create($port) failed";
error_log("CKPERR: $msg '$sockerr'");
return false;
}
if ($unix === true)
$res = socket_connect($socket, $port, NULL);
else
$res = socket_connect($socket, '127.0.0.1', $port);
if ($res === false)
{
// try 3x
if ($unix === true)
$res = socket_connect($socket, $port);
else
{
sleep(2);
$res = socket_connect($socket, '127.0.0.1', $port);
}
if ($res === false)
{
if ($unix === true)
$res = socket_connect($socket, $port);
else
{
sleep(5);
$res = socket_connect($socket, '127.0.0.1', $port);
}
if ($res === false)
{
$sockerr = socket_strerror(socket_last_error());
if ($unix === true)
$msg = "$fun() _getsock() connect($port) failed 3x";
else
$msg = "$fun() _getsock() connect($port) failed 3x (+2+5s sleep)";
error_log("CKPERR: $msg '$sockerr'");
socket_close($socket);
return false;
}
}
}
return $socket;
}
#
function getsock($fun)
{
return _getsock($fun, '/opt/ckdb/listener');
}
#
function readsockline($fun, $socket)
{
$siz = socket_read($socket, 4);
if ($siz === false)
{
$sockerr = socket_strerror(socket_last_error());
$msg = "$fun() readsockline() failed";
error_log("CKPERR: $msg '$sockerr'");
return false;
}
if (strlen($siz) != 4)
{
$msg = "$fun() readsockline() short read $siz vs ".strlen($siz);
error_log("CKPERR: $msg");
return false;
}
$len = ord($siz[0]) + ord($siz[1])*256 +
ord($siz[2])*65536 + ord($siz[3])*16777216;
$line = socket_read($socket, $len);
if ($line === false)
{
$sockerr = socket_strerror(socket_last_error());
$msg = "$fun() readsockline() failed";
error_log("CKPERR: $msg '$sockerr'");
return false;
}
else
if (strlen($line) != $len)
{
$msg = "$fun() readsockline() incomplete ($len)";
error_log("CKPERR: $msg '$line'");
return false;
}
return $line;
}
#
function dosend($fun, $socket, $msg)
{
$msg .= "\n";
$len = strlen($msg);
$sen = $len;
$siz = chr($sen % 256);
$sen = $sen >> 8;
$siz .= chr($sen % 256);
$sen = $sen >> 8;
$siz .= chr($sen % 256);
$sen = $sen >> 8;
$siz .= chr($sen % 256);
$msg = $siz . $msg;
$left = $len + 4;
while ($left > 0)
{
$res = socket_write($socket, substr($msg, 0 - $left), $left);
if ($res === false)
{
$sockerr = socket_strerror(socket_last_error());
$msg = "$fun() sendsock() failed";
error_log("CKPERR: $msg '$sockerr'");
break;
}
else
$left -= $res;
}
if ($left == 0)
$ret = true;
return $ret;
}
#
function sendsock($fun, $msg)
{
$ret = false;
$socket = getsock($fun);
if ($socket !== false)
{
$ret = dosend($fun, $socket, $msg);
socket_close($socket);
}
return $ret;
}
#
function sendsockreply($fun, $msg)
{
$ret = false;
$socket = getsock($fun);
if ($socket !== false)
{
$ret = dosend($fun, $socket, $msg);
if ($ret !== false)
$ret = readsockline($fun, $socket);
socket_close($socket);
}
return $ret;
}
#
?>
Loading…
Cancel
Save