Skip to content

Add exception support for handling errors #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 39 additions & 6 deletions src/clamd.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,23 @@
$EICAR_TEST = 'X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*';


class ClamdSocketException extends Exception {
protected $errorCode;

public function __construct($message, $socketErrorCode) {
$this->errorCode = $socketErrorCode;
if (!$message) {
$message = socket_strerror($this->errorCode);
}
parent::__construct($message);
}

/* Get socket error (returned from 'socket_last_error') */
public function getErrorCode() {
return $this->errorCode;
}
}

/* An abstract class that `ClamdPipe` and `ClamdNetwork` will inherit. */
abstract class ClamdBase {

Expand Down Expand Up @@ -107,8 +124,20 @@ public function __construct($pip=CLAMD_PIPE) {
}

protected function getSocket() {
$socket = socket_create(AF_UNIX, SOCK_STREAM, 0);
socket_connect($socket, $this->pip);
$socket = @socket_create(AF_UNIX, SOCK_STREAM, 0);
if ($socket === FALSE) {
throw new ClamdSocketException('', socket_last_error());
}
$hasError = @socket_connect($socket, $this->pip);
if ($hasError === FALSE) {
$errorCode = socket_last_error();
$errorMessage = socket_strerror($errorCode);
if ($errorCode === 2) {
// ie. `No such file or directory "/var/run/clamav/clamd.ctl"`
$errorMessage .= ' "'.$this->pip.'", Is clamd running and are your user/group permissions configured properly?';
}
throw new ClamdSocketException($errorMessage, $errorCode);
}
return $socket;
}
}
Expand All @@ -126,10 +155,14 @@ public function __construct($host=CLAMD_HOST, $port=CLAMD_PORT) {
}

protected function getSocket() {
$socket = socket_create(AF_INET, SOCK_STREAM, 0);
socket_connect($socket, $this->host, $this->port);
$socket = @socket_create(AF_INET, SOCK_STREAM, 0);
if ($socket === FALSE) {
throw new ClamdSocketException('', socket_last_error());
}
$hasError = @socket_connect($socket, $this->host, $this->port);
if ($hasError === FALSE) {
throw new ClamdSocketException('', socket_last_error());
}
return $socket;
}
}

?>