private function connect()
{
if ($this->socket !== false) {
// we are in persistent connection mode, so we have a socket
// however, need to check whether it's still alive
if (!@feof($this->socket)) {
return $this->socket;
}
// force reopen
$this->socket = false;
}
$errno = 0;
$errstr = '';
$this->connerror = false;
if ($this->path) {
$host = $this->path;
$port = 0;
} else {
$host = $this->host;
$port = $this->port;
}
if ($this->timeout <= 0) {
$fp = @fsockopen($host, $port, $errno, $errstr);
} else {
$fp = @fsockopen($host, $port, $errno, $errstr, $this->timeout);
}
if (!$fp) {
if ($this->path) {
$location = $this->path;
} else {
$location = $this->host . ':' . $this->port;
}
$errstr = trim($errstr);
$this->error = sprintf('connection to %s failed (errno=%d, msg=%s)', $location, $errno, $errstr);
$this->connerror = true;
return false;
}
// send client version
// this is a subtle part. we must do it before (!) reading back from searchd.
// because otherwise under some conditions (reported on FreeBSD for instance)
// TCP stack could throttle write-write-read pattern because of Nagle.
if (!$this->send($fp, pack('N', 1), 4)) {
fclose($fp);
$this->error = 'failed to send client protocol version';
return false;
}
// check version
list(, $v) = unpack('N*', fread($fp, 4));
$v = (int) $v;
if ($v < 1) {
fclose($fp);
$this->error = sprintf('expected searchd protocol version 1+, got version \'%d\'', $v);
return false;
}
return $fp;
}