Ejemplo n.º 1
0
bool send_init_oft2(file_transfer *ft, char* file)
{
	aimString astr(file);

	unsigned short len = max(0x100, 0xc0 + astr.getTermSize());

	oft2 *oft = (oft2*)alloca(len);
	memset(oft, 0, len);

	memcpy(oft->protocol_version, "OFT2", 4);
	oft->length = _htons(len);
	oft->type = 0x0101;
	oft->total_files = _htons(ft->pfts.totalFiles);
	oft->num_files_left = _htons(ft->pfts.totalFiles - ft->pfts.currentFileNumber);
	oft->total_parts = _htons(1);
	oft->parts_left = _htons(1);
	oft->total_size = _htonl(ft->pfts.totalBytes);
	oft->size = _htonl(ft->pfts.currentFileSize);
	oft->mod_time = _htonl(ft->pfts.currentFileTime);
	oft->checksum = _htonl(aim_oft_checksum_file(ft->pfts.tszCurrentFile));
	oft->recv_RFchecksum = 0x0000FFFF;
	oft->RFchecksum = 0x0000FFFF;
	oft->recv_checksum = 0x0000FFFF;
	memcpy(oft->idstring, "Cool FileXfer", 13);
	oft->flags = 0x20;
	oft->list_name_offset = 0x1c;
	oft->list_size_offset = 0x11;
	oft->encoding = _htons(astr.isUnicode() ? 2 : 0);
	memcpy(oft->filename, astr.getBuf(), astr.getTermSize());

	if (!ft->requester || ft->pfts.currentFileNumber)
		memcpy(oft->icbm_cookie, ft->icbm_cookie, 8);

	return Netlib_Send(ft->hConn, (char*)oft, len, 0) > 0;
}
Ejemplo n.º 2
0
int TlenWsSendAES(TlenProtocol *proto, char *data, int datalen, aes_context *aes_ctx, unsigned char *aes_iv)
{
	int len, sendlen;
	unsigned char aes_input[16];
	unsigned char aes_output[256];
	if (proto->threadData == NULL) {
		return FALSE;
	}
	while (datalen > 0) {
		len = 0;
		while (datalen > 0 && len < 256) {
			int pad = datalen < 16 ? 16 - datalen : 0;
			memcpy(aes_input, data, datalen < 16 ? datalen : 16);
			memset(aes_input + 16 - pad, ' ', pad);
			aes_crypt_cbc(aes_ctx, AES_ENCRYPT, 16, aes_iv, aes_input, aes_output + len);
			datalen -= 16;
			data += 16;
			len += 16;
		}
		if (len > 0) {
			proto->debugLogA("Sending %d bytes", len);
			if ((sendlen=Netlib_Send(proto->threadData->s, (char *)aes_output, len, MSG_NODUMP)) == SOCKET_ERROR || len != sendlen) {
				proto->debugLogA("Netlib_Send() failed, error=%d", WSAGetLastError());
				return FALSE;
			}
		}
	}
	return TRUE;
}
Ejemplo n.º 3
0
void CLHttpUser::SendRedir(int iErrorCode, const char * pszError, const char * pszDescription, const char * pszRedirect) {
	char szCurrTime[ 100 ];
	time_t ltime;
	time(&ltime);
	strftime(szCurrTime, sizeof(szCurrTime), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&ltime));

	if (!pszDescription)
		pszDescription = pszError;

	char szBuff[1000];
	DWORD dwBytesToWrite = mir_snprintf(szBuff, SIZEOF(szBuff),
	    "HTTP/1.1 %i %s\r\n"
	    "Date: %s\r\n"
	    "Server: MirandaWeb/%s\r\n"
	    "Location: %s/\r\n"
	    "Transfer-Encoding: chunked\r\n"
	    "Content-Type: text/html; charset=iso-8859-1\r\n"
	    "\r\n"
	    "10f\r\n"
	    "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
	    "<HTML><HEAD>\n"
	    "<TITLE>%i %s</TITLE>\n"
	    "</HEAD><BODY>\n"
	    "<H1>%s</H1>\n"
	    "%s<P>\n"
	    "<HR>\n"
	    "<ADDRESS>MirandaWeb/%s</ADDRESS>\n"
	    "</BODY></HTML>\n"
	    "\r\n"
	    "\r\n",
	    iErrorCode, pszError, szCurrTime, PLUGIN_MAKE_VERSION(__MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM), pszRedirect, iErrorCode, pszError, pszError, pszDescription, PLUGIN_MAKE_VERSION(__MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM));

	Netlib_Send(hConnection, szBuff, dwBytesToWrite, 0);
}
Ejemplo n.º 4
0
int TlenWsSend(TlenProtocol *proto, HANDLE s, char *data, int datalen)
{
	int len;
	if ((len=Netlib_Send(s, data, datalen, /*MSG_NODUMP|*/MSG_DUMPASTEXT)) == SOCKET_ERROR || len != datalen) {
	proto->debugLogA("Netlib_Send() failed, error=%d", WSAGetLastError());
		return FALSE;
	}
	return TRUE;
}
Ejemplo n.º 5
0
int __cdecl SessionWrite(mwSession* session, const unsigned char* buf, gsize len)
{
	CSametimeProto* proto = (CSametimeProto*)mwSession_getProperty(session, "PROTO_STRUCT_PTR");
	proto->debugLog(_T("SessionWrite()  server_connection=[%d], len=[%d]"), proto->server_connection, len);
	if (!proto->server_connection) return 1;
	if (Netlib_Send(proto->server_connection, (const char*)buf, len, 0) == SOCKET_ERROR)
		return 1;
	return 0;
}
Ejemplo n.º 6
0
int JabberWsSend(JABBER_SOCKET hConn, char *data, int datalen)
{
	int len;

	if ((len=Netlib_Send(hConn, data, datalen, /*MSG_NODUMP|*/MSG_DUMPASTEXT))==SOCKET_ERROR || len!=datalen) {
		JabberLog("Netlib_Send() failed, error=%d", WSAGetLastError());
		return FALSE;
	}
	return TRUE;
}
Ejemplo n.º 7
0
void upload_avt(int id, INT_PTR fd, int error, void *data)
{
	struct yahoo_file_info *sf = (struct yahoo_file_info*) data;
	unsigned long size = 0;
	char buf[1024];
	int rw;			/* */
	DWORD dw;		/* needed for ReadFile */
	HANDLE myhFile;

	if (fd < 1 || error) {
		LOG(("[get_fd] Connect Failed!"));
		return;
	}

	myhFile = CreateFileA(sf->filename,
		GENERIC_READ,
		FILE_SHARE_READ | FILE_SHARE_WRITE,
		NULL,
		OPEN_EXISTING,
		FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
		0);

	if (myhFile == INVALID_HANDLE_VALUE) {
		LOG(("[get_fd] Can't open file for reading?!"));
		return;
	}

	LOG(("Sending file: %s size: %ld", sf->filename, sf->filesize));

	do {
		rw = ReadFile(myhFile, buf, sizeof(buf), &dw, NULL);

		if (rw != 0) {
			rw = Netlib_Send((HANDLE)fd, buf, dw, MSG_NODUMP);

			if (rw < 1) {
				LOG(("Upload Failed. Send error?"));
				//ShowError(Translate("Yahoo Error"), Translate("Avatar upload failed!?!"));
				break;
			}

			size += rw;
		}
	} while (rw >= 0 && size < sf->filesize);

	CloseHandle(myhFile);

	do {
		rw = Netlib_Recv((HANDLE)fd, buf, sizeof(buf), 0);
		LOG(("Got: %d bytes", rw));
	} while (rw > 0);

	LOG(("File send complete!"));
}
Ejemplo n.º 8
0
int CJabberProto::WsSend(JABBER_SOCKET hConn, char* data, int datalen, int flags)
{
	m_lastTicks = ::GetTickCount();
	int len;

	if ((len = Netlib_Send(hConn, data, datalen, flags)) == SOCKET_ERROR || len != datalen) {
		debugLogA("Netlib_Send() failed, error=%d", WSAGetLastError());
		return SOCKET_ERROR;
	}
	return len;
}
Ejemplo n.º 9
0
LPCOMMANDPROC SendCommand(HWND wnd, int command, int value)
{
    switch (command)
    {
    case WAT_CTRL_PREV:
        Netlib_Send(ghConnection, "previous\n", (int)strlen("previous\n"), 0);
        break;
    case WAT_CTRL_PLAY: //add resuming support
        if(gbState != WAT_PLS_PAUSED)
            Netlib_Send(ghConnection, "play\n", (int)strlen("play\n"), 0);
        else
            Netlib_Send(ghConnection, "pause 0\n", (int)strlen("pause 0\n"), 0);
        break;
    case WAT_CTRL_PAUSE:
        Netlib_Send(ghConnection, "pause 1\n", (int)strlen("pause 1\n"), 0);
        break;
    case WAT_CTRL_STOP:
        Netlib_Send(ghConnection, "stop\n", (int)strlen("stop\n"), 0);
        break;
    case WAT_CTRL_NEXT:
        Netlib_Send(ghConnection, "next\n", (int)strlen("next\n"), 0);
        break;
    case WAT_CTRL_VOLDN:
        break;
    case WAT_CTRL_VOLUP:
        break;
    case WAT_CTRL_SEEK:
        break;
    default:
        break;
    }
    return 0;
}
Ejemplo n.º 10
0
int SendCommand(HWND, int command, int)
{
	switch (command)
	{
	case WAT_CTRL_PREV:
		Netlib_Send(ghConnection, "previous\n", (int)mir_strlen("previous\n"), 0);
		return 0;
	case WAT_CTRL_PLAY: //add resuming support
		if(gbState != WAT_PLS_PAUSED)
			Netlib_Send(ghConnection, "play\n", (int)mir_strlen("play\n"), 0);
		else
			Netlib_Send(ghConnection, "pause 0\n", (int)mir_strlen("pause 0\n"), 0);
		return 0;
	case WAT_CTRL_PAUSE:
		Netlib_Send(ghConnection, "pause 1\n", (int)mir_strlen("pause 1\n"), 0);
		return 0;
	case WAT_CTRL_STOP:
		Netlib_Send(ghConnection, "stop\n", (int)mir_strlen("stop\n"), 0);
		return 0;
	case WAT_CTRL_NEXT:
		Netlib_Send(ghConnection, "next\n", (int)mir_strlen("next\n"), 0);
		return 0;
	case WAT_CTRL_VOLDN:
		return 0;
	case WAT_CTRL_VOLUP:
		return 0;
	case WAT_CTRL_SEEK:
		return 0;
	default:
		return 0;
	}
}
Ejemplo n.º 11
0
int icq_httpGatewayWalkTo(HANDLE hConn, NETLIBOPENCONNECTION* nloc)
{ // this is bad simplification - for avatars to work we need to handle
	// two "virtual connections" at the same time
	icq_packet packet;
	DWORD dwGatewaySeq = GetGatewayIndex(hConn);

	packet.wLen = 0;
	write_httphdr(&packet, HTTP_PACKETTYPE_CLOSE, dwGatewaySeq);
	Netlib_Send(hConn, (char*)packet.pData, packet.wLen, MSG_DUMPPROXY|MSG_NOHTTPGATEWAYWRAP);
	// we closed virtual connection, open new one
	dwGatewaySeq++;
	SetGatewayIndex(hConn, dwGatewaySeq);
	return icq_httpGatewayBegin(hConn, nloc);
}
Ejemplo n.º 12
0
void FromServerToClient(LPVOID lParam) {
	char buf[1024] = { 0 };

	HANDLE hConnection = (HANDLE)lParam;
	do {
		if (!hBindPort) return;

		int cbRead = Netlib_Recv(netlibcon, buf, sizeof(buf), 0);
		if (cbRead == SOCKET_ERROR)
			break;

		if (cbRead) {
			Netlib_Send(hConnection, buf, cbRead, 0);
		}
	} while (1);
}
Ejemplo n.º 13
0
int PASCAL send(SOCKET s, const char FAR *buf, int len, int flags)
{
	int rlen = Netlib_Send((HANDLE)s, buf, len, 0);

#ifdef HTTP_GATEWAY				
	if (iHTTPGateway)
		lLastSend = time(NULL);
#endif

	if (rlen == SOCKET_ERROR) {
		LOG(("SEND Error."));
		return -1;
	}

	return len;
}
Ejemplo n.º 14
0
int icq_httpGatewayWrapSend( HANDLE hConn, PBYTE buf, int len, int flags, MIRANDASERVICE pfnNetlibSend )
{
	icq_packet packet;
	int sendResult;

	packet.wLen = len;
	write_httphdr( &packet, HTTP_PACKETTYPE_FLAP );
	packString( &packet, buf, ( WORD )len );
	sendResult = Netlib_Send( hConn, packet.pData, packet.wLen, flags );
	mir_free( packet.pData );
	if( sendResult <= 0 )
		return sendResult;
	if( sendResult < 14 )
		return 0;
	return sendResult - 14;
}
Ejemplo n.º 15
0
int avatars_server_connection::sendServerPacket(icq_packet *pPacket)
{
	int lResult = 0;

	// This critsec makes sure that the sequence order doesn't get screwed up
	localSeqMutex->Enter();

	if (hConnection)
	{
		int nRetries;
		int nSendResult;

		// :IMPORTANT:
		// The FLAP sequence must be a WORD. When it reaches 0xFFFF it should wrap to
		// 0x0000, otherwise we'll get kicked by server.
		wLocalSequence++;

		// Pack sequence number
		pPacket->pData[2] = ((wLocalSequence & 0xff00) >> 8);
		pPacket->pData[3] = (wLocalSequence & 0x00ff);

		for (nRetries = 3; nRetries >= 0; nRetries--)
		{
			nSendResult = Netlib_Send(hConnection, (const char *)pPacket->pData, pPacket->wLen, 0);

			if (nSendResult != SOCKET_ERROR)
				break;

			Sleep(1000);
		}

		// Send error
		if (nSendResult == SOCKET_ERROR)
		{ // thread stops automatically
			ppro->debugLogA("Your connection with the ICQ avatar server was abortively closed");
		}
		else
		{
			lResult = 1; // packet sent successfully

			icq_lock l(m_ratesMutex);
			if (m_rates)
				m_rates->packetSent(pPacket);
		}
	}
	else
	{
Ejemplo n.º 16
0
DWORD CMraProto::MraSendPacket(HANDLE hConnection, DWORD dwCmdNum, DWORD dwType, LPVOID lpData, size_t dwDataSize)
{
	LPBYTE lpbData = (LPBYTE)_alloca(dwDataSize + sizeof(mrim_packet_header_t));

	mrim_packet_header_t *pmaHeader = (mrim_packet_header_t*)lpbData;
	memset(pmaHeader, 0, sizeof(mrim_packet_header_t));
	pmaHeader->magic = CS_MAGIC;
	pmaHeader->proto = (PROTO_VERSION_MAJOR << 16) + PROTO_VERSION_MINOR; // Версия протокола
	pmaHeader->seq = dwCmdNum;// Sequence
	pmaHeader->msg = dwType;// Тип пакета
	pmaHeader->dlen = (unsigned)dwDataSize;// Длина данных

	debugLogA("Sending packet %08x\n", dwType);

	memcpy((lpbData + sizeof(mrim_packet_header_t)), lpData, dwDataSize);
	return Netlib_Send(hConnection, (LPSTR)lpbData, (int)(dwDataSize + sizeof(mrim_packet_header_t)), 0);
}
Ejemplo n.º 17
0
void CIcqProto::sendServPacket(icq_packet *pPacket)
{
	// make sure to have the connection handle
	connectionHandleMutex->Enter();

	if (hServerConn)
	{
		int nSendResult;

		// This critsec makes sure that the sequence order doesn't get screwed up
		localSeqMutex->Enter();

		// :IMPORTANT:
		// The FLAP sequence must be a WORD. When it reaches 0xFFFF it should wrap to
		// 0x0000, otherwise we'll get kicked by server.
		wLocalSequence++;

		// Pack sequence number
		pPacket->pData[2] = ((wLocalSequence & 0xff00) >> 8);
		pPacket->pData[3] = (wLocalSequence & 0x00ff);

		nSendResult = Netlib_Send(hServerConn, (const char *)pPacket->pData, pPacket->wLen, 0);

		localSeqMutex->Leave();
		connectionHandleMutex->Leave();

		// Send error
		if (nSendResult == SOCKET_ERROR)
		{
			icq_LogUsingErrorCode(LOG_ERROR, GetLastError(), LPGEN("Your connection with the ICQ server was abortively closed"));
			icq_serverDisconnect(FALSE);

			if (m_iStatus != ID_STATUS_OFFLINE)
			{
				SetCurrentStatus(ID_STATUS_OFFLINE);
			}
		}
		else
		{ // Rates management
			icq_lock l(m_ratesMutex);
			m_rates->packetSent(pPacket);
		}

	}
	else
	{
Ejemplo n.º 18
0
int icq_httpGatewayBegin(HANDLE hConn, NETLIBOPENCONNECTION* nloc)
{ // open our "virual data connection"
	icq_packet packet;
	size_t serverNameLen;

	serverNameLen = strlennull(nloc->szHost);

	packet.wLen = (WORD)(serverNameLen + 4);
	write_httphdr(&packet, HTTP_PACKETTYPE_LOGIN, GetGatewayIndex(hConn));
	packWord(&packet, (WORD)serverNameLen);
	packBuffer(&packet, (LPBYTE)nloc->szHost, (WORD)serverNameLen);
	packWord(&packet, nloc->wPort);
	INT_PTR res = Netlib_Send(hConn, (char*)packet.pData, packet.wLen, MSG_DUMPPROXY|MSG_NOHTTPGATEWAYWRAP);
	SAFE_FREE((void**)&packet.pData);

	return res != SOCKET_ERROR;
}
Ejemplo n.º 19
0
int proxy_initialize_send(HANDLE connection, char* sn, char* cookie)
{
	const char sn_length = (char)strlen(sn);
	const int len = sn_length + 21 + TLV_HEADER_SIZE + AIM_CAPS_LENGTH;

	char* buf= (char*)_malloca(len);
	unsigned short offset=0;

	aim_writeshort(len-2, offset, buf);
	aim_writegeneric(10, "\x04\x4a\0\x02\0\0\0\0\0\0", offset, buf);
	aim_writechar((unsigned char)sn_length, offset, buf);               // screen name len
	aim_writegeneric(sn_length, sn, offset, buf);                       // screen name
	aim_writegeneric(8, cookie, offset, buf);                           // icbm cookie
	aim_writetlv(1, AIM_CAPS_LENGTH, AIM_CAP_FILE_TRANSFER, offset, buf);

	return Netlib_Send(connection, buf, offset, 0) >= 0 ? 0 : -1; 
}
Ejemplo n.º 20
0
//xfireclient baut verbindung auf
void XfireclientConnecting(HANDLE hConnection, DWORD, void* extra )
{
	char buf[1024]={0};

	//verbindung zum richtigen xfire server aufbauen
	NETLIBOPENCONNECTION ncon = { 0 };
	ncon.cbSize = sizeof(ncon);
	ncon.szHost = "206.220.42.147";
	ncon.wPort = (WORD)atol("25999");
	ncon.timeout=5;
	netlibcon = (HANDLE) CallService(MS_NETLIB_OPENCONNECTION, (WPARAM) hNetlib, (LPARAM) & ncon);

	if (!netlibcon) {
		Netlib_CloseHandle(hConnection);
	}

	mir_forkthread(FromServerToClient,(LPVOID)hConnection);

	//schleife behandelt empfangende daten
	do {
		int cbRead = Netlib_Recv(hConnection, buf, sizeof(buf), 0);
		if ( cbRead == SOCKET_ERROR)
		{
			Netlib_CloseHandle(hConnection);
			Netlib_CloseHandle(netlibcon);
			break;
		}

		if (cbRead) {
			if (!Netlib_Send(netlibcon, buf, cbRead, 0))
			{
				Netlib_CloseHandle(hConnection);
				Netlib_CloseHandle(netlibcon);
				break;
			}
		}
	}
	while(1);
}
Ejemplo n.º 21
0
static BOOL JabberFtSend( HANDLE hConn, void *userdata )
{
	filetransfer* ft = ( filetransfer* ) userdata;

	struct _stat statbuf;
	int fd;
	char* buffer;
	int numRead;

	JabberLog( "Sending [%s]", ft->std.files[ ft->std.currentFileNumber ] );
	_stat( ft->std.files[ ft->std.currentFileNumber ], &statbuf );	// file size in statbuf.st_size
	if (( fd=_open( ft->std.files[ ft->std.currentFileNumber ], _O_BINARY|_O_RDONLY )) < 0 ) {
		JabberLog( "File cannot be opened" );
		return FALSE;
	}

	ft->std.sending = TRUE;
	ft->std.currentFileSize = statbuf.st_size;
	ft->std.currentFileProgress = 0;

	if (( buffer=( char* )mir_alloc( 2048 )) != NULL ) {
		while (( numRead=_read( fd, buffer, 2048 )) > 0 ) {
			if ( Netlib_Send( hConn, buffer, numRead, 0 ) != numRead ) {
				mir_free( buffer );
				_close( fd );
				return FALSE;
			}
			ft->std.currentFileProgress += numRead;
			ft->std.totalProgress += numRead;
			JSendBroadcast( ft->std.hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, ( LPARAM )&ft->std );
		}
		mir_free( buffer );
	}
	_close( fd );
	return TRUE;
}
Ejemplo n.º 22
0
int CAimProto::sending_file(file_transfer *ft, HANDLE hServerPacketRecver, NETLIBPACKETRECVER &packetRecv)
{
	debugLogA("P2P: Entered file sending thread.");

	bool failed = true;
	bool failed_conn = false;

	if (!setup_next_file_send(ft)) return 2;

	debugLogA("Sent file information to buddy.");
	//start listen for packets stuff

	for (;;) {
		int recvResult = packetRecv.bytesAvailable - packetRecv.bytesUsed;
		if (recvResult <= 0)
			recvResult = CallService(MS_NETLIB_GETMOREPACKETS, (WPARAM)hServerPacketRecver, (LPARAM)&packetRecv);
		if (recvResult == 0) {
			debugLogA("P2P: File transfer connection Error: 0");
			break;
		}
		if (recvResult == SOCKET_ERROR) {
			failed_conn = true;
			debugLogA("P2P: File transfer connection Error: -1");
			break;
		}
		if (recvResult > 0) {
			if (recvResult < 0x100) continue;

			oft2* recv_ft = (oft2*)&packetRecv.buffer[packetRecv.bytesUsed];

			unsigned short pkt_len = _htons(recv_ft->length);
			if (recvResult < pkt_len) continue;

			packetRecv.bytesUsed += pkt_len;
			unsigned short type = _htons(recv_ft->type);
			if (type == 0x0202 || type == 0x0207) {
				debugLogA("P2P: Buddy Accepts our file transfer.");

				int fid = _topen(ft->pfts.tszCurrentFile, _O_RDONLY | _O_BINARY, _S_IREAD);
				if (fid < 0) {
					report_file_error(ft->pfts.tszCurrentFile);
					return 2;
				}

				if (ft->pfts.currentFileProgress) _lseeki64(fid, ft->pfts.currentFileProgress, SEEK_SET);

				NETLIBSELECT tSelect = { 0 };
				tSelect.cbSize = sizeof(tSelect);
				tSelect.hReadConns[0] = ft->hConn;

				ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->pfts);

				clock_t lNotify = clock();
				for (;;) {
					char buffer[4096];
					int bytes = _read(fid, buffer, sizeof(buffer));
					if (bytes <= 0) break;

					if (Netlib_Send(ft->hConn, buffer, bytes, MSG_NODUMP) <= 0) break;
					ft->pfts.currentFileProgress += bytes;
					ft->pfts.totalProgress += bytes;

					if (clock() >= lNotify) {
						ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->pfts);
						if (CallService(MS_NETLIB_SELECT, 0, (LPARAM)&tSelect)) break;

						lNotify = clock() + 500;
					}
				}
				ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->pfts);
				debugLogA("P2P: Finished sending file bytes.");
				_close(fid);
			}
			else if (type == 0x0204) {
				// Handle file skip case
				if (ft->pfts.currentFileProgress == 0) {
					ft->pfts.totalProgress += ft->pfts.currentFileSize;
				}

				debugLogA("P2P: Buddy says they got the file successfully");
				if ((ft->pfts.currentFileNumber + 1) < ft->pfts.totalFiles) {
					ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
					++ft->pfts.currentFileNumber; ++ft->cf;

					if (!setup_next_file_send(ft)) {
						report_file_error(ft->pfts.tszCurrentFile);
						return 2;
					}
				}
				else {
					failed = _htonl(recv_ft->recv_bytes) != ft->pfts.currentFileSize;
					break;
				}
			}
			else if (type == 0x0205) {
				recv_ft = (oft2*)packetRecv.buffer;
				recv_ft->type = _htons(0x0106);

				ft->pfts.currentFileProgress = _htonl(recv_ft->recv_bytes);
				if (aim_oft_checksum_file(ft->pfts.tszCurrentFile, ft->pfts.currentFileProgress) != _htonl(recv_ft->recv_checksum)) {
					ft->pfts.currentFileProgress = 0;
					recv_ft->recv_bytes = 0;
				}

				debugLogA("P2P: Buddy wants us to start sending at a specified file point. (%I64u)", ft->pfts.currentFileProgress);
				if (Netlib_Send(ft->hConn, (char*)recv_ft, _htons(recv_ft->length), 0) <= 0) break;

				ft->pfts.totalProgress += ft->pfts.currentFileProgress;
				ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->pfts);
			}
		}
	}

	ft->success = !failed;
	return failed ? (failed_conn ? 1 : 2) : 0;
}
Ejemplo n.º 23
0
void CJabberProto::ByteSendViaProxy( JABBER_BYTE_TRANSFER *jbt )
{
	TCHAR *szHost, *szPort;
	WORD port;
	HANDLE hConn;
	char data[3];
	char* buffer;
	int datalen, bytesParsed, recvResult;
	BOOL validStreamhost;

	if ( jbt == NULL ) return;
	if (( buffer=( char* )mir_alloc( JABBER_NETWORK_BUFFER_SIZE )) == NULL ) {
		m_ThreadInfo->send( XmlNodeIq( _T("error"), jbt->iqId, jbt->srcJID )
			<< XCHILD( _T("error")) << XATTRI( _T("code"), 406 ) << XATTR( _T("type"), _T("auth"))
			<< XCHILDNS( _T("not-acceptable"), _T("urn:ietf:params:xml:ns:xmpp-stanzas")));
		return;
	}

	jbt->state = JBT_INIT;
	validStreamhost = FALSE;
	szPort = jbt->szProxyPort;
	szHost = jbt->szProxyHost;

	port = ( WORD )_ttoi( szPort );
	if ( jbt->streamhostJID ) mir_free( jbt->streamhostJID );
	jbt->streamhostJID = mir_tstrdup( jbt->szProxyJid );

	NETLIBOPENCONNECTION nloc = { 0 };
	nloc.cbSize = sizeof( nloc );
	nloc.szHost = mir_t2a(szHost);
	nloc.wPort = port;
	hConn = ( HANDLE ) JCallService( MS_NETLIB_OPENCONNECTION, ( WPARAM ) m_hNetlibUser, ( LPARAM )&nloc );
	mir_free((void*)nloc.szHost);

	if ( hConn != NULL ) {
		jbt->hConn = hConn;

		data[0] = 5;
		data[1] = 1;
		data[2] = 0;
		Netlib_Send( hConn, data, 3, 0 );

		jbt->state = JBT_INIT;
		datalen = 0;
		while ( jbt->state!=JBT_DONE && jbt->state!=JBT_ERROR && jbt->state!=JBT_SOCKSERR ) {
			recvResult = Netlib_Recv( hConn, buffer+datalen, JABBER_NETWORK_BUFFER_SIZE-datalen, 0 );
			if ( recvResult <= 0 )
				break;

			datalen += recvResult;
			bytesParsed = ByteSendProxyParse( hConn, jbt, buffer, datalen );
			if ( bytesParsed < datalen )
				memmove( buffer, buffer+bytesParsed, datalen-bytesParsed );
			datalen -= bytesParsed;
			if ( jbt->state == JBT_DONE ) validStreamhost = TRUE;
		}
		Netlib_CloseHandle( hConn );
	}
	mir_free( buffer );
	(this->*jbt->pfnFinal)(( jbt->state == JBT_DONE ) ? TRUE : FALSE, jbt->ft );
	jbt->ft = NULL;
	if ( !validStreamhost )
		m_ThreadInfo->send( XmlNodeIq( _T("error"), jbt->iqId, jbt->srcJID )
			<< XCHILD( _T("error")) << XATTRI( _T("code"), 404 ) << XATTR( _T("type"), _T("cancel"))
			<< XCHILDNS( _T("item-not-found"), _T("urn:ietf:params:xml:ns:xmpp-stanzas")));
}
Ejemplo n.º 24
0
int CJabberProto::ByteSendProxyParse( HANDLE hConn, JABBER_BYTE_TRANSFER *jbt, char* buffer, int datalen )
{
	int num = datalen;

	switch ( jbt->state ) {
	case JBT_INIT:
		// received:
		// 00-00 ver ( 0x05 )
		// 01-01 selected method ( 0=no auth, 0xff=error )
		// send:
		// 00-00 ver ( 0x05 )
		// 01-01 cmd ( 1=connect )
		// 02-02 reserved ( 0 )
		// 03-03 address type ( 3 )
		// 04-44 dst.addr ( 41 bytes: 1-byte length, 40-byte SHA1 hash of [sid,srcJID,dstJID] )
		// 45-46 dst.port ( 0 )
		if ( datalen==2 && buffer[0]==5 && buffer[1]==0 ) {
			BYTE data[47];
			ZeroMemory( data, sizeof( data ));
			*(( DWORD* )data ) = 0x03000105;
			data[4] = 40;

			TCHAR text[256];

			TCHAR *szInitiatorJid = JabberPrepareJid(jbt->srcJID);
			TCHAR *szTargetJid = JabberPrepareJid(jbt->dstJID);
			mir_sntprintf( text, SIZEOF( text ), _T("%s%s%s"), jbt->sid, szInitiatorJid, szTargetJid );
			mir_free(szInitiatorJid);
			mir_free(szTargetJid);

			char* szAuthString = mir_utf8encodeT( text );
			Log( "Auth: '%s'", szAuthString );
			char* szHash = JabberSha1( szAuthString );
			strncpy(( char* )( data+5 ), szHash, 40 );
			mir_free( szHash );
			Netlib_Send( hConn, ( char* )data, 47, 0 );
			jbt->state = JBT_CONNECT;
			mir_free( szAuthString );
		}
		else jbt->state = JBT_SOCKSERR;
		break;

	case JBT_CONNECT:
		// received:
		// 00-00 ver ( 0x05 )
		// 01-01 reply ( 0=success,2=not allowed )
		// 02-02 reserved ( 0 )
		// 03-03 address type ( 1=IPv4 address,3=host address )
		// 04-mm bnd.addr server bound address ( 4-byte IP if IPv4, 1-byte length + n-byte host address string if host address )
		// nn-nn+1 bnd.port server bound port
		if ( datalen>=5 && buffer[0]==5 && buffer[1]==0 && ( buffer[3]==1 || buffer[3]==3 || buffer[3]==0 )) {
			if ( buffer[3]==1 && datalen>=10 )
				num = 10;
			else if ( buffer[3]==3 && datalen>=buffer[4]+7 )
				num = buffer[4] + 7;
			else if ( buffer[3]==0 && datalen>=6 )
				num = 6;
			else {
				jbt->state = JBT_SOCKSERR;
				break;
			}
			jbt->state = JBT_SENDING;

			jbt->hProxyEvent = CreateEvent( NULL, FALSE, FALSE, NULL );
			jbt->bStreamActivated = FALSE;

			int iqId = SerialNext();

			TCHAR listJid[256];
			mir_sntprintf(listJid, SIZEOF( listJid ), _T("ftproxy_%d"), iqId);

			JABBER_LIST_ITEM *item = ListAdd( LIST_FTIQID, listJid );
			item->jbt = jbt;

			IqAdd( iqId, IQ_PROC_NONE, &CJabberProto::IqResultStreamActivate );
			m_ThreadInfo->send( 
				XmlNodeIq( _T("set"), iqId, jbt->streamhostJID ) << XQUERY( _T(JABBER_FEAT_BYTESTREAMS))
					<< XATTR( _T("sid"), jbt->sid ) << XCHILD( _T("activate"), jbt->dstJID ));

			WaitForSingleObject( jbt->hProxyEvent, INFINITE );

			CloseHandle( jbt->hProxyEvent );
			jbt->hProxyEvent = NULL;

			ListRemove( LIST_FTIQID, listJid );

			if ( jbt->bStreamActivated) 
				jbt->state = (this->*jbt->pfnSend)( hConn, jbt->ft ) ? JBT_DONE : JBT_ERROR;
			else
				jbt->state = JBT_ERROR;
		}
		else jbt->state = JBT_SOCKSERR;
		break;
	}

	return num;
}
Ejemplo n.º 25
0
int CJabberProto::FileSendParse(JABBER_SOCKET s, filetransfer *ft, char* buffer, int datalen)
{
	char* p, *q, *t, *eob;
	char* str;
	int num;
	int currentFile;
	int fileId;
	int numRead;

	eob = buffer + datalen;
	p = buffer;
	num = 0;
	while (ft->state == FT_CONNECTING || ft->state == FT_INITIALIZING) {
		for (q = p; q + 1 < eob && (*q != '\r' || *(q + 1) != '\n'); q++);
		if (q + 1 >= eob)
			break;
		if ((str = (char*)mir_alloc(q - p + 1)) == NULL) {
			ft->state = FT_ERROR;
			break;
		}
		strncpy_s(str, q - p, p, _TRUNCATE);
		str[q - p] = '\0';
		debugLogA("FT Got: %s", str);
		if (ft->state == FT_CONNECTING) {
			// looking for "GET filename.ext HTTP/1.1"
			if (!strncmp(str, "GET ", 4)) {
				for (t = str + 4; *t != '\0' && *t != ' '; t++);
				*t = '\0';
				for (t = str + 4; *t != '\0' && *t == '/'; t++);
				ft->httpPath = mir_a2t(t);
				JabberHttpUrlDecode(ft->httpPath);
				ft->state = FT_INITIALIZING;
				debugLogA("Change to FT_INITIALIZING");
			}
		}
		else {	// FT_INITIALIZING
			if (str[0] == '\0') {
				struct _stati64 statbuf;

				mir_free(str);
				num += 2;

				currentFile = ft->std.currentFileNumber;
				TCHAR *t = _tcsrchr(ft->std.ptszFiles[currentFile], '\\');
				if (t != NULL)
					t++;
				else
					t = ft->std.ptszFiles[currentFile];

				if (ft->httpPath == NULL || mir_tstrcmp(ft->httpPath, t)) {
					if (ft->httpPath == NULL)
						debugLogA("Requested file name does not matched (httpPath == NULL)");
					else
						debugLog(_T("Requested file name does not matched ('%s' vs. '%s')"), ft->httpPath, t);
					ft->state = FT_ERROR;
					break;
				}
				debugLog(_T("Sending [%s]"), ft->std.ptszFiles[currentFile]);
				_tstati64(ft->std.ptszFiles[currentFile], &statbuf);	// file size in statbuf.st_size
				if ((fileId = _topen(ft->std.ptszFiles[currentFile], _O_BINARY | _O_RDONLY)) < 0) {
					debugLogA("File cannot be opened");
					ft->state = FT_ERROR;
					mir_free(ft->httpPath);
					ft->httpPath = NULL;
					break;
				}

				char fileBuffer[2048];
				int bytes = mir_snprintf(fileBuffer, _countof(fileBuffer), "HTTP/1.1 200 OK\r\nContent-Length: %I64u\r\n\r\n", statbuf.st_size);
				WsSend(s, fileBuffer, bytes, MSG_DUMPASTEXT);

				ft->std.flags |= PFTS_SENDING;
				ft->std.currentFileProgress = 0;
				debugLogA("Sending file data...");

				while ((numRead = _read(fileId, fileBuffer, 2048)) > 0) {
					if (Netlib_Send(s, fileBuffer, numRead, 0) != numRead) {
						ft->state = FT_ERROR;
						break;
					}
					ft->std.currentFileProgress += numRead;
					ft->std.totalProgress += numRead;
					ProtoBroadcastAck(ft->std.hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->std);
				}
				_close(fileId);
				if (ft->state != FT_ERROR)
					ft->state = FT_DONE;
				debugLogA("Finishing this file...");
				mir_free(ft->httpPath);
				ft->httpPath = NULL;
				break;
		}	}

		mir_free(str);
		q += 2;
		num += (q-p);
		p = q;
	}

	return num;
}
Ejemplo n.º 26
0
void __cdecl CJabberProto::ByteReceiveThread( JABBER_BYTE_TRANSFER *jbt )
{
	HXML iqNode, queryNode = NULL, n;
	const TCHAR *sid = NULL, *from = NULL, *to = NULL, *szId = NULL, *szHost, *szPort, *str;
	int i;
	WORD port;
	HANDLE hConn;
	char data[3];
	char* buffer;
	int datalen, bytesParsed, recvResult;
	BOOL validStreamhost = FALSE;

	if ( jbt == NULL ) return;

	jbt->state = JBT_INIT;

	if ( iqNode = jbt->iqNode ) {
		from = xmlGetAttrValue( iqNode, _T("from"));
		to = xmlGetAttrValue( iqNode, _T("to"));
		szId = xmlGetAttrValue( iqNode, _T("id"));

		queryNode = xmlGetChild( iqNode , "query" );
		if ( queryNode )
			sid = xmlGetAttrValue( queryNode, _T("sid"));
	}

	if ( szId && from && to && sid && ( n = xmlGetChild( queryNode , "streamhost" ))!=NULL ) {
		jbt->iqId = mir_tstrdup( szId );
		jbt->srcJID = mir_tstrdup( from );
		jbt->dstJID = mir_tstrdup( to );
		jbt->sid = mir_tstrdup( sid );

		if (( buffer=( char* )mir_alloc( JABBER_NETWORK_BUFFER_SIZE ))) {
			for ( i=1; ( n = xmlGetNthChild( queryNode, _T("streamhost"), i ))!=NULL; i++ ) {
				if (( szHost = xmlGetAttrValue( n, _T("host"))) != NULL &&
					( szPort = xmlGetAttrValue( n, _T("port"))) != NULL &&
					( str = xmlGetAttrValue( n, _T("jid"))) != NULL ) {

						port = ( WORD )_ttoi( szPort );
						if ( jbt->streamhostJID ) mir_free( jbt->streamhostJID );
						jbt->streamhostJID = mir_tstrdup( str );

						Log( "bytestream_recv connecting to " TCHAR_STR_PARAM ":%d", szHost, port );
						NETLIBOPENCONNECTION nloc = { 0 };
						nloc.cbSize = sizeof( nloc );
						nloc.szHost = mir_t2a(szHost);
						nloc.wPort = port;
						hConn = ( HANDLE ) JCallService( MS_NETLIB_OPENCONNECTION, ( WPARAM ) m_hNetlibUser, ( LPARAM )&nloc );
						mir_free((void*)nloc.szHost);

						if ( hConn == NULL ) {
							Log( "bytestream_recv_connection connection failed ( %d ), try next streamhost", WSAGetLastError());
							continue;
						}

						jbt->hConn = hConn;

						data[0] = 5;
						data[1] = 1;
						data[2] = 0;
						Netlib_Send( hConn, data, 3, 0 );

						jbt->state = JBT_INIT;
						datalen = 0;
						while ( jbt->state!=JBT_DONE && jbt->state!=JBT_ERROR && jbt->state!=JBT_SOCKSERR ) {
							recvResult = Netlib_Recv( hConn, buffer+datalen, JABBER_NETWORK_BUFFER_SIZE-datalen, 0 );
							if ( recvResult <= 0 ) break;
							datalen += recvResult;
							bytesParsed = ByteReceiveParse( hConn, jbt, buffer, datalen );
							if ( bytesParsed < datalen )
								memmove( buffer, buffer+bytesParsed, datalen-bytesParsed );
							datalen -= bytesParsed;
							if ( jbt->state == JBT_RECVING ) validStreamhost = TRUE;
						}
						Netlib_CloseHandle( hConn );
						Log( "bytestream_recv_connection closing connection" );
				}
				if ( jbt->state==JBT_ERROR || validStreamhost==TRUE )
					break;
				Log( "bytestream_recv_connection stream cannot be established, try next streamhost" );
			}
			mir_free( buffer );
		}
	}

	(this->*jbt->pfnFinal)(( jbt->state==JBT_DONE )?TRUE:FALSE, jbt->ft );
	jbt->ft = NULL;
	if ( !validStreamhost && szId && from ) {
		Log( "bytestream_recv_connection session not completed" );

		m_ThreadInfo->send( XmlNodeIq( _T("error"), szId, from )
			<< XCHILD( _T("error")) << XATTRI( _T("code"), 404 ) << XATTR( _T("type"), _T("cancel"))
			<< XCHILDNS( _T("item-not-found"), _T("urn:ietf:params:xml:ns:xmpp-stanzas")));
	}

	delete jbt;
	Log( "Thread ended: type=bytestream_recv" );
}
Ejemplo n.º 27
0
int CJabberProto::ByteReceiveParse( HANDLE hConn, JABBER_BYTE_TRANSFER *jbt, char* buffer, int datalen )
{
	int bytesReceived, num = datalen;

	switch ( jbt->state ) {
	case JBT_INIT:
		// received:
		// 00-00 ver ( 0x05 )
		// 01-01 selected method ( 0=no auth, 0xff=error )
		// send:
		// 00-00 ver ( 0x05 )
		// 01-01 cmd ( 1=connect )
		// 02-02 reserved ( 0 )
		// 03-03 address type ( 3 )
		// 04-44 dst.addr ( 41 bytes: 1-byte length, 40-byte SHA1 hash of [sid,srcJID,dstJID] )
		// 45-46 dst.port ( 0 )
		if ( datalen==2 && buffer[0]==5 && buffer[1]==0 ) {
			BYTE data[47];
			ZeroMemory( data, sizeof( data ));
			*(( DWORD* )data ) = 0x03000105;
			data[4] = 40;

			TCHAR text[JABBER_MAX_JID_LEN*2];
			TCHAR *szInitiatorJid = JabberPrepareJid(jbt->srcJID);
			TCHAR *szTargetJid = JabberPrepareJid(jbt->dstJID);
			mir_sntprintf( text, SIZEOF( text ), _T("%s%s%s"), jbt->sid, szInitiatorJid, szTargetJid );
			mir_free(szInitiatorJid);
			mir_free(szTargetJid);
			char* szAuthString = mir_utf8encodeT( text );
			Log( "Auth: '%s'", szAuthString );
			char* szHash = JabberSha1( szAuthString );
			strncpy(( char* )( data+5 ), szHash, 40 );
			mir_free( szHash );
			Netlib_Send( hConn, ( char* )data, 47, 0 );
			jbt->state = JBT_CONNECT;
			mir_free( szAuthString );
		}
		else jbt->state = JBT_SOCKSERR;
		break;

	case JBT_CONNECT:
		// received:
		// 00-00 ver ( 0x05 )
		// 01-01 reply ( 0=success,2=not allowed )
		// 02-02 reserved ( 0 )
		// 03-03 address type ( 1=IPv4 address,3=host address )
		// 04-mm bnd.addr server bound address ( 4-byte IP if IPv4, 1-byte length + n-byte host address string if host address )
		// nn-nn+1 bnd.port server bound port
		if ( datalen>=5 && buffer[0]==5 && buffer[1]==0 && ( buffer[3]==1 || buffer[3]==3 || buffer[3]==0 )) {
			if ( buffer[3]==1 && datalen>=10 )
				num = 10;
			else if ( buffer[3]==3 && datalen>=buffer[4]+7 )
				num = buffer[4] + 7;
			else if ( buffer[3]==0 && datalen>=6 )
				num = 6;
			else {
				jbt->state = JBT_SOCKSERR;
				break;
			}
			jbt->state = JBT_RECVING;

			m_ThreadInfo->send(
				XmlNodeIq( _T("result"), jbt->iqId, jbt->srcJID ) << XQUERY( _T(JABBER_FEAT_BYTESTREAMS))
					<< XCHILD( _T("streamhost-used")) << XATTR( _T("jid"), jbt->streamhostJID ));
		}
		else jbt->state = JBT_SOCKSERR;
		break;

	case JBT_RECVING:
		bytesReceived = (this->*jbt->pfnRecv)( hConn, jbt->ft, buffer, datalen );
		if ( bytesReceived < 0 )
			jbt->state = JBT_ERROR;
		else if ( bytesReceived == 0 )
			jbt->state = JBT_DONE;
		break;
	}

	return num;
}
Ejemplo n.º 28
0
int Parser()
{
    static NETLIBPACKETRECVER nlpr = {0};
    char *ptr;
    char tmp[256];
    int i;
    char *buf;
    static char ver[16];
    nlpr.cbSize = sizeof(nlpr);
    nlpr.dwTimeout = 5;
    if(!ghConnection)
    {
        mir_forkthread(&Start, 0);
    }
    if(ghConnection)
    {
        int recvResult;
        /*		do
        		{
        			recvResult = CallService(MS_NETLIB_GETMOREPACKETS,(WPARAM)ghPacketReciever, (LPARAM)&nlpr);
        			if(recvResult == SOCKET_ERROR)
        			{
        				ReStart();
        				return 1;
        			}
        		}
        		while(recvResult > 0);*/
        if(!Connected)
        {
            char tmp[128];
            char *tmp2 = mir_t2a(gbPassword);
            recvResult = CallService(MS_NETLIB_GETMOREPACKETS,(WPARAM)ghPacketReciever, (LPARAM)&nlpr);
            if(recvResult == SOCKET_ERROR)
            {
                mir_forkthread(&ReStart, 0);
//				ReStart();
                return 1;
            }
            if(strlen(tmp2) > 2)
            {
                strcpy(tmp, "password ");
                strcat(tmp, tmp2);
                strcat(tmp, "\n");
                Netlib_Send(ghConnection, tmp, (int)strlen(tmp), 0);
                recvResult = CallService(MS_NETLIB_GETMOREPACKETS,(WPARAM)ghPacketReciever, (LPARAM)&nlpr);
                if(recvResult == SOCKET_ERROR)
                {
                    mir_forkthread(&ReStart, 0);
                    return 1;
                }
            }
            mir_free(tmp2);
        }
        Netlib_Send(ghConnection, "status\n", (int)strlen("status\n"), 0);
        recvResult = CallService(MS_NETLIB_GETMOREPACKETS,(WPARAM)ghPacketReciever, (LPARAM)&nlpr);
        if(recvResult == SOCKET_ERROR)
        {
            mir_forkthread(&ReStart, 0);
            return 1;
        }
        Netlib_Send(ghConnection, "currentsong\n", (int)strlen("currentsong\n"), 0);
        recvResult = CallService(MS_NETLIB_GETMOREPACKETS,(WPARAM)ghPacketReciever, (LPARAM)&nlpr);
        if(recvResult == SOCKET_ERROR)
        {
            mir_forkthread(&ReStart, 0);
            return 1;
        }
        nlpr.bytesUsed = nlpr.bytesAvailable;
    }
    buf = (char*)nlpr.buffer;
    if(ptr = strstr(buf, "MPD"))
    {
        Connected = TRUE;
        ptr = &ptr[4];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        strcpy(ver, tmp);
        SongInfo.txtver = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.txtver = (TCHAR*)mir_utf8decodeW(ver);
    if(ptr = strstr(buf, "file:"))
    {
        ptr = &ptr[6];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.mfile = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.mfile = _T("");
    if(ptr = strstr(buf, "Time:"))
    {
        ptr = &ptr[6];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.total = atoi(tmp);
    }
    else if(!SongInfo.total)
        SongInfo.total = 0;
    if(ptr = strstr(buf, "time:"))
    {
        ptr = &ptr[6];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.time = atoi(tmp);
    }
    else if(!SongInfo.time)
        SongInfo.time = 0;
    if(ptr = strstr(buf, "Title:"))
    {
        ptr = &ptr[7];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.title = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.title = _T("Unknown track");
    if(ptr = strstr(buf, "Artist:"))
    {
        ptr = &ptr[8];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.artist = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.artist = _T("Unknown artist");
    if(ptr = strstr(buf, "Genre:"))
    {
        ptr = &ptr[7];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.genre = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.genre = _T("Unknown genre");
    if(ptr = strstr(buf, "Album:"))
    {
        ptr = &ptr[7];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.album = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.album = _T("Unknown album");
    if(ptr = strstr(buf, "Date:"))
    {
        ptr = &ptr[6];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.year = (TCHAR*)mir_utf8decodeW(tmp);
    }
    else
        SongInfo.year = _T("Unknown year");
    if(ptr = strstr(buf, "volume:"))
    {
        ptr = &ptr[8];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.volume = atoi(tmp);
    }
    else if(!SongInfo.volume)
        SongInfo.volume = 0;
    if(ptr = strstr(buf, "audio:"))
    {
        ptr = &ptr[7];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.khz = atoi(tmp);
    }
    else if(!SongInfo.khz)
        SongInfo.khz = 0;
    if(ptr = strstr(buf, "bitrate:"))
    {
        ptr = &ptr[9];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.kbps = atoi(tmp);
    }
    else if(!SongInfo.kbps)
        SongInfo.kbps = 0;

    if(ptr = strstr(buf, "Track:"))
    {
        ptr = &ptr[7];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        SongInfo.track = atoi(tmp);
    }
    else if(!SongInfo.track)
        SongInfo.track = 0;
    if(ptr = strstr(buf, "state:"))
    {
        ptr = &ptr[7];
        for(i = 0; ((ptr[i] != '\n') && (ptr[i] != '\0')); i++)
            tmp[i] = ptr[i];
        tmp[i] = '\0';
        if(strstr(tmp, "play"))
            gbState = WAT_PLS_PLAYING;
        if(strstr(tmp, "pause"))
            gbState = WAT_PLS_PAUSED;
        if(strstr(tmp, "stop"))
            gbState = WAT_PLS_STOPPED;
    }
    else if(!gbState)
        gbState = WAT_PLS_UNKNOWN;
    return 0;
}
Ejemplo n.º 29
0
// wParam is zero
// lParam is address of PINGADDRESS structure where ping result is placed (i.e. modifies 'responding' 
// and 'round_trip_time')
int PluginPing(WPARAM wParam,LPARAM lParam)
{
	PINGADDRESS *pa = (PINGADDRESS *)lParam;

	if(pa->port == -1) {
		if(use_raw_ping) {
			pa->round_trip_time = raw_ping(pa->pszName, options.ping_timeout * 1000);
			pa->responding = (pa->round_trip_time != -1);
		} else {
			// ICMP echo
			IP_ECHO_REPLY result;
			pa->responding = ICMP::get_instance()->ping(pa->pszName, result);
			if(pa->responding)
				pa->round_trip_time = (short)result.RoundTripTime;
			else
				pa->round_trip_time = -1;
		}
	} else if(hNetlibUser) {
		// TCP connect

		clock_t start_tcp = clock();
		
		//GetLocalTime(&systime);
		NETLIBOPENCONNECTION conn = {0};
		conn.cbSize = sizeof(NETLIBOPENCONNECTION);
		conn.szHost = pa->pszName;
		conn.wPort = pa->port;
		conn.flags = NLOCF_V2;
		conn.timeout = options.ping_timeout; 

		HANDLE s = (HANDLE)CallService(MS_NETLIB_OPENCONNECTION, (WPARAM)hNetlibUser, (LPARAM)&conn);

		clock_t end_tcp = clock();
		
		if(s) {
			LINGER l;
			char buf[1024];
			SOCKET socket = (SOCKET)CallService(MS_NETLIB_GETSOCKET, (WPARAM)s, (LPARAM)NLOCF_HTTP);
			if(socket != INVALID_SOCKET) {
				l.l_onoff = 1;
				l.l_linger = 0;
				setsockopt(socket, SOL_SOCKET, SO_LINGER, (char *)&l, sizeof(l));

				Netlib_Send(s, "OUT\r\n\r\n", 7, 0); //MSG_RAW);

				//Sleep(ICMP::get_instance()->get_timeout());
				Sleep(options.ping_timeout * 1000);
				unsigned long bytes_remaining;
				ioctlsocket(socket, FIONBIO, &bytes_remaining);

				if(bytes_remaining > 0) {
					int retval, rx = 0;
					while((retval = Netlib_Recv(s, buf, 1024, 0)) != SOCKET_ERROR && (retval > 0) && rx < 2048) {
						rx += retval; // recv at most 2kb before closing connection
					}
				}
				//closesocket(socket);

			}

			Netlib_CloseHandle(s);

			pa->responding = true;
			pa->round_trip_time = (int)(((end_tcp - start_tcp) / (double)CLOCKS_PER_SEC) * 1000);
		} else {
			pa->responding = false;
			pa->round_trip_time = -1;
		}

	}
	return 0;
}
Ejemplo n.º 30
0
int CAimProto::receiving_file(file_transfer *ft, HANDLE hServerPacketRecver, NETLIBPACKETRECVER &packetRecv)
{
	debugLogA("P2P: Entered file receiving thread.");
	bool failed = true;
	bool failed_conn = false;
	bool accepted_file = false;
	int fid = -1;

	oft2 *oft = NULL;

	ft->pfts.tszWorkingDir = mir_utf8decodeT(ft->file);

	//start listen for packets stuff
	for (;;) {
		int recvResult = packetRecv.bytesAvailable - packetRecv.bytesUsed;
		if (recvResult <= 0)
			recvResult = CallService(MS_NETLIB_GETMOREPACKETS, (WPARAM)hServerPacketRecver, (LPARAM)&packetRecv);
		if (recvResult == 0) {
			debugLogA("P2P: File transfer connection Error: 0");
			break;
		}
		if (recvResult == SOCKET_ERROR) {
			failed_conn = true;
			debugLogA("P2P: File transfer connection Error: -1");
			break;
		}
		if (recvResult > 0) {
			if (!accepted_file) {
				if (recvResult < 0x100) continue;

				oft2* recv_ft = (oft2*)&packetRecv.buffer[packetRecv.bytesUsed];
				unsigned short pkt_len = _htons(recv_ft->length);

				if (recvResult < pkt_len) continue;
				packetRecv.bytesUsed += pkt_len;

				unsigned short type = _htons(recv_ft->type);
				if (type == 0x0101) {
					debugLogA("P2P: Buddy Ready to begin transfer.");
					oft = (oft2*)mir_realloc(oft, pkt_len);
					memcpy(oft, recv_ft, pkt_len);
					memcpy(oft->icbm_cookie, ft->icbm_cookie, 8);

					int buflen = pkt_len - 0x100 + 64;
					char *buf = (char*)mir_calloc(buflen + 2);
					unsigned short enc;

					ft->pfts.currentFileSize = _htonl(recv_ft->size);
					ft->pfts.totalBytes = _htonl(recv_ft->total_size);
					ft->pfts.currentFileTime = _htonl(recv_ft->mod_time);
					memcpy(buf, recv_ft->filename, buflen);
					enc = _htons(recv_ft->encoding);

					TCHAR *name;
					if (enc == 2) {
						wchar_t* wbuf = (wchar_t*)buf;
						wcs_htons(wbuf);
						for (wchar_t *p = wbuf; *p; ++p) { if (*p == 1) *p = '\\'; }
						name = mir_u2t(wbuf);
					}
					else {
						for (char *p = buf; *p; ++p) { if (*p == 1) *p = '\\'; }
						name = mir_a2t(buf);
					}

					mir_free(buf);

					TCHAR fname[256];
					mir_sntprintf(fname, _T("%s%s"), ft->pfts.tszWorkingDir, name);
					mir_free(name);
					mir_free(ft->pfts.tszCurrentFile);
					ft->pfts.tszCurrentFile = mir_tstrdup(fname);

					ResetEvent(ft->hResumeEvent);
					if (ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_FILERESUME, ft, (LPARAM)&ft->pfts))
						WaitForSingleObject(ft->hResumeEvent, INFINITE);

					if (ft->pfts.tszCurrentFile) {
						TCHAR* dir = get_dir(ft->pfts.tszCurrentFile);
						CreateDirectoryTreeT(dir);
						mir_free(dir);

						oft->type = _htons(ft->pfts.currentFileProgress ? 0x0205 : 0x0202);

						const int flag = ft->pfts.currentFileProgress ? 0 : _O_TRUNC;
						fid = _topen(ft->pfts.tszCurrentFile, _O_CREAT | _O_WRONLY | _O_BINARY | flag, _S_IREAD | _S_IWRITE);

						if (fid < 0) {
							report_file_error(fname);
							break;
						}

						accepted_file = ft->pfts.currentFileProgress == 0;

						if (ft->pfts.currentFileProgress) {
							bool the_same;
							oft->recv_bytes = _htonl(ft->pfts.currentFileProgress);
							oft->recv_checksum = _htonl(aim_oft_checksum_file(ft->pfts.tszCurrentFile));
							the_same = oft->size == oft->recv_bytes && oft->checksum == oft->recv_checksum;
							if (the_same) {
								ft->pfts.totalProgress += ft->pfts.currentFileProgress;
								oft->type = _htons(0x0204);
								_close(fid);

								ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
								++ft->pfts.currentFileNumber;
								ft->pfts.currentFileProgress = 0;
							}
						}
					}
					else {
						oft->type = _htons(0x0204);

						ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
						++ft->pfts.currentFileNumber;
						ft->pfts.currentFileProgress = 0;
					}

					if (Netlib_Send(ft->hConn, (char*)oft, pkt_len, 0) == SOCKET_ERROR)
						break;

					if (ft->pfts.currentFileNumber >= ft->pfts.totalFiles && _htons(oft->type) == 0x0204) {
						failed = false;
						break;
					}
				}
				else if (type == 0x0106) {
					oft = (oft2*)mir_realloc(oft, pkt_len);
					memcpy(oft, recv_ft, pkt_len);

					ft->pfts.currentFileProgress = _htonl(oft->recv_bytes);
					ft->pfts.totalProgress += ft->pfts.currentFileProgress;

					_lseeki64(fid, ft->pfts.currentFileProgress, SEEK_SET);
					accepted_file = true;

					oft->type = _htons(0x0207);
					if (Netlib_Send(ft->hConn, (char*)oft, pkt_len, 0) == SOCKET_ERROR)
						break;
				}
				else break;
			}
			else {
				packetRecv.bytesUsed = packetRecv.bytesAvailable;
				_write(fid, packetRecv.buffer, packetRecv.bytesAvailable);
				ft->pfts.currentFileProgress += packetRecv.bytesAvailable;
				ft->pfts.totalProgress += packetRecv.bytesAvailable;
				ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_DATA, ft, (LPARAM)&ft->pfts);
				if (ft->pfts.currentFileSize == ft->pfts.currentFileProgress) {
					oft->type = _htons(0x0204);
					oft->recv_bytes = _htonl(ft->pfts.currentFileProgress);
					oft->recv_checksum = _htonl(aim_oft_checksum_file(ft->pfts.tszCurrentFile));

					debugLogA("P2P: We got the file successfully");
					Netlib_Send(ft->hConn, (char*)oft, _htons(oft->length), 0);
					if (_htons(oft->num_files_left) == 1) {
						failed = false;
						break;
					}
					else {
						accepted_file = false;
						_close(fid);

						ProtoBroadcastAck(ft->hContact, ACKTYPE_FILE, ACKRESULT_NEXTFILE, ft, 0);
						++ft->pfts.currentFileNumber;
						ft->pfts.currentFileProgress = 0;
					}
				}
			}
		}
	}

	if (accepted_file) _close(fid);
	mir_free(oft);

	ft->success = !failed;
	return failed ? (failed_conn ? 1 : 2) : 0;
}