Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault on fopen using sftp and ssh2

I have a php system running on AWS and a class that upload a xlsx file on external server using shh2 and sftp. This code worked fine until last upgrade of aws package openssh-clients-6.6.1p1-31.62 and openssh-server-6.6.1p1-31.62 by this time I have a segfault during fopen. Fopen create a file on external server. Here the code:

$stream = @fopen("ssh2.sftp://$this->sftp$remote_file", 'w');

Then I use $stream to write the content, but the code stop on fopen bacause a segfault. I don't find anything about this problem, I think the problem is the new upgrade of opnessh, because the php code isn't changed. Any idea?

like image 663
Daniele Avatar asked Dec 13 '16 10:12

Daniele


3 Answers

Found the answer here on StackOverflow: https://stackoverflow.com/a/40972584/2520795

It seems since this PHP update, you have to surround your host part (result of ssh2_sftp()) with intval():

$handle = opendir("ssh2.sftp://".intval($sftp)."/path/to/directory");

In my case there was a fopen instead of an opendir, but the solution is the same.

like image 53
Christian Avatar answered Nov 01 '22 13:11

Christian


You may experience "segmentation fault" issue even with intval($sftp) solution if you're closing connection with ssh2_disconnect(). The right solution is to close SFTP connection before closing SSH2-connection by unset($sftp) or $sftp = null. Here's my fully working example of reading remote file:

if (!$ssh2_connection = ssh2_connect($host, $port)) {
    die("Failed to connect\n");
}
if (!ssh2_auth_password($ssh2_connection, $username, $password)) {
    die("Failed to login\n");
}
if (!$sftp_connection = ssh2_sftp($ssh2_connection)) {
    die("Failed to open SFTP session\n");
}
if (!$fh = fopen("ssh2.sftp://".intval($sftp_connection).$path, 'r')) {
    die("Failed to open file\n");
}
while (($s = fgets($fh)) !== false) {
    echo $s;
}
fclose($fh);
unset($sftp_connection);
if (!ssh2_disconnect($ssh2_connection)) {
    die("Failed to disconnect\n");
}

P.S. Also instead of "segmentation fault" you may see something like:

php: channel.c:2570: _libssh2_channel_free: Assertion `session' failed.

Aborted

My solution solves it.

like image 20
Paul Melekhov Avatar answered Nov 01 '22 14:11

Paul Melekhov


In our case, the intval() didn't solve the segmentation fault. However, changing the call format did work:

fopen("ssh2.sftp://{$username}:{$password}@{$host}:{$port}/{$absolutePath}/{$filename}", 'w');
like image 28
Arian Acosta Avatar answered Nov 01 '22 13:11

Arian Acosta