libssh  0.7
libsshpp.hpp
1 /*
2  * This file is part of the SSH Library
3  *
4  * Copyright (c) 2010 by Aris Adamantiadis
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 #ifndef LIBSSHPP_HPP_
22 #define LIBSSHPP_HPP_
23 
51 /* do not use deprecated functions */
52 #define LIBSSH_LEGACY_0_4
53 
54 #include <libssh/libssh.h>
55 #include <libssh/server.h>
56 #include <stdlib.h>
57 #include <stdarg.h>
58 #include <stdio.h>
59 #include <string>
60 
61 namespace ssh {
62 
63 class Channel;
68 #ifndef SSH_NO_CPP_EXCEPTIONS
69 
75 public:
76  SshException(ssh_session csession){
77  code=ssh_get_error_code(csession);
78  description=std::string(ssh_get_error(csession));
79  }
80  SshException(const SshException &e){
81  code=e.code;
82  description=e.description;
83  }
89  int getCode(){
90  return code;
91  }
96  std::string getError(){
97  return description;
98  }
99 private:
100  int code;
101  std::string description;
102 };
103 
107 #define ssh_throw(x) if((x)==SSH_ERROR) throw SshException(getCSession())
108 #define ssh_throw_null(CSession,x) if((x)==NULL) throw SshException(CSession)
109 #define void_throwable void
110 #define return_throwable return
111 
112 #else
113 
114 /* No exception at all. All functions will return an error code instead
115  * of an exception
116  */
117 #define ssh_throw(x) if((x)==SSH_ERROR) return SSH_ERROR
118 #define ssh_throw_null(CSession,x) if((x)==NULL) return NULL
119 #define void_throwable int
120 #define return_throwable return SSH_OK
121 #endif
122 
126 class Session {
127  friend class Channel;
128 public:
129  Session(){
130  c_session=ssh_new();
131  }
132  ~Session(){
133  ssh_free(c_session);
134  c_session=NULL;
135  }
142  void_throwable setOption(enum ssh_options_e type, const char *option){
143  ssh_throw(ssh_options_set(c_session,type,option));
144  return_throwable;
145  }
152  void_throwable setOption(enum ssh_options_e type, long int option){
153  ssh_throw(ssh_options_set(c_session,type,&option));
154  return_throwable;
155  }
162  void_throwable setOption(enum ssh_options_e type, void *option){
163  ssh_throw(ssh_options_set(c_session,type,option));
164  return_throwable;
165  }
170  void_throwable connect(){
171  int ret=ssh_connect(c_session);
172  ssh_throw(ret);
173  return_throwable;
174  }
181  int ret=ssh_userauth_publickey_auto(c_session, NULL, NULL);
182  ssh_throw(ret);
183  return ret;
184  }
193  int ret=ssh_userauth_none(c_session,NULL);
194  ssh_throw(ret);
195  return ret;
196  }
203  int userauthPassword(const char *password){
204  int ret=ssh_userauth_password(c_session,NULL,password);
205  ssh_throw(ret);
206  return ret;
207  }
215  int userauthTryPublickey(ssh_key pubkey){
216  int ret=ssh_userauth_try_publickey(c_session, NULL, pubkey);
217  ssh_throw(ret);
218  return ret;
219  }
226  int userauthPublickey(ssh_key privkey){
227  int ret=ssh_userauth_publickey(c_session, NULL, privkey);
228  ssh_throw(ret);
229  return ret;
230  }
231  int userauthPrivatekeyFile(const char *filename,
232  const char *passphrase);
238  int getAuthList(){
239  int ret=ssh_userauth_list(c_session, NULL);
240  ssh_throw(ret);
241  return ret;
242  }
246  void disconnect(){
247  ssh_disconnect(c_session);
248  }
253  const char *getDisconnectMessage(){
254  const char *msg=ssh_get_disconnect_message(c_session);
255  return msg;
256  }
260  const char *getError(){
261  return ssh_get_error(c_session);
262  }
266  int getErrorCode(){
267  return ssh_get_error_code(c_session);
268  }
275  socket_t getSocket(){
276  return ssh_get_fd(c_session);
277  }
282  std::string getIssueBanner(){
283  char *banner=ssh_get_issue_banner(c_session);
284  std::string ret= std::string(banner);
285  ::free(banner);
286  return ret;
287  }
293  return ssh_get_openssh_version(c_session);
294  }
299  int getVersion(){
300  return ssh_get_version(c_session);
301  }
309  int ret=ssh_is_server_known(c_session);
310  ssh_throw(ret);
311  return ret;
312  }
313  void log(int priority, const char *format, ...){
314  char buffer[1024];
315  va_list va;
316 
317  va_start(va, format);
318  vsnprintf(buffer, sizeof(buffer), format, va);
319  va_end(va);
320  _ssh_log(priority, "libsshpp", "%s", buffer);
321  }
322 
327  void_throwable optionsCopy(const Session &source){
328  ssh_throw(ssh_options_copy(source.c_session,&c_session));
329  return_throwable;
330  }
336  void_throwable optionsParseConfig(const char *file){
337  ssh_throw(ssh_options_parse_config(c_session,file));
338  return_throwable;
339  }
344  ssh_silent_disconnect(c_session);
345  }
352  int ret = ssh_write_knownhost(c_session);
353  ssh_throw(ret);
354  return ret;
355  }
356 
365  inline Channel *acceptForward(int timeout_ms);
366  /* implemented outside the class due Channel references */
367 
368  void_throwable cancelForward(const char *address, int port){
369  int err=ssh_channel_cancel_forward(c_session, address, port);
370  ssh_throw(err);
371  return_throwable;
372  }
373 
374  void_throwable listenForward(const char *address, int port,
375  int &boundport){
376  int err=ssh_channel_listen_forward(c_session, address, port, &boundport);
377  ssh_throw(err);
378  return_throwable;
379  }
380 
381 private:
382  ssh_session c_session;
383  ssh_session getCSession(){
384  return c_session;
385  }
386  /* No copy constructor, no = operator */
387  Session(const Session &);
388  Session& operator=(const Session &);
389 };
390 
395 class Channel {
396  friend class Session;
397 public:
398  Channel(Session &session){
399  channel=ssh_channel_new(session.getCSession());
400  this->session=&session;
401  }
402  ~Channel(){
403  ssh_channel_free(channel);
404  channel=NULL;
405  }
406 
415  Channel *acceptX11(int timeout_ms){
416  ssh_channel x11chan = ssh_channel_accept_x11(channel,timeout_ms);
417  ssh_throw_null(getCSession(),x11chan);
418  Channel *newchan = new Channel(getSession(),x11chan);
419  return newchan;
420  }
427  void_throwable changePtySize(int cols, int rows){
428  int err=ssh_channel_change_pty_size(channel,cols,rows);
429  ssh_throw(err);
430  return_throwable;
431  }
432 
437  void_throwable close(){
438  ssh_throw(ssh_channel_close(channel));
439  return_throwable;
440  }
441 
442  int getExitStatus(){
443  return ssh_channel_get_exit_status(channel);
444  }
445  Session &getSession(){
446  return *session;
447  }
451  bool isClosed(){
452  return ssh_channel_is_closed(channel) != 0;
453  }
457  bool isEof(){
458  return ssh_channel_is_eof(channel) != 0;
459  }
463  bool isOpen(){
464  return ssh_channel_is_open(channel) != 0;
465  }
466  int openForward(const char *remotehost, int remoteport,
467  const char *sourcehost=NULL, int localport=0){
468  int err=ssh_channel_open_forward(channel,remotehost,remoteport,
469  sourcehost, localport);
470  ssh_throw(err);
471  return err;
472  }
473  /* TODO: completely remove this ? */
474  void_throwable openSession(){
475  int err=ssh_channel_open_session(channel);
476  ssh_throw(err);
477  return_throwable;
478  }
479  int poll(bool is_stderr=false){
480  int err=ssh_channel_poll(channel,is_stderr);
481  ssh_throw(err);
482  return err;
483  }
484  int read(void *dest, size_t count, bool is_stderr){
485  int err;
486  /* handle int overflow */
487  if(count > 0x7fffffff)
488  count = 0x7fffffff;
489  err=ssh_channel_read_timeout(channel,dest,count,is_stderr,-1);
490  ssh_throw(err);
491  return err;
492  }
493  int read(void *dest, size_t count, int timeout){
494  int err;
495  /* handle int overflow */
496  if(count > 0x7fffffff)
497  count = 0x7fffffff;
498  err=ssh_channel_read_timeout(channel,dest,count,false,timeout);
499  ssh_throw(err);
500  return err;
501  }
502  int read(void *dest, size_t count, bool is_stderr=false, int timeout=-1){
503  int err;
504  /* handle int overflow */
505  if(count > 0x7fffffff)
506  count = 0x7fffffff;
507  err=ssh_channel_read_timeout(channel,dest,count,is_stderr,timeout);
508  ssh_throw(err);
509  return err;
510  }
511  int readNonblocking(void *dest, size_t count, bool is_stderr=false){
512  int err;
513  /* handle int overflow */
514  if(count > 0x7fffffff)
515  count = 0x7fffffff;
516  err=ssh_channel_read_nonblocking(channel,dest,count,is_stderr);
517  ssh_throw(err);
518  return err;
519  }
520  void_throwable requestEnv(const char *name, const char *value){
521  int err=ssh_channel_request_env(channel,name,value);
522  ssh_throw(err);
523  return_throwable;
524  }
525 
526  void_throwable requestExec(const char *cmd){
527  int err=ssh_channel_request_exec(channel,cmd);
528  ssh_throw(err);
529  return_throwable;
530  }
531  void_throwable requestPty(const char *term=NULL, int cols=0, int rows=0){
532  int err;
533  if(term != NULL && cols != 0 && rows != 0)
534  err=ssh_channel_request_pty_size(channel,term,cols,rows);
535  else
536  err=ssh_channel_request_pty(channel);
537  ssh_throw(err);
538  return_throwable;
539  }
540 
541  void_throwable requestShell(){
542  int err=ssh_channel_request_shell(channel);
543  ssh_throw(err);
544  return_throwable;
545  }
546  void_throwable requestSendSignal(const char *signum){
547  int err=ssh_channel_request_send_signal(channel, signum);
548  ssh_throw(err);
549  return_throwable;
550  }
551  void_throwable requestSubsystem(const char *subsystem){
552  int err=ssh_channel_request_subsystem(channel,subsystem);
553  ssh_throw(err);
554  return_throwable;
555  }
556  int requestX11(bool single_connection,
557  const char *protocol, const char *cookie, int screen_number){
558  int err=ssh_channel_request_x11(channel,single_connection,
559  protocol, cookie, screen_number);
560  ssh_throw(err);
561  return err;
562  }
563  void_throwable sendEof(){
564  int err=ssh_channel_send_eof(channel);
565  ssh_throw(err);
566  return_throwable;
567  }
577  int write(const void *data, size_t len, bool is_stderr=false){
578  int ret;
579  if(is_stderr){
580  ret=ssh_channel_write_stderr(channel,data,len);
581  } else {
582  ret=ssh_channel_write(channel,data,len);
583  }
584  ssh_throw(ret);
585  return ret;
586  }
587 private:
588  ssh_session getCSession(){
589  return session->getCSession();
590  }
591  Channel (Session &session, ssh_channel c_channel){
592  this->channel=c_channel;
593  this->session=&session;
594  }
595  Session *session;
596  ssh_channel channel;
597  /* No copy and no = operator */
598  Channel(const Channel &);
599  Channel &operator=(const Channel &);
600 };
601 
602 
603 inline Channel *Session::acceptForward(int timeout_ms){
604  ssh_channel forward =
605  ssh_channel_accept_forward(c_session, timeout_ms, NULL);
606  ssh_throw_null(c_session,forward);
607  Channel *newchan = new Channel(*this,forward);
608  return newchan;
609  }
610 
611 } // namespace ssh
612 
614 #endif /* LIBSSHPP_HPP_ */
int userauthNone()
Authenticates using the "none" method.
Definition: libsshpp.hpp:192
int getAuthList()
Returns the available authentication methods from the server.
Definition: libsshpp.hpp:238
Definition: libsshpp.hpp:61
int ssh_channel_read_timeout(ssh_channel channel, void *dest, uint32_t count, int is_stderr, int timeout_ms)
Reads data from a channel.
Definition: channels.c:2623
void connect()
connects to the remote host
Definition: libsshpp.hpp:170
int ssh_options_parse_config(ssh_session session, const char *filename)
Parse the ssh config file.
Definition: options.c:1206
Channel * acceptX11(int timeout_ms)
accept an incoming X11 connection
Definition: libsshpp.hpp:415
int ssh_channel_request_x11(ssh_channel channel, int single_connection, const char *protocol, const char *cookie, int screen_number)
Sends the "x11-req" channel request over an existing session channel.
Definition: channels.c:1866
int ssh_channel_request_shell(ssh_channel channel)
Request a shell.
Definition: channels.c:1756
int ssh_channel_open_forward(ssh_channel channel, const char *remotehost, int remoteport, const char *sourcehost, int localport)
Open a TCP/IP forwarding channel.
Definition: channels.c:939
int ssh_channel_is_eof(ssh_channel channel)
Check if remote has sent an EOF.
Definition: channels.c:1414
int isServerKnown()
verifies that the server is known
Definition: libsshpp.hpp:308
int ssh_channel_send_eof(ssh_channel channel)
Send an end of file on the channel.
Definition: channels.c:1067
void close()
closes a channel
Definition: libsshpp.hpp:437
int ssh_channel_close(ssh_channel channel)
Close a channel.
Definition: channels.c:1119
int userauthPublickey(ssh_key privkey)
Authenticates using the publickey method.
Definition: libsshpp.hpp:226
int getVersion()
returns the version of the SSH protocol being used
Definition: libsshpp.hpp:299
The ssh::Session class contains the state of a SSH connection.
Definition: libsshpp.hpp:126
LIBSSH_API int ssh_channel_write_stderr(ssh_channel channel, const void *data, uint32_t len)
Blocking write on a channel stderr.
Definition: channels.c:3172
int ssh_get_openssh_version(ssh_session session)
Get the version of the OpenSSH server, if it is not an OpenSSH server then 0 will be returned...
Definition: client.c:613
int ssh_userauth_list(ssh_session session, const char *username)
Get available authentication methods from the server.
Definition: auth.c:318
const char * ssh_get_error(void *error)
Retrieve the error text message from the last error.
Definition: error.c:111
int ssh_channel_write(ssh_channel channel, const void *data, uint32_t len)
Blocking write on a channel.
Definition: channels.c:1371
int ssh_channel_request_pty_size(ssh_channel channel, const char *term, int cols, int rows)
Request a pty with a specific type and size.
Definition: channels.c:1620
int ssh_channel_request_subsystem(ssh_channel channel, const char *subsystem)
Request a subsystem (for example "sftp").
Definition: channels.c:1782
the ssh::Channel class describes the state of an SSH channel.
Definition: libsshpp.hpp:395
int ssh_get_version(ssh_session session)
Get the protocol version of the session.
Definition: session.c:783
int ssh_channel_request_env(ssh_channel channel, const char *name, const char *value)
Set environment variables.
Definition: channels.c:2294
int userauthPublickeyAuto(void)
Authenticates automatically using public key.
Definition: libsshpp.hpp:180
char * ssh_get_issue_banner(ssh_session session)
Get the issue banner from the server.
Definition: client.c:587
int write(const void *data, size_t len, bool is_stderr=false)
Writes on a channel.
Definition: libsshpp.hpp:577
void changePtySize(int cols, int rows)
change the size of a pseudoterminal
Definition: libsshpp.hpp:427
std::string getIssueBanner()
gets the Issue banner from the ssh server
Definition: libsshpp.hpp:282
int ssh_options_copy(ssh_session src, ssh_session *dest)
Duplicate the options of a session structure.
Definition: options.c:64
void disconnect()
Disconnects from the SSH server and closes connection.
Definition: libsshpp.hpp:246
int getCode()
returns the Error code
Definition: libsshpp.hpp:89
int ssh_channel_open_session(ssh_channel channel)
Open a session channel (suited for a shell, not TCP forwarding).
Definition: channels.c:862
Some people do not like C++ exceptions.
Definition: libsshpp.hpp:74
int ssh_channel_is_open(ssh_channel channel)
Check if the channel is open or not.
Definition: channels.c:1384
int ssh_write_knownhost(ssh_session session)
Write the current server as known in the known hosts file.
Definition: known_hosts.c:526
int ssh_channel_is_closed(ssh_channel channel)
Check if the channel is closed or not.
Definition: channels.c:1400
socket_t getSocket()
returns the file descriptor used for the communication
Definition: libsshpp.hpp:275
void optionsParseConfig(const char *file)
parses a configuration file for options
Definition: libsshpp.hpp:336
void setOption(enum ssh_options_e type, void *option)
sets an SSH session options
Definition: libsshpp.hpp:162
int ssh_channel_poll(ssh_channel channel, int is_stderr)
Polls a channel for data to read.
Definition: channels.c:2785
int writeKnownhost()
Writes the known host file with current host key.
Definition: libsshpp.hpp:351
ssh_channel ssh_channel_new(ssh_session session)
Allocate a new channel.
Definition: channels.c:79
int ssh_options_set(ssh_session session, enum ssh_options_e type, const void *value)
This function can set all possible ssh options.
Definition: options.c:388
int ssh_userauth_password(ssh_session session, const char *username, const char *password)
Try to authenticate by password.
Definition: auth.c:1105
int ssh_userauth_publickey_auto(ssh_session session, const char *username, const char *passphrase)
Tries to automatically authenticate with public key and "none".
Definition: auth.c:888
int ssh_userauth_publickey(ssh_session session, const char *username, const ssh_key privkey)
Authenticate with public/private key.
Definition: auth.c:550
socket_t ssh_get_fd(ssh_session session)
Get the fd of a connection.
Definition: session.c:516
int userauthPassword(const char *password)
Authenticates using the password method.
Definition: libsshpp.hpp:203
bool isEof()
returns true if channel is in EOF state
Definition: libsshpp.hpp:457
int ssh_channel_change_pty_size(ssh_channel channel, int cols, int rows)
Change the size of the terminal associated to a channel.
Definition: channels.c:1709
int ssh_connect(ssh_session session)
Connect to the ssh server.
Definition: client.c:469
void ssh_disconnect(ssh_session session)
Disconnect from a session (client or server).
Definition: client.c:627
int getOpensshVersion()
returns the OpenSSH version (server) if possible
Definition: libsshpp.hpp:292
bool isClosed()
returns true if channel is in closed state
Definition: libsshpp.hpp:451
int ssh_userauth_none(ssh_session session, const char *username)
Try to authenticate through the "none" method.
Definition: auth.c:354
ssh_channel ssh_channel_accept_x11(ssh_channel channel, int timeout_ms)
Accept an X11 forwarding channel.
Definition: channels.c:1982
int ssh_channel_listen_forward(ssh_session session, const char *address, int port, int *bound_port)
Sends the "tcpip-forward" global request to ask the server to begin listening for inbound connections...
Definition: channels.c:2167
int ssh_channel_request_send_signal(ssh_channel channel, const char *signum)
Send a signal to remote process (as described in RFC 4254, section 6.9).
Definition: channels.c:2439
std::string getError()
returns the error message of the last exception
Definition: libsshpp.hpp:96
ssh_channel ssh_channel_accept_forward(ssh_session session, int timeout_ms, int *destination_port)
Accept an incoming TCP/IP forwarding channel and get information about incomming connection.
Definition: channels.c:2225
int userauthTryPublickey(ssh_key pubkey)
Try to authenticate using the publickey method.
Definition: libsshpp.hpp:215
void silentDisconnect()
silently disconnect from remote host
Definition: libsshpp.hpp:343
Channel * acceptForward(int timeout_ms)
accept an incoming forward connection
Definition: libsshpp.hpp:603
int ssh_channel_request_exec(ssh_channel channel, const char *cmd)
Run a shell command without an interactive shell.
Definition: channels.c:2364
bool isOpen()
returns true if channel is in open state
Definition: libsshpp.hpp:463
int ssh_channel_request_pty(ssh_channel channel)
Request a PTY.
Definition: channels.c:1690
void ssh_silent_disconnect(ssh_session session)
Disconnect impolitely from a remote host by closing the socket.
Definition: session.c:417
void setOption(enum ssh_options_e type, long int option)
sets an SSH session options
Definition: libsshpp.hpp:152
const char * ssh_get_disconnect_message(ssh_session session)
Get the disconnect message from the server.
Definition: session.c:758
ssh_session ssh_new(void)
Create a new ssh session.
Definition: session.c:58
void ssh_channel_free(ssh_channel channel)
Close and free a channel.
Definition: channels.c:995
int ssh_userauth_try_publickey(ssh_session session, const char *username, const ssh_key pubkey)
Try to authenticate with the given public key.
Definition: auth.c:441
int ssh_is_server_known(ssh_session session)
Check if the server is known.
Definition: known_hosts.c:406
void setOption(enum ssh_options_e type, const char *option)
sets an SSH session options
Definition: libsshpp.hpp:142
int ssh_channel_get_exit_status(ssh_channel channel)
Get the exit status of the channel (error code from the executed instruction).
Definition: channels.c:2914
int ssh_channel_cancel_forward(ssh_session session, const char *address, int port)
Sends the "cancel-tcpip-forward" global request to ask the server to cancel the tcpip-forward request...
Definition: channels.c:2244
const char * getDisconnectMessage()
Returns the disconnect message from the server, if any.
Definition: libsshpp.hpp:253
void optionsCopy(const Session &source)
copies options from a session to another
Definition: libsshpp.hpp:327
void ssh_free(ssh_session session)
Deallocate a SSH session handle.
Definition: session.c:172
int ssh_channel_read_nonblocking(ssh_channel channel, void *dest, uint32_t count, int is_stderr)
Do a nonblocking read on the channel.
Definition: channels.c:2733
int ssh_get_error_code(void *error)
Retrieve the error code from the last error.
Definition: error.c:131