Page MenuHomePhabricator

v9.0 example and cpp wrappers returning -1 on ssh_channel_read and ssh_channel_read_timeout
Open, Needs TriagePublic

Description

The example in http://api.libssh.org/stable/libssh_tutor_guided_tour.html ("doing something") seems to always exit with SSH_ERROR when calling show_remote_processes (nbytes is lesser than zero). This same behaviour is exhibited in the "read" function of the Channel class for the C++ wrappers, which causes it to throw.

Apparently, the channel has reached EOF and that might be causing read calls to return with an error. Checking that the channel has reached EOF before throwing fixes this issue in my tests. However, I am just beginning to use this library, so I might be missing something.

The code:

#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <sstream>
#include <stdexcept>

#include <libssh/libsshpp.hpp>

/**
Add this method to the channel wrapper:

int test_read(void *dest, size_t count, bool is_stderr=false, int timeout=-1){
    int err;
    /* handle int overflow */
    if(count > 0x7fffffff)
      count = 0x7fffffff;
    err=ssh_channel_read_timeout(channel,dest,count,is_stderr,timeout);
	if(isEof()) {
		return err;
	}
    ssh_throw(err);
    return err;
}
*/

int main(int argc, char ** argv) {

	try {
		ssh::Session ses;

		ses.setOption(SSH_OPTIONS_HOST, "****");
		ses.setOption(SSH_OPTIONS_USER, "****");
		ses.connect();

		auto auth_result=ses.userauthPassword("****");
		if(SSH_AUTH_SUCCESS!=auth_result) {
			throw std::runtime_error("unauthorized");
		}

		ssh::Channel ch(ses);
		ch.openSession();
		if(!ch.isOpen()) {
			throw std::runtime_error("closed channel");
		}

		ch.requestExec("echo hello");
		ch.sendEof();
		char buff[256];
		memset(buff, 0, 256);

		int bytes_read=0;
		while(!ch.isEof()) {
			bytes_read=ch.test_read((void*)buff, sizeof(buff), false, -1);
			std::cout<<"read "<<bytes_read<<std::endl;
			if(bytes_read > 0) {
				//Do something with the buffer...
			}
  		}
		
		return 0;
	}
	catch(ssh::SshException& e) {

		std::cerr<<"ssh error: "<<e.getError()<<std::endl;
		return 1;
	}
	catch(std::exception& e) {
		
		std::cerr<<"error: "<<e.what()<<std::endl;
		return 1;
	}
}

Event Timeline