#include "bot.h"
void Bot::SOCK_CON()
{
#ifdef _WIN32
WSADATA wsaData;
WSAStartup(MAKEWORD(1,1), &wsaData);
#endif
if( SOCK_CREATE() == true) Login();
}
void Bot::SOCK_DISCON()
{
#ifdef _WIN32
shutdown(sock, SD_BOTH);
close(sock);
WSACleanup();
#else
close(sock);
#endif
Connected = false;
printf("Socket Closed\n");
}
void Bot::Login()
{
if(!strcmp(Client,"TAHC"))
{
Connected = true;
APACKET0("\x03\x04%s\r\n%s\r\n/join %s\r\n", Username, Password, Channel);
}
else
{
send(sock,"\x01",1,0);
SP_0x50();
}
SOCK_HANDLER();
}
bool Bot::SOCK_CREATE()
{
struct hostent *h;
struct sockaddr_in their_addr;
// if this is a hostname and not an IP address, resolve it
char *p = Server;
while (*p && (isdigit(*p) || (*p == '.')))
p++;
if ((h=gethostbyname(Server)) == NULL)
{
printf("gethostbyname error\n");
return 0;
}
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
printf("socket error \n");
return 0;
}
their_addr.sin_family = AF_INET;
their_addr.sin_port = htons(6112);
if (*p)
their_addr.sin_addr = *((struct in_addr *)h->h_addr);
else
their_addr.sin_addr.s_addr = inet_addr(Server);
//bzero(&(their_addr.sin_zero), 8);
if (connect(sock, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1)
{
printf("connect error\n");
return 0;
}
return 1;
}
void Bot::SOCK_HANDLER()
{
int numbytes;
int nBufLen=0;
int nBufPos=0;
char stageBuf[2048];
while(1)
{
int nNumToRead = 2048 - nBufLen - nBufPos;
if (nNumToRead == 0)
{
memmove(stageBuf, stageBuf+nBufPos, nBufLen);
nBufPos = 0;
nNumToRead = 2048 - nBufLen;
}
numbytes = recv(sock, stageBuf + nBufPos + nBufLen, nNumToRead, 0);
if (numbytes <= 0)
{
printf("\nSOCK_HANDLERB() ERROR\n");
return;
}
nBufLen += numbytes;
while (nBufLen > 0)
{
char *m = stageBuf + nBufPos;
int packetlen = 0;
if(!strcmp(Client,"TAHC"))
{
while (packetlen < nBufLen)
{
if (m[packetlen] == '\n') break;
packetlen++;
}
packetlen++;
}
else
{
if ((unsigned char)m[0] != (unsigned char)0xFF)
{
printf("\nNOT A 0xFF HHEADER\n");
hexdump(m,numbytes);
break;
}
packetlen = *(unsigned short*)( m + 2 );
}
if (packetlen > nBufLen) break;
if((PSB == SB) && (Dump==true))
hexdump(m,packetlen);
if(!strcmp(Client,"TAHC"))
{
m[packetlen - 1] = '\0';
//if (isdigit(*m))
CDispatch(m);
}
else
{// add to cut that extra shit with like memcpy(m,m,packetlen); then a m[packetlen+1] ="/0";
RP_HANDLER(m[1], m,packetlen);
}
nBufLen -= packetlen;
nBufPos += packetlen;
}
if (!nBufLen) nBufPos = 0;
}
}