[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: SSH.dll crash problem


Hi,

I missed the CPP file.

Regards,
Ravi

From: Ravikumar Sunkari [mailto:Ravikumar.Sunkari@xxxxxxxxxxxxxx]
Sent: Tuesday, October 07, 2014 3:03 PM
To: libssh@xxxxxxxxxx
Subject: FW: SSH.dll crash problem

Hello,

I have developed a SSH server in windows using LIBSSH 0.6.0 DLL. Our testing team has found a bug in the DLL distribution. Attached are the logs and the server code that I have collected during the tests,

I am getting VC++ Runtime Library -- "Debug assertion failed".

Can anyone help on this,

Please guide me and also let me know how can I setup windows project to debug ssh.dll

Thanks & Regards,
Ravi

/* 

ebpsshd.c compile:

gcc -g -Wall -Wstrict-prototypes -O0 -o ebpsshd `pkg-config --cflags --libs glib-2.0` -I/home/jeetu/utils/libssh/libssh-project/include ebpsshd.c -L/home/jeetu/utils/libssh/libssh-project/build/src -lssh -L/home/jeetu/utils/libssh/libssh-project/build/src/threads -lssh_threads -lgthread-2.0

*/
/*#include<iostream>
using namespace std;*/
#include <iostream>
#include <list>
#include <vector>
#include <map>
using namespace std;

#include <libssh/libssh.h>
#include <libssh/server.h>
#include <libssh/callbacks.h>
//#include <unistd.h>
//#include <string.h>
//#include <stdio.h>
//#include <glib.h>
//#include <stdlib.h>
//#include <errno.h>
//#include <poll.h>
#include "poll.h"
//#include <sys/types.h>
//#include <sys/socket.h>
#include <WinSock2.h>
//#include <netdb.h>
//#include <fcntl.h>
#include <Windows.h>
//#include <io.h>
#pragma comment(lib, "ws2_32.lib")
//#include "key.h" //jeetu - temporary hardcoded key

#ifndef KEYS_FOLDER	
#ifdef _WIN32
#define KEYS_FOLDER	"C:\\Users\\inrasun3\\.ssh\\"
#define AUTHORIZED_KEYS "C:\\Users\\inrasun3\\.ssh\\ssh_host_dsa_key"
#else
#define KEYS_FOLDER "/home/jeetu/tmp/" //jeetu - temporary
#define AUTHORIZED_KEYS "/home/jeetu/tmp/authorized_keys"
#endif
#endif

typedef void* gpointer;

#define MAX_X11_AUTH_PROTO_STR_SZ 18
#define MAX_X11_AUTH_COOKIE_STR_SZ 50

//jeetu - all hardcoded defines; should probably figure out how these values came to be in the orig openssh code
#define MAX_DISPLAYS 1000
#define NI_MAXSERV 32
#define NUM_SOCKS 10
#define SSH_LISTEN_BACKLOG 128

#define SSHD_USER		"INRASUN3"
#define SSHD_PASSWORD	"libssh"

fd_set g_ReadSet, g_WriteSet, g_ExceptSet;
void InitSets(SOCKET ListenSocket) ;
int pubkey_auth(char* pk64);
int auth_password(const char *user, const char *password);

struct Context
{
    ssh_session session;
    ssh_channel channel;
	int shell;
	bool bAuthenticated;
};

struct BindContext
{
	ssh_bind sshbind;
	ssh_session session;
};


void ssh_bind_callaback_function_r(ssh_bind bind, void *userdata)
{
	BindContext* bc = static_cast<BindContext*>(userdata);
	SOCKET sSock = ssh_get_fd(bc->session);
}

//bool iAuthenticated = false;

int message_callback(ssh_session session, ssh_message message, void *data)
{
    Context* ctx = static_cast<Context*>(data); //    .... processes message and sets the channel member in the ctx struct in reaction for SSH_REQUEST_CHANNEL_OPEN msg type
	ssh_string pubkey = NULL;
    char *pk64 = NULL;
    int signature_state = SSH_PUBLICKEY_STATE_NONE;
	//ctx->channel = 0;
	//ctx->shell = 0;

	if(!message) 
       return 0;


	printf("\n message received = %d", ssh_message_type(message));

	//if(!ctx->bAuthenticated)
	{

     switch(ssh_message_type(message)) 
	 {
	 case SSH_REQUEST_AUTH:
		 {
			 int iSubType = ssh_message_subtype(message);
			 switch(ssh_message_subtype(message))
			 {
			 case SSH_AUTH_METHOD_NONE:
				 ssh_message_auth_set_methods(message, SSH_AUTH_METHOD_PASSWORD);
				 ssh_message_reply_default(message);
				 break;
			 
			 case SSH_AUTH_METHOD_PUBLICKEY:
				 pubkey = publickey_to_string(ssh_message_auth_publickey(message));
				 //pk64 = g_base64_encode((const guchar *)ssh_string_to_char(pubkey), ssh_string_len(pubkey));
				 signature_state = ssh_message_auth_publickey_state(message);
				 if(signature_state == SSH_PUBLICKEY_STATE_NONE) 
				 {
					 /* no signature */
					 ssh_message_auth_reply_pk_ok_simple(message);
					 break;
				 } 
				 else if(signature_state != SSH_PUBLICKEY_STATE_VALID) 
				 {
					 /* will be rejected later */
				 } 
				 else 
				 {
					 /* signature is good at that point */
					 if(pubkey_auth(pk64)) 
					 {
						 /* user is allowed */
						 ssh_message_auth_reply_success(message, 0);
						 //ssh_message_free(message);
						 return 1;
					 }
				 }
				 
				 /* the following is not necessary if we want only pubkey auth */
				 ssh_message_auth_set_methods(message,SSH_AUTH_METHOD_PUBLICKEY);
				 /* reject authentication */
				 ssh_message_reply_default(message);
				 break;
				 
			 case SSH_AUTH_METHOD_PASSWORD:
				 /* handle password auth if needed */
				 if(auth_password(ssh_message_auth_user(message), ssh_message_auth_password(message)))
				 {
					 ssh_message_auth_reply_success(message,0);
					 ctx->bAuthenticated = true;
					 //ssh_message_free(message);
					 //return 1;
				 }
			 break;

			 default:
				 ssh_message_auth_set_methods(message,SSH_AUTH_METHOD_PUBLICKEY);
				 ssh_message_reply_default(message);
				 //ssh_message_free(message);
				 break;
			 }
		 }
		 
		 break;

	 case SSH_REQUEST_CHANNEL_OPEN:
		 {
			 int mn = ssh_message_subtype(message);

			 switch(mn)
			 {
			 case SSH_CHANNEL_SESSION:
				 {
					 ctx->channel = ssh_message_channel_request_open_reply_accept(message);
					 //ssh_message_free(message);
				 }
				 break;

			 default:
				 {
					 ssh_message_reply_default(message);
					 //ssh_message_free(message);
				 }
				 break;
			 }
		 }
		 break;

	 case SSH_REQUEST_CHANNEL:
		 {
			 int ity = ssh_message_subtype(message);
			 switch(ity)
			 {
			 case SSH_CHANNEL_REQUEST_SHELL:
				 {
					 ctx->shell = 1;
					 ssh_message_channel_request_reply_success(message);
				 }
				 break;

			 case SSH_CHANNEL_REQUEST_PTY:
				 ssh_message_channel_request_reply_success(message);
				 break;

			 default:
				 ssh_message_reply_default(message);
				 break;
			 }
		 }
		 break;

	 default:
		 ssh_message_reply_default(message);
		 //ssh_message_free(message);
		 break;
	 }
	}
	   
	return 0;
}

void InitSets(SOCKET ListenSocket) 
{
     //Initialize
     FD_ZERO(&g_ReadSet);
     FD_ZERO(&g_WriteSet);
     FD_ZERO(&g_ExceptSet);

     //Assign the ListenSocket to Sets
     FD_SET(ListenSocket, &g_ReadSet);
     FD_SET(ListenSocket, &g_ExceptSet);
     FD_SET(ListenSocket, &g_WriteSet);
}

int pubkey_auth(char* pk64)
{
    char header[100],key[300],footer[100];
    int ret = 0;
    FILE *fp;

    fp = fopen(AUTHORIZED_KEYS,"r");
    if(fp == NULL)
      {
      fprintf(stderr,"\nCould not open authorized_keys file %s\n",AUTHORIZED_KEYS);
      return 0;
      }

    while(fgetc(fp) != EOF)
         {
         header[0] = '\0';
         key[0] = '\0';
         footer[0] = '\0';
         fscanf(fp,"%s %s %s\n",header,key,footer);
         printf("\nkey = %s\n",key);
         if(strcmp(pk64,key) == 0)
           {
           ret = 1;
           break;
           }
         }

    fclose(fp);
    return ret;
}

int auth_password(const char *user, const char *password)
{
    if(strcmp(user, SSHD_USER))
		return 0;

    if(strcmp(password, SSHD_PASSWORD))
        return 0;

    return 1; // authenticated
}

class cSessionData
{
public:
	cSessionData(INT nSessionId = 0): m_nTxBytes(0), m_nRxBytes(0) {};
	~cSessionData() {};
	string m_strDataFromClient;
	string m_strDataToClient;
	INT m_nTxBytes;
	INT m_nRxBytes;
};

std::map<INT , cSessionData *> m_mapSessionData;

//int GetSshSessionAndChannel(void *Args);

CRITICAL_SECTION m_csRead;
CRITICAL_SECTION m_csProcess;


class CThread01
{
friend void *ThreadFunc01(void*);

protected:

	enum 
	{
		NOT_STARTED,
		RUNNING,
		FINISH_REQUESTED,
		FINISHED
	} m_stThread;

	
	HANDLE  m_hThread;

    CRITICAL_SECTION m_csThread;
    BOOL m_bTerminateUnresponsive;

	virtual INT Body(void* args)
	{
		return 0;
	}

public:
	CThread01()
	{
		m_hThread  = NULL;
		m_stThread = NOT_STARTED;
		InitializeCriticalSection(&m_csThread);
		m_bTerminateUnresponsive = FALSE;
	}

	virtual ~CThread01(void)
	{

	}

	INT Start(void* args);
	INT Stop(void);
	BOOL StopRequest(void);

};

void* ThreadFunc01(void* args)
{
	void** p = (void**) args;
	CThread01* pTh = (CThread01*) p[0];

    EnterCriticalSection(&pTh->m_csThread);
	pTh->m_stThread = pTh->RUNNING;
    LeaveCriticalSection(&pTh->m_csThread);
	pTh->Body(p[1]);
    EnterCriticalSection(&pTh->m_csThread);
	pTh->m_stThread = pTh->FINISHED;
    LeaveCriticalSection(&pTh->m_csThread);
    return ((void *) TRUE);
}


INT CThread01::Start(void *pThArgs)
{
	INT nErr = 0;
	unsigned int u32ThId;
	void* pp[2] = {this, pThArgs};
	LPTHREAD_START_ROUTINE pThFunc = (LPTHREAD_START_ROUTINE) ThreadFunc01;

	if(   (m_stThread == NOT_STARTED)
		||(m_stThread == FINISHED)
	  )
	{
		m_stThread = NOT_STARTED;
        EnterCriticalSection(&m_csThread);
		m_hThread =CreateThread(
                        NULL,   // LPSECURITY_ATTRIBUTES lpThreadAttributes, 
                                // pointer to thread security attributes 
                        0,      // DWORD dwStackSize, 
						pThFunc,//(LPTHREAD_START_ROUTINE)    SClkSrvThread,// pointer to thread function 
                        pp,		// argument for new thread 
                        0,      // DWORD dwCreationFlags, 
                        (LPDWORD)&u32ThId// pointer to returned thread identifier 
                        );

        LeaveCriticalSection(&m_csThread);

		if(m_hThread == NULL) 
			nErr = GetLastError();

		if(!nErr)
		{
			while(m_stThread == NOT_STARTED) 
				Sleep(1);
		}
	}

	if(nErr) 
		printf("Could not start CThread01");
	
	return nErr;
}

INT CThread01::Stop(void)
{
    INT nNumIterations;

    nNumIterations = 0;
	if(m_stThread == RUNNING)
	{
		m_stThread = FINISH_REQUESTED;
		while(m_stThread != FINISHED)
        {
            Sleep(1);
            nNumIterations++;
            if ((nNumIterations>200))
            {
                TerminateThread(m_hThread, 0);
                m_stThread = FINISHED;
            }
        }
	}
	CloseHandle(m_hThread);
	m_hThread = NULL;
	return 0;
}

BOOL CThread01::StopRequest(void)
{
	return true;
}

class cSShService: public CThread01
{
public:
	cSShService() { };
	virtual INT Body(void* args);
	virtual ~cSShService() { };

	char* ReadData(INT ni);
	char* WriteData(INT ni, char *pData);
};

INT cSShService::Body(void *pArgs)
{
	bool bQuit = false;
	while(true)
	{
		EnterCriticalSection(&m_csThread);
		if(m_stThread == FINISH_REQUESTED)
			bQuit = true;
		LeaveCriticalSection(&m_csThread);
		
		if(bQuit)
		{
			break;
		}

		INT nConCount = 0;

		EnterCriticalSection(&m_csThread);
		nConCount = m_mapSessionData.size();
		LeaveCriticalSection(&m_csThread);

		for (INT ni = 0; ni < nConCount; ni++)
		{
			char *pData = ReadData(ni);
			if(pData)
			{
				int nCnt = strlen(pData);
				if(nCnt > 0)
				{
					string strDt;
					strDt.insert(0, pData, nCnt);
					strDt += ("Session " + ni);
					WriteData(ni, (char *)strDt.c_str());
					strDt.clear();
				}
			}
		}
		
		Sleep(10);
	}

	return 0;
}

char* cSShService::ReadData(INT iIndex)
{
	INT nConCount = 0;
	char Data[255] = {0};
	
	EnterCriticalSection(&m_csThread);
	if(!m_mapSessionData[iIndex]->m_strDataFromClient.empty())
	{
		m_mapSessionData[iIndex]->m_strDataFromClient.copy(Data, 255);
		m_mapSessionData[iIndex]->m_strDataFromClient.clear();
	}
	LeaveCriticalSection(&m_csThread);

	return Data;
}

char* cSShService::WriteData(INT ni, char *pData)
{
	int nSize = strlen(pData);

	EnterCriticalSection(&m_csThread);
	m_mapSessionData[ni]->m_strDataToClient.insert(0, pData, nSize);
	LeaveCriticalSection(&m_csThread);
	
	return 0;
}

class cSShProtocol: public CThread01
{
public:
	cSShProtocol(INT nSessionID = 0);
	INT GetThreadState()
	{
		return m_stThread;
	}
	virtual INT Body(void* args);
	virtual ~cSShProtocol();
	/*typedef int (cSShProtocol::*pMsgcb)(ssh_session, ssh_message, void *);
	pMsgcb cb_func;
	void SetCbFunction(pMsgcb pfunptr);
	void CallCbFunction(ssh_session, ssh_message, void *);
	int message_callback(ssh_session session, ssh_message message, void *data);*/
	cSessionData *pSessionData;
	string m_strClientTxData;
	string m_strClientRxData;
	INT m_nTxBytes;
	INT m_nRxBytes;
	BOOL m_bConsole;
	INT m_nSessionId;
};

cSShProtocol::cSShProtocol(INT nSessionID) : m_bConsole(FALSE), m_nTxBytes(0), m_nRxBytes(0), m_nSessionId(0)
{
	EnterCriticalSection(&m_csThread);
	m_mapSessionData[nSessionID] = new cSessionData();
	LeaveCriticalSection(&m_csThread);

	//pMsgcb = message_callback;
	//SetCbFunction(cSShProtocol::message_callback);
	
	//pSessionData = new cSessionData();
}

//void cSShProtocol::SetCbFunction(pMsgcb pfunptr)
//{
//	cb_func = pfunptr;
//}

//void cSShProtocol::CallCbFunction(ssh_session session, ssh_message message, void *data)
//{
//	(this->*cb_func)(session, message, data);
//}

INT cSShProtocol::Body(void *pArgs)
{
	ssh_session session = (ssh_session)pArgs;
	ssh_channel chan = 0;
	ssh_message message;
	int shell = 0;
	int u32TestTimer = 0;
	bool bQuit = false;
	int verbosity = SSH_LOG_PACKET;
	ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity );

	//SOCKET sSock = ssh_get_fd(session);

	 if(ssh_handle_key_exchange(session))
	 {
		 printf("ssh_handle_key_exchange: %s\n",ssh_get_error(session));
		 return 3;
	 }
	 
    //ssh_bind_set_fd(sshbind, sSock);

    Context ctx;
	ctx.session = session;
	ctx.channel = 0;
	ctx.shell = 0;
	ctx.bAuthenticated = false;
	ssh_set_message_callback(session, message_callback, &ctx);
	ssh_set_blocking(session, 0);
	

   while(true)
   {
	   InitSets(ssh_get_fd(session));
	   
	   EnterCriticalSection(&m_csThread);
	   if(m_stThread == FINISH_REQUESTED)
		   bQuit = true;
	   LeaveCriticalSection(&m_csThread);
	   
	   if(bQuit)
	   {
		   ssh_free(session);
		   break;
	   }

	   //if (select(0, &g_ReadSet, &g_WriteSet, &g_ExceptSet, 0) > 0) 
	   {
		   ssh_execute_message_callbacks(session);           // PROCESS ALL MESSAGES FROM THE QUEUE

		   /*if((ctx.bAuthenticated) && (!ctx.channel) && (!ctx.shell) )
		   {
			   do 
			   {
				   message = ssh_message_get(session);//pCon->session);
				   if(message)
				   {
					   if(ssh_message_type(message) == SSH_REQUEST_CHANNEL_OPEN && ssh_message_subtype(message) == SSH_CHANNEL_SESSION) 
					   {
						   ctx.channel = ssh_message_channel_request_open_reply_accept(message);
						   ssh_message_free(message);
						   break;
					   } 
					   else 
					   {
						   ssh_message_reply_default(message);
						   ssh_message_free(message);
					   }
				   } 
				   else 
				   {
					   break;
				   }
			   } while(!ctx.channel);
			   
			   if(!ctx.channel) 
			   {
				   printf("Error: cleint did not ask for a channel session (%s)\n", ssh_get_error(session));//pCon->session));
				   ssh_finalize();
				   return 1;
			   }
			   
			   //Wait for a session from ssh client
			   do 
			   {
				   message = ssh_message_get(session);//pCon->session);
				   if(message != NULL) 
				   {
					   if(ssh_message_type(message) == SSH_REQUEST_CHANNEL) 
					   {
						   if(ssh_message_subtype(message) == SSH_CHANNEL_REQUEST_SHELL) 
						   {
							   ctx.shell = 1;
							   ssh_message_channel_request_reply_success(message);
							   ssh_message_free(message);
							   break;
						   } 
						   else if(ssh_message_subtype(message) == SSH_CHANNEL_REQUEST_PTY) 
						   {
							   ssh_message_channel_request_reply_success(message);
							   ssh_message_free(message);
							   continue;
						   }
					   }
					   
					   ssh_message_reply_default(message);
					   ssh_message_free(message);
				   } 
				   else 
				   {
					   break;
				   }
			   } while(!ctx.shell);
			   
			   if(!ctx.shell) 
			   {
				   printf("Error: No shell requested (%s)\n", ssh_get_error(session));//pCon->session));
				   return 1;
			   }
		   }*/

		   int nRxBytes = 0;
		   string strInData;
		   if(( ctx.channel != 0 ) && (ctx.shell == 1) )
		   {
			   //while (ssh_channel_is_open(ctx.channel) && !ssh_channel_is_eof(ctx.channel))
			   if (ssh_channel_is_open(ctx.channel) && !ssh_channel_is_eof(ctx.channel))
			   {
				   bool bStatus = false;
				   
				   EnterCriticalSection(&m_csThread);
				   if(m_stThread == FINISH_REQUESTED)
					   bStatus = true;
				   LeaveCriticalSection(&m_csThread);
				   
				   if(bStatus)
				   {
					   ssh_channel_send_eof(ctx.channel);
					   ssh_channel_close(ctx.channel);
					   ssh_free(session);//pCon->session);
					   return 0;//break;
				   }
				   
				   /*u32TestTimer++;

				   if(u32TestTimer >= 3000L)
				   {
					   u32TestTimer = 0;
					   if(ssh_handle_key_exchange(session))
					   {
						   printf("ssh_handle_key_exchange: %s\n",ssh_get_error(session));
						   return 3;
					   }
				   }*/

				   char pReadPt[255];
				   unsigned int iRxLen = 0;
				   int iBytes = ssh_channel_read_nonblocking(ctx.channel, pReadPt, 255, 0);
				   if(iBytes > 0)
				   {
					   strInData.insert(nRxBytes, pReadPt, iBytes);
   					   nRxBytes += iBytes;

					   int iError = ssh_channel_write(ctx.channel, pReadPt, iBytes);
					   if(iError == -1)
						   printf("Error in writing SSH %s", ssh_get_error(session));//pCon->session));
				   }
				   else
				   {
					   if(iBytes < 0)
					   {
						   message = ssh_message_get(session);
						   int type = ssh_message_type(message);

						   int type1 = ssh_message_subtype(message);

						   printf("Client requested for close: BYtes are less than zero ");
						   char *cError = new char[255];
						   cError = (char *)ssh_get_error(session);
                           printf("\n Error = %s ", cError);
						   ssh_channel_send_eof(ctx.channel);
						   ssh_channel_close(ctx.channel);
						   ssh_free(session);//pCon->session);

						   EnterCriticalSection(&m_csThread);
						   Stop();								//Once the connection is closed , exit the thread
						   LeaveCriticalSection(&m_csThread);
						   break;
					   }
				   }

				   if(!strInData.empty())
				   {
					   std::size_t found = strInData.find('\r');
					   //Write Recieved data to buffer, so that main module picks up sent to DCU
					   if(found != std::string::npos)
					   {
						   char *pPtr1 = "\n";
						   int nSize = strlen(pPtr1);
						   int iError = ssh_channel_write(ctx.channel, pPtr1, iBytes);
						   if(iError == -1)
							   printf("Error in writing SSH %s", ssh_get_error(session));//pCon->session));

						   const char *pPtr = strInData.c_str();
						   int nLen = strInData.size();

						   EnterCriticalSection(&m_csThread);
						   m_mapSessionData[m_nSessionId]->m_strDataFromClient.insert(0, pPtr, nLen);
						   LeaveCriticalSection(&m_csThread);

   						   strInData.clear();
						   nRxBytes = 0;
					   }
				   }

				   char Data[255] = {0};
				   int nc = 0;
				   EnterCriticalSection(&m_csThread);
				   if(!m_mapSessionData[m_nSessionId]->m_strDataToClient.empty())
				   {
					   nc = m_mapSessionData[m_nSessionId]->m_strDataToClient.size();
					   m_mapSessionData[m_nSessionId]->m_strDataToClient.copy(Data, 255);
					   m_mapSessionData[m_nSessionId]->m_strDataToClient.clear();
				   }
				   LeaveCriticalSection(&m_csThread);
					
				   //char *pData = Data;
				   if(nc)
				   {
					   //int nSize = strlen(pData);
					   int iError = ssh_channel_write(ctx.channel, Data, nc);
					   if(iError == -1)
						   printf("Error in writing SSH %s", ssh_get_error(session));//pCon->session));
				   }

				   Sleep(10);
			   }
		   }
		   /*if(( ctx.channel != 0 ) && (ctx.shell == 1) )
		   {
			   std::vector<char> buf(512, '\0');

			   if( ssh_channel_is_open(ctx.channel) && !ssh_channel_is_eof(ctx.channel) )
			   {
				   int num = ssh_channel_read(ctx.channel, &buf[0], buf.size(), 0);
				   if(num <= 0)
				   {
					   continue;
				   }
				   
				   cout<<"Enter the SSH";
				   string str = string(&buf[0], num);
				   cout<<str.c_str()<< std::endl;
				   ssh_channel_write(ctx.channel, &buf[0], num);
			   }
		   }*/
	   }
    } // while(true)

	return 0;
}

cSShProtocol::~cSShProtocol()
{

}

std::list<cSShProtocol *> m_Clients;

int main(int argc, void *argv[])
{
	ssh_bind sshbind;     int auth=0;     int r;     int port = 2000;     int verbosity = SSH_LOG_PACKET;
    int session_count = 0; 	ssh_message message = 0; 	int shell=0;
	char ptr1[9999] = "WELCOME TO ABB SSH SERVER \n"; 	int *ptr = (int *)malloc(4); 	unsigned int uTxLen = 0;
	unsigned int uRxLen = 0; 	int iBytes = 0;	int iError = -1; 	char *pReadPtr = (char *)malloc(255);
	ssh_session session;
	ssh_channel chan=0;
	

	cSShService *pSshService = new cSShService();
	pSshService->Start(NULL);

	sshbind=ssh_bind_new();

    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_BINDPORT,&port);
    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_DSAKEY, KEYS_FOLDER "ssh_host_dsa_key");
    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_RSAKEY, KEYS_FOLDER "ssh_host_rsa_key");

    if(ssh_bind_listen(sshbind)<0)
	{
		printf("Error listening to socket: %s\n",ssh_get_error(sshbind));
		return 1;
	}
	
	int argc1 = argc;
	char **argv1 = (char **)argv;
    //ssh_options_getopt(session,&argc1,argv1);
   
	int icon = 0;
	while(true)
	{
		session = ssh_new();

		r = ssh_bind_accept(sshbind,session);
		
		if(r==SSH_ERROR)
		{
			printf("error accepting a connection : %s\n",ssh_get_error(sshbind));
			return 2;
		}

		if(icon > 2)//if(!m_Clients.empty())	//if connections are more than 5 simply close the first one
		{
			cSShProtocol *pProtocolHandleLocal = m_Clients.front();

			INT iThreadSts = pProtocolHandleLocal->GetThreadState();

			if(iThreadSts == 1)		//if thread state is running then only close
				pProtocolHandleLocal->Stop();

			delete pProtocolHandleLocal;
			m_Clients.pop_front();
		}

		cSShProtocol *pProtocolHandle = new cSShProtocol(icon);	//Loading the session
		pProtocolHandle->Start(session);
		m_Clients.push_back(pProtocolHandle);

		icon++;
		cout<<"Connection accepted:"<<icon<<endl;
		session = NULL;

		Sleep(1000);
	}

	return 0;
}


//
//struct Arguments
//{
//	int argc;
//	char *argv[10];
//}Args;
//
//std::list<cSShProtocol *> m_Clients;
//
//int main(int argc, char **argv)
//{
//	HANDLE hThreadHandle = NULL;
//	DWORD dwThreadId = -1;
//	ssh_session session = NULL;
//	ssh_channel chan = 0;
//	ssh_bind    sshbind = NULL;
//	int cnt = 0;
//
//	Arguments *Args = new Arguments();
//	Args->argc = argc;
//
//	for(int i = 0; i < argc; i++)
//		Args->argv[i] = *argv;
//
//	//GetSshSessionAndChannel(Args);
//
//	InitializeCriticalSection(&m_csRead);
//
//	hThreadHandle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&GetSshSessionAndChannel, Args, 0, &dwThreadId);
//
//	while(1)
//	{
//		//if(_kbhit())
//		//{
//
//		//}
//		//EnterCriticalSection(&m_csRead);
//		//if(!m_Clients.empty())
//		//{
//			//cnt = m_Clients.size();
//			//if(cnt > 1)
//			//{
//				//ssh_channel_send_eof(m_Clients.front()->chan);
//				//ssh_channel_close(m_Clients.front()->chan);
//				//ssh_free(m_Clients.front()->session);
//				//m_Clients.pop_front();
//			//}
//
//			//session = m_Clients.front()->session;
//			//chan    = m_Clients.front()->chan;
//			//sshbind = m_Clients.front()->sshbind;
//		//}
//		//LeaveCriticalSection(&m_csRead);
//
//
//		//if(!m_Clients.empty())
//		//if(session != NULL && chan != NULL)
//		//{
//			/*if(m_Clients.size() > 1)
//			{
//				//ssh_channel_send_eof(m_Clients.front()->chan);
//				ssh_channel_close(m_Clients.front()->chan);
//				//ssh_free(m_Clients.front()->session);
//				m_Clients.pop_front();
//			}*/
//
//			//if (ssh_channel_is_open(m_Clients.front()->chan) && !ssh_channel_is_eof(m_Clients.front()->chan))
//			//if (ssh_channel_is_open(chan) && !ssh_channel_is_eof(chan))
//			//{
//				//char pReadPt[255];
//				//unsigned int iRxLen = 0;
//				//int iBytes = ssh_channel_read_nonblocking(chan, pReadPt, 255, 0);
//				//if(iBytes > 0)
//				//{
//					//int iError = ssh_channel_write(chan, pReadPt, iBytes);
//					//if(iError == -1)
//						//printf("Error in writing SSH %s", ssh_get_error(session));
//				//}
//			//}
//			//else
//			//{
//				//ssh_channel_close(chan);
//				//ssh_free(session);
//				//ssh_bind_free(sshbind);
//				//ssh_finalize();
//				//break;
//			//}
//		//}
//
//		char input = NULL;
//		bool bStatus = false;
//		printf("I am in main thread\n");
//		cout<<"Enter Q or q for 'Quit' ";
//		cin>>input;
//
//		if(input == 'q' || input == 'Q')
//		{
//			Sleep(500);
//			TerminateThread(hThreadHandle, 0);
//			bStatus = true;
//		}
//
//		Sleep(1000);
//		if(bStatus)
//			break;
//	}
//  
//    return 0;
//}
//
//int GetSshSessionAndChannel(void *pArgs)
//{
//	ssh_bind sshbind;
//    int auth=0;
//    int r;
//    int port = 2000;
//    int verbosity = SSH_LOG_PACKET;
//    int session_count = 0;
//	ssh_message message = 0;
//	int shell=0;
//	char ptr1[9999] = "WELCOME TO ABB SSH SERVER \n";//(char *) malloc(10);
//	int *ptr = (int *)malloc(4);
//	unsigned int uTxLen = 0;
//	unsigned int uRxLen = 0;
//	int iBytes = 0;
//	int iError = -1;
//	char *pReadPtr = (char *)malloc(255);
//	ssh_session session;
//	ssh_channel chan=0;
//	Arguments *Args1 = (Arguments *)pArgs;
//	//cConnection *pConnection;
//
//    //g_thread_init(NULL);
//
//    //ssh_threads_set_callbacks(ssh_threads_get_pthread());
//    if(ssh_init() == -1)
//      {
//      printf("\nError initializing ssh: ssh_init() failed");
//      exit(1);
//      }
//
//    sshbind=ssh_bind_new();
//    //session = (ssh_session *) ssh_new();
//	//session =  ssh_new();
//
//    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_BINDPORT,&port);
//    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_DSAKEY, KEYS_FOLDER "ssh_host_dsa_key");
//    ssh_bind_options_set(sshbind, SSH_BIND_OPTIONS_RSAKEY, KEYS_FOLDER "ssh_host_rsa_key");
//
//    if(ssh_bind_listen(sshbind)<0)
//      {
//      printf("Error listening to socket: %s\n",ssh_get_error(sshbind));
//      return 1;
//      }   
// 
//    while(1)
//         {
//         //session[session_count]=ssh_new();
//         //ssh_options_getopt(session[session_count],&argc,argv);
//         //r=ssh_bind_accept(sshbind,session[session_count]);
//		 
//		 session=ssh_new();
//		 int argc = Args1->argc;
//		 char **argv = Args1->argv;
//         ssh_options_getopt(session,&argc,argv);
//         r=ssh_bind_accept(sshbind,session);
//         if(r==SSH_ERROR)
//           {
//           printf("error accepting a connection : %s\n",ssh_get_error(sshbind));
//           return 2;
//           }
//
//		 IN_ADDR *addr;
//		 SOCKET sSock = ssh_get_fd(session);
//		 SOCKADDR *pName = new SOCKADDR;
//		 int iLen = sizeof(SOCKADDR);
//		 int iErr = getpeername(sSock, pName, &iLen);
//		 addr = (IN_ADDR *)&pName->sa_data[2];
//		 char *ip = NULL;
//
//		 if(iErr != 0)
//			 printf("Error in reading");
//		 else
//		 {
//			 ip = inet_ntoa(*addr);
//
//			 printf("Socket Connected From %s\n", ip);
//			 //inet_addr(pName);
//			 //inet_ntop(AF_INET, &name.sin_addr, buf, sizeof buf);
//		 }
//
//
//
//		 //ssh_options_get(
//
//		 //pConnection = new cConnection();
//         //ssh_options_set(session[session_count], SSH_OPTIONS_LOG_VERBOSITY, &verbosity );
//		 //ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity );
//         //if(ssh_handle_key_exchange(session[session_count]))
//		 if(ssh_handle_key_exchange(session))
//           {
//           //printf("ssh_handle_key_exchange: %s\n",ssh_get_error(session[session_count]));
//			   printf("ssh_handle_key_exchange: %s\n",ssh_get_error(session));
//           return 3;
//           }
//      
//         /* public key authentication */
//         //auth = authenticate_user(session[session_count]);
//		 auth = authenticate_user(session);
//         if(!auth)
//           {
//           //printf("auth error: %s\n",ssh_get_error(session[session_count]));
//			   printf("auth error: %s\n",ssh_get_error(session));
//           //ssh_disconnect(session[session_count]);
//			   ssh_disconnect(session);
//           return 4;
//           }
//         //g_thread_create(server_thread,session[session_count],FALSE,NULL);
//         session_count++;
//
//		 ////Wait for a session and channel request from client
//		 //do 
//		 //{
//			// message = ssh_message_get(session);
//			// if(message)
//			// {
//			//	 if(ssh_message_type(message) == SSH_REQUEST_CHANNEL_OPEN && ssh_message_subtype(message) == SSH_CHANNEL_SESSION) 
//			//	 {
//			//		 chan = ssh_message_channel_request_open_reply_accept(message);
//			//		 ssh_message_free(message);
//			//		 break;
//			//	 } 
//			//	 else 
//			//	 {
//			//		 ssh_message_reply_default(message);
//			//		 ssh_message_free(message);
//			//	 }
//			// } 
//			// else 
//			// {
//			//	 break;
//			// }
//		 //} while(!chan);
//		 //
//		 //if(!chan) 
//		 //{
//			// printf("Error: cleint did not ask for a channel session (%s)\n", ssh_get_error(session));
//			// ssh_finalize();
//			// return 1;
//		 //}
//
//		 ////Wait for a session from ssh client
//		 //do 
//		 //{
//			// message = ssh_message_get(session);
//			// if(message != NULL) 
//			// {
//			//	 if(ssh_message_type(message) == SSH_REQUEST_CHANNEL) 
//			//	 {
//			//		 if(ssh_message_subtype(message) == SSH_CHANNEL_REQUEST_SHELL) 
//			//		 {
//			//			 shell = 1;
//			//			 ssh_message_channel_request_reply_success(message);
//			//			 ssh_message_free(message);
//			//			 break;
//			//		 } 
//			//		 else if(ssh_message_subtype(message) == SSH_CHANNEL_REQUEST_PTY) 
//			//		 {
//			//			 ssh_message_channel_request_reply_success(message);
//			//			 ssh_message_free(message);
//			//			 continue;
//			//		 }
//			//	 }
//			//	 ssh_message_reply_default(message);
//			//	 ssh_message_free(message);
//			// } 
//			// else 
//			// {
//			//	 break;
//			// }
//		 //} while(!shell);
//		 //
//		 //if(!shell) 
//		 //{
//			// printf("Error: No shell requested (%s)\n", ssh_get_error(session));
//			// return 1;
//		 //}
//
//		 ////char *ClientReq = "Enter Password: ";
//		 ////CHAR ptr = 'a';
//		 ////unsigned char char1 = 'a';
//		 //uTxLen = strlen(ptr1);
//		 //iBytes = ssh_channel_write(chan, ptr1, uTxLen);
//		 //		 
//		 //if(iBytes < 0)
//			// printf("Error: Channel write failed -- (%s)\n", ssh_get_error(session));
//		 //else
//		 //{
//			// printf("Error: Channel write Successful -- (%s)\n");
//			// //iError = ssh_channel_send_eof(chan);
//			// //if(iError < 0)
//			//	 //printf("Error: Channel write failed eof -- (%s)\n", ssh_get_error(session));
//		 //}
//
//		 if(session != NULL)
//		 {
//			 cSShProtocol *pPtr;
//			 if(!m_Clients.empty())
//			 {
//				 pPtr = m_Clients.front();
//				 pPtr->Stop();
//				 delete pPtr;
//				 m_Clients.pop_front();
//			 }
//
//		 }
//
//		 /*pConnection->sshbind = sshbind;
//		 pConnection->chan	  = chan;
//		 pConnection->session = session;
//		 pConnection->m_bChannelClosingRequest = false;*/
//
//         //cSShProtocol *pProtocolHandle = new cSShProtocol(pConnection);
//		 cSShProtocol *pProtocolHandle = new cSShProtocol();
//		 m_Clients.push_back(pProtocolHandle);
//         //pProtocolHandle->Start(pConnection);
//		 pProtocolHandle->Start(session);
//
//
//		 /*
//		 EnterCriticalSection(&m_csRead);
//		 m_Clients.push_back(pConnection);
//		 LeaveCriticalSection(&m_csRead);
//		 */
//
//		 /*while (ssh_channel_is_open(chan) && !ssh_channel_is_eof(chan))
//		 {
//			char *pReadPt = (char *)malloc(255);
//			unsigned int iRxLen = 0;
//			iBytes = ssh_channel_read(chan, ptr1, uTxLen, 0);
//		 }*/
//
//		 session = NULL;
//		 chan = 0;
//
//		 Sleep(2000);
//
//		 }//While(1)
//
//	return 0;
//}


Follow-Ups:
RE: SSH.dll crash problemalvesfonseca@xxxxxxxxxxxx
References:
FW: SSH.dll crash problemRavikumar Sunkari <Ravikumar.Sunkari@xxxxxxxxxxxxxx>
Archive administrator: postmaster@lists.cynapses.org