/*
 * $Id: ssh2.c,v 1.18 2008/11/10 16:48:41 bagder Exp $
 *
 * Sample showing how to do SSH2 connect.
 *
 * The sample code has default values for host name, user name, password
 * and path to copy, but you can specify them on the command line like:
 *
 * "ssh2 host user password [-p|-i|-k]"
 */

#include "libssh2_config.h"
#include <libssh2.h>
#include <libssh2_sftp.h>

#ifdef HAVE_WINDOWS_H
# include <windows.h>
#endif
#ifdef HAVE_WINSOCK2_H
# include <winsock2.h>
#endif
#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
# ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
# ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif

#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <stdio.h>
#include <ctype.h>

#include <signal.h>

const char *keyfile1="/home/pwu/.ssh/id_rsa.pub";
const char *keyfile2="/home/pwu/.ssh/id_rsa";
const char *username="username";
const char *password="password";

int alarmclock;

LIBSSH2_SFTP *sftp_session;
LIBSSH2_SFTP_HANDLE *sftp_handle;

static void kbd_callback(const char *name, int name_len, 
             const char *instruction, int instruction_len, int num_prompts,
             const LIBSSH2_USERAUTH_KBDINT_PROMPT *prompts,
             LIBSSH2_USERAUTH_KBDINT_RESPONSE *responses,
             void **abstract)
{
    (void)name;
    (void)name_len;
    (void)instruction;
    (void)instruction_len;
    if (num_prompts == 1) {
        responses[0].text = strdup(password);
        responses[0].length = strlen(password);
    }
    (void)prompts;
    (void)abstract;
} /* kbd_callback */


alarmed() {
  printf("Read timed out\n");
  alarmclock=1;
}

int main(int argc, char *argv[])
{
    char buf[1025];
    int buflen;
    int status;

    unsigned long hostaddr;
    int sock, i, auth_pw = 0;
    struct sockaddr_in sin;
    const char *fingerprint;
    char *userauthlist;
    LIBSSH2_SESSION *session;
    LIBSSH2_CHANNEL *channel;
#ifdef WIN32
    WSADATA wsadata;

    WSAStartup(MAKEWORD(2,0), &wsadata);
#endif

    if (argc > 1) {
        hostaddr = inet_addr(argv[1]);
    } else {
        hostaddr = htonl(0x7F000001);
    }

    if(argc > 2) {
        username = argv[2];
    }
    if(argc > 3) {
        password = argv[3];
    }

    /* Ultra basic "connect to port 22 on localhost"
     * Your code is responsible for creating the socket establishing the connection
     */
    sock = socket(AF_INET, SOCK_STREAM, 0);
#ifndef WIN32
    fcntl(sock, F_SETFL, 0);
#endif
    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = hostaddr;
    if (connect(sock, (struct sockaddr*)(&sin),
                sizeof(struct sockaddr_in)) != 0) {
        fprintf(stderr, "failed to connect!\n");
        return -1;
    }

    /* Create a session instance and start it up
     * This will trade welcome banners, exchange keys, and setup crypto, compression, and MAC layers
     */
    session = libssh2_session_init();
    if (libssh2_session_startup(session, sock)) {
        fprintf(stderr, "Failure establishing SSH session\n");
        return -1;
    }

    /* At this point we havn't authenticated,
     * The first thing to do is check the hostkey's fingerprint against our known hosts
     * Your app may have it hard coded, may go to a file, may present it to the user, that's your call
     */
    fingerprint = libssh2_hostkey_hash(session, LIBSSH2_HOSTKEY_HASH_MD5);
    printf("Fingerprint: ");
    for(i = 0; i < 16; i++) {
        printf("%02X ", (unsigned char)fingerprint[i]);
    }
    printf("\n");

    /* check what authentication methods are available */
    userauthlist = libssh2_userauth_list(session, username, strlen(username));
    printf("Authentication methods: %s\n", userauthlist);
    if (strstr(userauthlist, "password") != NULL) {
        auth_pw |= 1;
    }
    if (strstr(userauthlist, "keyboard-interactive") != NULL) {
        auth_pw |= 2;
    }
    if (strstr(userauthlist, "publickey") != NULL) {
        auth_pw |= 4;
    }

    /* if we got an 4. argument we set this option if supported */ 
    if(argc > 4) {
        if ((auth_pw & 1) && !strcasecmp(argv[4], "-p")) {
            auth_pw = 1;
        }
        if ((auth_pw & 2) && !strcasecmp(argv[4], "-i")) {
            auth_pw = 2;
        }
        if ((auth_pw & 4) && !strcasecmp(argv[4], "-k")) {
            auth_pw = 4;
        }
    }

    if (auth_pw & 4) {
        /* Or by public key */
        if (libssh2_userauth_publickey_fromfile(session, username, keyfile1, keyfile2, password)) {
            printf("\tAuthentication by public key failed!\n");
        } else {
            printf("\tAuthentication by public key succeeded.\n");
            goto newsession;
        }
    }

    if (auth_pw & 1) {
        /* We could authenticate via password */
        if (libssh2_userauth_password(session, username, password)) {
        } else {
            printf("\tAuthentication by password succeeded.\n");
            goto newsession;
        }
    }

    if (auth_pw & 2) {
        /* Or via keyboard-interactive */
        if (libssh2_userauth_keyboard_interactive(session, username, &kbd_callback) ) {
            printf("\tAuthentication by keyboard-interactive failed!\n");
        } else {
            printf("\tAuthentication by keyboard-interactive succeeded.\n");
            goto newsession;
        }
    }

    printf("Authentication failed\n");
    exit(1);

    newsession:
    sftp_session = libssh2_sftp_init(session);
    if (!sftp_session) {
        fprintf(stderr, "Unable to init SFTP session\n");
        goto shutdown;
    }
    sftp_handle =
        libssh2_sftp_open(sftp_session, "/tmp/exectest_output",
                      LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC,0755);
    if (!sftp_handle) {
        fprintf(stderr, "Unable to open remote file /tmp/exectest_output with SFTP\n");
        goto shutdown;
    }
    libssh2_sftp_write(sftp_handle,"Hello\n",6);
    libssh2_sftp_close(sftp_handle);
    libssh2_sftp_shutdown(sftp_session);

    /* Request a shell */
    if (!(channel = libssh2_channel_open_session(session))) {
        fprintf(stderr, "Unable to open a session\n");
        goto shutdown;
    }

    /* Request a terminal with 'vanilla' terminal emulation
     * See /etc/termcap for more options
     */
    if (libssh2_channel_request_pty(channel, "vanilla")) {
        fprintf(stderr, "Failed requesting pty\n");
        goto skip_shell;
    }

    /* exec date */
    if (libssh2_channel_exec(channel,"/bin/date")) {
        fprintf(stderr, "Unable to run command 'date' on allocated pty\n");
        goto shutdown;
    }

    signal(SIGALRM,&alarmed);
    alarm(120);
    alarmclock=0;
    while (alarmclock==0) {
      buflen=(int) libssh2_channel_read(channel,buf,sizeof(buf));
      if (buflen<0) {
        printf("Error from ssh2 read %d\n",buflen);
      }
      else if (buflen==0) {
      }
      else {
        alarm(0);
        alarm(120);
        buf[buflen]=0;
        printf("Received %s",buf);
        fflush(NULL);
      }
    }

    printf("\n");
    /* Close channel */
    status=libssh2_channel_close(channel);
    if (status!=0) {
      printf("Channel close returned %d\n",status);
    }

    /* Wait for other side to close */
    status=libssh2_channel_wait_closed(channel);
    if (status!=0) {
      printf("Channel close wait from remote returned %d\n",status);
    }

    /* Read anything the other side wants to send */
    signal(SIGALRM,&alarmed);
    alarm(120);
    buflen=(int) libssh2_channel_read(channel,buf,sizeof(buf));
    if (buflen>0) {
      buf[buflen]=0;
      printf("Received %s",buf);
    }

    printf("\n");
    status=libssh2_channel_get_exit_status(channel);
    printf("Your exit status is %d\n",status);
  skip_shell:
    if (channel) {
        libssh2_channel_free(channel);
        channel = NULL;
    }
    /* Other channel types are supported via:
     * libssh2_scp_send()
     * libssh2_scp_recv()
     * libssh2_channel_direct_tcpip()
     */

  shutdown:

    libssh2_session_disconnect(session, "Normal Shutdown, Thank you for playing");
    libssh2_session_free(session);

#ifdef WIN32
    Sleep(1000);
    closesocket(sock);
#else
    sleep(1);
    close(sock);
#endif
    printf("all done!\n");
    return 0;
}
