Пример #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;
}
Пример #2
0
void tcp_send_fin(struct tcp_sock *tsk)
{
	struct tcp *otcp;
	struct pkbuf *opkb;

	opkb = alloc_pkb(ETH_HRD_SZ + IP_HRD_SZ + TCP_HRD_SZ);
	/* fill tcp head */
	otcp = (struct tcp *)pkb2ip(opkb)->ip_data;
	otcp->src = tsk->sk.sk_sport;
	otcp->dst = tsk->sk.sk_dport;
	otcp->doff = TCP_HRD_DOFF;
	otcp->seq = _htonl(tsk->snd_nxt);
	otcp->window = _htons(tsk->rcv_wnd);
	otcp->fin = 1;
	/*
	 * Should we send an ACK?
	 * Yes, tcp stack will drop packet if it has no ACK bit
	 * according to RFC 793 #SEGMENT RECEIVE
	 */
	otcp->ackn = _htonl(tsk->rcv_nxt);
	otcp->ack = 1;
	tcpdbg("send FIN(%u)/ACK(%u) [WIN %d] to "IPFMT":%d",
			_ntohl(otcp->seq), _ntohl(otcp->ackn),
			_ntohs(otcp->window), ipfmt(tsk->sk.sk_daddr),
			_ntohs(otcp->dst));
	tcp_send_out(tsk, opkb, NULL);
}
Пример #3
0
void tcp_send_synack(struct tcp_sock *tsk, struct tcp_segment *seg)
{
	/*
	 * LISTEN :
	 * SYN-SENT:
	 *         SEG: SYN, no ACK, no RST
	 *         <SEQ=ISS><ACK=RCV.NXT><CTL=SYN,ACK>
	 *         (ISS == SND.NXT)
	 */
	struct tcp *otcp, *tcphdr = seg->tcphdr;
	struct pkbuf *opkb;

	if (tcphdr->rst)
		return;
	opkb = alloc_pkb(ETH_HRD_SZ + IP_HRD_SZ + TCP_HRD_SZ);
	/* fill tcp head */
	otcp = (struct tcp *)pkb2ip(opkb)->ip_data;
	otcp->src = tcphdr->dst;
	otcp->dst = tcphdr->src;
	otcp->doff = TCP_HRD_DOFF;
	otcp->seq = _htonl(tsk->iss);
	otcp->ackn = _htonl(tsk->rcv_nxt);
	otcp->syn = 1;
	otcp->ack = 1;
	otcp->window = _htons(tsk->rcv_wnd);
	tcpdbg("send SYN(%u)/ACK(%u) [WIN %d] to "IPFMT":%d",
			_ntohl(otcp->seq), _ntohs(otcp->window),
			_ntohl(otcp->ackn), ipfmt(seg->iphdr->ip_dst),
			_ntohs(otcp->dst));
	tcp_send_out(tsk, opkb, seg);
}
Пример #4
0
extern "C" __declspec(dllexport) const PLUGININFOEX* MirandaPluginInfoEx(DWORD mirandaVersion)
{
	if (mirandaVersion < __VERSION_DWORD) 
	{
		MessageBox(NULL, 
			_T("The AIM protocol plugin cannot be loaded. It requires Miranda IM ") 
			_T(__VERSION_STRING) _T(" or later."),
			_T("Miranda"), MB_OK | MB_ICONWARNING | MB_SETFOREGROUND | MB_TOPMOST);
		return NULL;
	}

	*(unsigned long*)(&AIM_CAP_MIRANDA[8]) = _htonl(mirandaVersion);
	*(unsigned long*)(&AIM_CAP_MIRANDA[12]) = _htonl(__VERSION_DWORD);
	return &pluginInfo;
}
Пример #5
0
//Function to write tlv header into a msg according to tlv info, the input buffer size should be at least MAX_TLV_HEADER_SIZE
static tlv_status_t write_tlv_header(uint8_t *msg, const tlv_info_t *info)
{
    uint8_t type = info->type;
    if(info->size>UINT16_MAX ||info->header_size == LARGE_TLV_HEADER_SIZE){//6 bytes header
        uint32_t size = info->size; //4 bytes in size field
        type |= FOUR_BYTES_SIZE_TYPE;
        msg[0] = type;
        msg[1] = info->version;
        size = _htonl(size);
        if(memcpy_s(&msg[2], sizeof(uint32_t), &size, sizeof(size))!=0){
            AESM_DBG_ERROR("memcpy failed");
            return TLV_UNKNOWN_ERROR;
        }
    }else{//4 bytes header
        uint16_t size = (uint16_t)info->size;//2 bytes in size field
        msg[0] = type;
        msg[1] = info->version;
        size = _htons(size); 
        if(memcpy_s(&msg[2], sizeof(uint16_t), &size, sizeof(size))!=0){
            AESM_DBG_ERROR("memcpy failed");
            return TLV_UNKNOWN_ERROR;
        }
    }
    return TLV_SUCCESS;
}
Пример #6
0
static ae_error_t prov_es_gen_header(provision_request_header_t *es_header,
                                     const uint8_t *xid,
                                     uint32_t msg_buffer_size)
{
    uint32_t total_size = 0;

    total_size = ES_SELECTOR_TLV_SIZE();
    //initialize ES Msg1 Header
    es_header->protocol = ENDPOINT_SELECTION;
    es_header->type = TYPE_ES_MSG1;
    es_header->version = TLV_VERSION_1;
    if(0!=memcpy_s(es_header->xid, XID_SIZE, xid, XID_SIZE)){
        AESM_DBG_FATAL("memcpy error");
        return PVE_UNEXPECTED_ERROR;
    }
    uint32_t size_in;
    size_in = _htonl(total_size);//big endian size required in msg header
    if(0!=memcpy_s(&es_header->size,sizeof(es_header->size), &size_in, sizeof(size_in))){
        AESM_DBG_FATAL("memcpy error");
        return PVE_UNEXPECTED_ERROR;
    }
    if(total_size +sizeof(*es_header) >msg_buffer_size){//the input msg body buffer size is not large enough
        AESM_DBG_ERROR("input msg buffer is too small");
        return PVE_INSUFFICIENT_MEMORY_ERROR;
    }
    return AE_SUCCESS;
}
Пример #7
0
ae_error_t CertificateProvisioningProtocol::msg3_create_header(const upse::Buffer& transactionID, uint32_t nonceSize, uint32_t quoteSize, uint32_t epidSigSize, uint32_t csrSize, provision_request_header_t& header)
{
    ae_error_t status = AESM_PSE_PR_INTERNAL_ERROR;

    do
    {
        uint32_t seq2_0_tlv_block_cipher_text_size = BLOCK_CIPHER_TEXT_TLV_SIZE(quoteSize + epidSigSize + csrSize);
        uint32_t seq3_0_tlv_nonce_size = nonceSize;
        uint32_t seq4_0_tlv_mac_size = MAC_TLV_SIZE(MAC_SIZE);

        header.protocol = PSE_PROVISIONING;
        header.version = TLV_VERSION_1;
        header.type = static_cast<uint8_t>(TYPE_PSE_MSG3);

        if (XID_SIZE != transactionID.getSize())
            break;

        if (memcpy_s(header.xid, sizeof(header.xid), transactionID.getData(), transactionID.getSize()) != 0)
            break;

        uint32_t totalSize = seq2_0_tlv_block_cipher_text_size + seq3_0_tlv_nonce_size + seq4_0_tlv_mac_size;

        uint32_t serializedSize = _htonl(totalSize);
        se_static_assert(sizeof(serializedSize) == sizeof(header.size));

        if (memcpy_s(header.size, sizeof(header.size), &serializedSize, sizeof(serializedSize)) != 0)
            break;

        status = AE_SUCCESS;
    } while (0);

    return status;
}
Пример #8
0
/*
 * Reset algorithm is not stated directly in RFC 793,
 * but we can conclude it according to all reset generation.
 * NOTE: maybe @tsk is NULL
 */
void tcp_send_reset(struct tcp_sock *tsk, struct tcp_segment *seg)
{
	struct tcp *otcp, *tcphdr = seg->tcphdr;
	struct pkbuf *opkb;

	if (tcphdr->rst)
		return;
	opkb = alloc_pkb(ETH_HRD_SZ + IP_HRD_SZ + TCP_HRD_SZ);
	/* fill tcp head */
	otcp = (struct tcp *)pkb2ip(opkb)->ip_data;
	otcp->src = tcphdr->dst;
	otcp->dst = tcphdr->src;
	if (tcphdr->ack) {
		/*
		 * Should we set ack?
		 * -Yes for xinu, it always set ack to seq+len
		 * +No for Linux
		 * +No for tapip
		 */
		otcp->seq = tcphdr->ackn;
	} else {
		otcp->ackn = _htonl(seg->seq + seg->len);
		otcp->ack = 1;
	}
	otcp->doff = TCP_HRD_DOFF;
	otcp->rst = 1;
	tcpdbg("send RESET from "IPFMT":%d to "IPFMT":%d",
			ipfmt(seg->iphdr->ip_dst), _ntohs(otcp->src),
			ipfmt(seg->iphdr->ip_src), _ntohs(otcp->dst));
	tcp_send_out(NULL, opkb, seg);
}
Пример #9
0
/* We're all done sorting.  Write out the logfile.
 * Format:
 *   Magic number 0x43 0x9f 0x22 0x53
 *   Number of elements
 *   Array of absolute offsets from the start of the file
 *   Magic number 0xa4 0xc3 0x2d 0xe5
 *   Array of events
 */
static int st_write(struct state *st) {
    int jump_offset;
    struct evt_file_header file_header;
    uint32_t offset;

    qDebug() << "Writing out...";
	st->out_fdh->seek(0);
    offset = 0;

    // Write out the file header
    memset(&file_header, 0, sizeof(file_header));
    memcpy(file_header.magic1, EVENT_HDR_1, strlen(EVENT_HDR_1));
    file_header.version = _ntohl(1);
    file_header.count = _htonl(hdr_count);
	offset += st->out_fdh->write((char *)&file_header, sizeof(file_header));

    // Advance the offset past the jump table
    offset += hdr_count*sizeof(offset);

    // Read in the jump table entries
	st->fdh->seek(0);
    for (jump_offset=0; jump_offset<hdr_count; jump_offset++) {
        union evt evt;
        uint32_t offset_swab = _htonl(offset);
		st->out_fdh->write((char *)&offset_swab, sizeof(offset_swab));

        st->fdh->seek(hdrs[jump_offset].pos);
        memset(&evt, 0, sizeof(evt));
        event_get_next(st, &evt);
        if (evt.header.size > 32768)
            return 1;
        offset += evt.header.size;
    }

	offset += st->out_fdh->write(EVENT_HDR_2, 4);

    // Now copy over the exact events
    for (jump_offset=0; jump_offset<hdr_count; jump_offset++) {
        union evt evt;
        st->fdh->seek(hdrs[jump_offset].pos);
        event_get_next(st, &evt);
        event_write(st, &evt);
    }

    sstate_set(st, ST_DONE);
    return 1;
}
/* Start Adafruit_WINC1500UDP socket, listening at local port PORT */
uint8_t Adafruit_WINC1500UDP::begin(uint16_t port, uint32_t multicastAddr)
{
	struct sockaddr_in addr;
	uint32 u32EnableCallbacks = 0;

	_flag = 0;
	_head = 0;
	_tail = 0;
	_rcvSize = 0;
	_rcvPort = 0;
	_rcvIP = 0;
	_sndSize = 0;

	// Initialize socket address structure.
	addr.sin_family = AF_INET;
	addr.sin_port = _htons(port);
	addr.sin_addr.s_addr = 0;

	// Open TCP server socket.
	if ((_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		return 0;
	}

	// Add socket buffer handler:
	socketBufferRegister(_socket, &_flag, &_head, &_tail, (uint8 *)_recvBuffer);
	setsockopt(_socket, SOL_SOCKET, SO_SET_UDP_SEND_CALLBACK, &u32EnableCallbacks, 0);

	// Set multicast address option if a multicast address was specified.
	if (multicastAddr != 0) {
		multicastAddr = _htonl(multicastAddr);
		if (setsockopt(_socket, SOL_SOCKET, IP_ADD_MEMBERSHIP, &multicastAddr, sizeof(multicastAddr)) < 0) {
			// Failed to set the multicast address option.
			close(_socket);
			_socket = -1;
			return 0;
		}
	}

	// Bind socket:
	if (bind(_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) < 0) {
		close(_socket);
		_socket = -1;
		return 0;
	}

	// Wait for connection or timeout:
	unsigned long start = millis();
	while (!READY && millis() - start < 2000) {
		m2m_wifi_handle_events(NULL);
	}
	if (!READY) {
		close(_socket);
		_socket = -1;
		return 0;
	}
	_flag &= ~SOCKET_BUFFER_FLAG_BIND;

	return 1;
}
Пример #11
0
QByteArray fromNumberToBuffer (quint32 number)
{
    QByteArray temp;
    QDataStream  ds (temp);
    ds << _htonl(number);

    return (temp);
}
Пример #12
0
static inline void set_tcp_ip_src(struct __sk_buff *skb, __u32 new_ip)
{
	__u32 old_ip = _htonl(load_word(skb, IP_SRC_OFF));

	bpf_l4_csum_replace(skb, TCP_CSUM_OFF, old_ip, new_ip, IS_PSEUDO | sizeof(new_ip));
	bpf_l3_csum_replace(skb, IP_CSUM_OFF, old_ip, new_ip, sizeof(new_ip));
	bpf_skb_store_bytes(skb, IP_SRC_OFF, &new_ip, sizeof(new_ip), 0);
}
Пример #13
0
static void tcp_init_text(struct tcp_sock *tsk, struct pkbuf *pkb,
		void *buf, int size)
{
	struct tcp *tcphdr = pkb2tcp(pkb);
	tcphdr->src = tsk->sk.sk_sport;
	tcphdr->dst = tsk->sk.sk_dport;
	tcphdr->doff = TCP_HRD_DOFF;
	tcphdr->seq = _htonl(tsk->snd_nxt);
	tcphdr->ackn = _htonl(tsk->rcv_nxt);
	tcphdr->ack = 1;
	tcphdr->window = _htons(tsk->rcv_wnd);
	memcpy(tcphdr->data, buf, size);
	tsk->snd_nxt += size;
	tsk->snd_wnd -= size;
	tcpsdbg("send TEXT(%u:%d) [WIN %d] to "IPFMT":%d",
			_ntohl(tcphdr->seq), size, _ntohs(tcphdr->window),
			ipfmt(tsk->sk.sk_daddr), _ntohs(tcphdr->dst));
}
Пример #14
0
/*
 * Need enough RX buffer space to receive a complete name service packet when
 * used in UDP mode.  NS expects MTU of 1500 subtracts UDP, IP and Ethernet
 * Type II overhead.  1500 - 8 -20 - 18 = 1454.  txData buffer size needs to
 * be big enough to hold a NS WHO-HAS for one name (4 + 2 + 256 = 262) in UDP
 * mode.  TCP buffer size dominates in that case.
 */
AJ_Status AJ_Net_Connect(AJ_BusAttachment* bus, const AJ_Service* service)
{
    int ret;
    //  IPAddress ip(service->ipv4);

    if (!(service->addrTypes & AJ_ADDR_TCP4)) 
	{
  //      AJ_ErrPrintf(("AJ_Net_Connect(): only IPV4 TCP supported\n", ret));
        return AJ_ERR_CONNECT;
    }
 //   printf("AJ_Net_Connect(netSock=0x%p, addrType=%d.)\n", netSock, addrType);
   
    printf("AJ_Net_Connect()\n");
    // ret = g_client.connect(ip, service->ipv4port);
	//   	addr.sin_port = _htons(48256);
	//   	addr.sin_addr.s_addr = _htonl(0xc0a8141d);
   	addr.sin_port = _htons(service->ipv4port);
    addr.sin_addr.s_addr = _htonl(service->ipv4);
	printf("AJ_Net_Connect(): ipv4= %x, port = %d\n",addr.sin_addr.s_addr,	addr.sin_port);
    tcp_client_socket = socket(AF_INET, SOCK_STREAM, 0);
	ret=connect(tcp_client_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in));
	 printf("AJ_Net_Connect(): connect\n");
	//ждем подключения
	while(tcp_ready_to_send==0)
	{
		m2m_wifi_handle_events(NULL);
	}
	 printf("AJ_Net_Connect(): connect OK\n");
    if (ret == -1) 
	{
        //AJ_ErrPrintf(("AJ_Net_Connect(): connect() failed: %d: status=AJ_ERR_CONNECT\n", ret));
        return AJ_ERR_CONNECT;
    } 
	else
	{
       //AJ_IOBufInit(&netSock->rx, rxData, sizeof(rxData), AJ_IO_BUF_RX, (void*)&g_clientUDP);
       bus->sock.rx.bufStart = AJ_in_data_tcp;
       bus->sock.rx.bufSize = sizeof(AJ_in_data_tcp);
       bus->sock.rx.readPtr = AJ_in_data_tcp;
       bus->sock.rx.writePtr = AJ_in_data_tcp;
       bus->sock.rx.direction = AJ_IO_BUF_RX;
       bus->sock.rx.recv = AJ_Net_Recv;
       //   AJ_IOBufInit(&netSock->tx, txData, sizeof(txData), AJ_IO_BUF_TX, (void*)&g_clientUDP);
       bus->sock.tx.bufStart = tcp_data_tx;
       bus->sock.tx.bufSize = sizeof(tcp_data_tx);
       bus->sock.tx.readPtr = tcp_data_tx;
       bus->sock.tx.writePtr = tcp_data_tx;
       bus->sock.tx.direction = AJ_IO_BUF_TX;
       bus->sock.tx.send = AJ_Net_Send;
        printf("AJ_Net_Connect(): connect() success: status=AJ_OK\n");
        return AJ_OK;
    }
    printf("AJ_Net_Connect(): connect() failed: %d: status=AJ_ERR_CONNECT\n", ret);
    return AJ_ERR_CONNECT;
}
Пример #15
0
static int _get_packet(unsigned char *packet, int *len)
{
    uint32_t data[12];
    struct timeval_t now = {0, 0};

    if (*len < 48) {
        log_err("packet buf too short!\n");
        return -1;
    }

    memset(packet, 0, *len);

    data[0] = _htonl((LI << 30) | (VN << 27) | (MODE << 24) |
                     (STRATUM << 16) | (POLL << 8) | (PREC & 0xff));
    data[1] = _htonl(1 << 16);  /* Root Delay (seconds) */
    data[2] = _htonl(1 << 16);  /* Root Dispersion (seconds) */
    data[10] = _htonl(now.tv_sec + JAN_1970); /* Transmit Timestamp coarse */
    data[11] = _htonl(NTPFRAC(now.tv_usec));  /* Transmit Timestamp fine */

    memcpy(packet, data, 48);
    *len = 48;

    return 0;
}
Пример #16
0
/*
 * Acknowledgment algorithm is not stated directly in RFC 793,
 * but we can conclude it from all acknowledgment situation.
 */
void tcp_send_ack(struct tcp_sock *tsk, struct tcp_segment *seg)
{
	/*
	 * SYN-SENT :
	 *         SEG: SYN, acceptable ACK, no RST   (SND.NXT = SEG.SEQ+1)
	 *         <SEQ=SND.NXT><ACK=RCV.NXT><CTL=ACK>
	 * SYN-RECEIVED / ESTABLISHED  / FIN-WAIT-1   / FIN-WAIT-2   /
	 * CLOSE-WAIT   / CLOSING      / LAST-ACK     / TIME-WAIT    :
	 *         SEG: no RST, ??ACK, ??SYN        (segment is not acceptable)
	 *         <SEQ=SND.NXT><ACK=RCV.NXT><CTL=ACK>
	 * ESTABLISHED  / FIN-WAIT-1  / FIN-WAIT-2  / process the segment text:
	 *         SEG: ACK, no RST
	 *         <SEQ=SND.NXT><ACK=RCV.NXT><CTL=ACK>
	 *         (This acknowledgment should be piggybacked on a segment being
	 *          transmitted if possible without incurring undue delay.)
	 */
	struct tcp *otcp, *tcphdr = seg->tcphdr;
	struct pkbuf *opkb;

	if (tcphdr->rst)
		return;
	opkb = alloc_pkb(ETH_HRD_SZ + IP_HRD_SZ + TCP_HRD_SZ);
	/* fill tcp head */
	otcp = (struct tcp *)pkb2ip(opkb)->ip_data;
	otcp->src = tcphdr->dst;
	otcp->dst = tcphdr->src;
	otcp->doff = TCP_HRD_DOFF;
	otcp->seq = _htonl(tsk->snd_nxt);
	otcp->ackn = _htonl(tsk->rcv_nxt);
	otcp->ack = 1;
	otcp->window = _htons(tsk->rcv_wnd);
	tcpdbg("send ACK(%u) [WIN %d] to "IPFMT":%d",
			_ntohl(otcp->ackn), _ntohs(otcp->window),
			ipfmt(seg->iphdr->ip_src), _ntohs(otcp->dst));
	tcp_send_out(tsk, opkb, seg);
}
void WiFiMDNSResponder::replyToRequest()
{
  int nameLength = name.length();
  int domainLength = sizeof(domain);
  uint32_t ipAddress = WiFi.localIP();
  uint32_t ttl = _htonl(ttlSeconds);

  int responseSize = sizeof(responseHeader) + 1 + nameLength + 1 + domainLength + 1 + sizeof(aRecord) + sizeof(nsecRecord);
  uint8_t response[responseSize];
  uint8_t* r = response;

  // copy header
  memcpy_P(r, responseHeader, sizeof(responseHeader));
  r += sizeof(responseHeader);
  
  // copy name
  *r = nameLength;
  memcpy(r + 1, name.c_str(), nameLength);
  r += (1 + nameLength);

  // copy domain
  *r = domainLength;
  memcpy_P(r + 1, domain, domainLength);
  r += (1 + domainLength);

  // terminator
  *r = 0x00;
  r++;

  // copy A record
  memcpy_P(r, aRecord, sizeof(aRecord));
  memcpy(r + TTL_OFFSET, &ttl, sizeof(ttl));            // replace TTL value
  memcpy(r + IP_OFFSET, &ipAddress, sizeof(ipAddress)); // replace IP address value
  r += sizeof(aRecord);

  // copy NSEC record
  memcpy_P(r, nsecRecord, sizeof(nsecRecord));
  r += sizeof(nsecRecord);

  udpSocket.beginPacket(IPAddress(224, 0, 0, 251), 5353);
  udpSocket.write(response, responseSize);
  udpSocket.endPacket();
}
Пример #18
0
//Function to initialize request header for ProvMsg1
//msg1_header: request header for ProvMsg1 to fill in
//use_flags: whether the flag tlv is included
//xid: transaction ID
//msg1_buffer_size: buffer size for ProvMsg1, in bytes
static ae_error_t prov_msg1_gen_header(provision_request_header_t *msg1_header,
                                       bool use_flags,
                                       const uint8_t *xid,
                                       uint32_t msg1_buffer_size)
{
    uint32_t total_size = 0;
    //platform info tlv size
    uint32_t field1_data_size = PLATFORM_INFO_TLV_SIZE();
    field1_data_size += CIPHER_TEXT_TLV_SIZE(RSA_3072_KEY_BYTES);
    //add flag tlv if needed
    if(use_flags){
        field1_data_size += FLAGS_TLV_SIZE();
    }

    if(sizeof(*msg1_header)>msg1_buffer_size){
        AESM_DBG_ERROR("Too small ProvMsg1 buffer size");
        return PVE_INSUFFICIENT_MEMORY_ERROR;
    }
    total_size = CIPHER_TEXT_TLV_SIZE(RSA_3072_KEY_BYTES) + BLOCK_CIPHER_TEXT_TLV_SIZE(field1_data_size) +MAC_TLV_SIZE(MAC_SIZE);
    //initialize Msg1 Header
    msg1_header->protocol = SE_EPID_PROVISIONING;
    msg1_header->type = TYPE_PROV_MSG1;
    msg1_header->version = TLV_VERSION_2;
    if(0!=memcpy_s(msg1_header->xid, sizeof(msg1_header->xid), xid, XID_SIZE)){
        AESM_DBG_FATAL("fail in memcpy_s");
        return PVE_UNEXPECTED_ERROR;
    }
    uint32_t size_in;
    //use as a tmp size, big endian required in msg header
    size_in = _htonl(total_size);
    //copy big endian msg body size into header
    if(0!=memcpy_s(&msg1_header->size, sizeof(msg1_header->size),&size_in, sizeof(size_in))){
        AESM_DBG_FATAL("fail in memcpy_s");
        return PVE_UNEXPECTED_ERROR;
    }
    if(total_size +sizeof(*msg1_header) >msg1_buffer_size){
        //the input msg body size is not large enough
        AESM_DBG_ERROR("Too small ProvMsg1 buffer size");
        return PVE_INSUFFICIENT_MEMORY_ERROR;
    }
    return AE_SUCCESS;
}
Пример #19
0
void tcp_send_syn(struct tcp_sock *tsk, struct tcp_segment *seg)
{
	/*
	 * SYN-SENT:
	 */
	struct tcp *otcp;
	struct pkbuf *opkb;

	opkb = alloc_pkb(ETH_HRD_SZ + IP_HRD_SZ + TCP_HRD_SZ);
	/* fill tcp head */
	otcp = (struct tcp *)pkb2ip(opkb)->ip_data;
	otcp->src = tsk->sk.sk_sport;
	otcp->dst = tsk->sk.sk_dport;
	otcp->doff = TCP_HRD_DOFF;
	otcp->seq = _htonl(tsk->iss);
	otcp->syn = 1;
	otcp->window = _htons(tsk->rcv_wnd);
	tcpdbg("send SYN(%u) [WIN %d] to "IPFMT":%d",
			_ntohl(otcp->seq), _ntohs(otcp->window),
			ipfmt(tsk->sk.sk_daddr), _ntohs(otcp->dst));
	tcp_send_out(tsk, opkb, seg);
}
Пример #20
0
//
// get_sgx_gid
//
// get sgx gid from epid blob, specifically from stored group cert in epid blob
//
// inputs
//
// pgid: pointer to gid
//
// outputs
//
// *pgid: gid
// status
//
ae_error_t EPIDBlob::get_sgx_gid(uint32_t* pgid) 
{
    ae_error_t aesm_result = AE_SUCCESS;
    epid_blob_with_cur_psvn_t epid_blob;
    sgx_sealed_data_t *sealed_epid = reinterpret_cast<sgx_sealed_data_t *>(epid_blob.trusted_epid_blob);

    if (NULL != pgid) {
        //
        // get the epid blob
        //
        aesm_result = this->read(epid_blob);
        if (AE_SUCCESS == aesm_result) {
            //
            // get the gid
            //
            uint32_t plain_text_offset = sealed_epid->plain_text_offset;
            se_plaintext_epid_data_t* plain_text = reinterpret_cast<se_plaintext_epid_data_t *>(epid_blob.trusted_epid_blob + sizeof(sgx_sealed_data_t) + plain_text_offset);
            if(memcpy_s(pgid, sizeof(*pgid), &plain_text->epid_group_cert.gid, sizeof(plain_text->epid_group_cert.gid)))	//read gid from EPID Data blob
            {
                AESM_DBG_ERROR("memcpy_s failed");
                aesm_result = AE_FAILURE;
            }
            //
            // return little-endian
            //
            *pgid = _htonl(*pgid);
            AESM_DBG_TRACE(": get gid %d from epid blob", *pgid);
        }
    }
    else {
        aesm_result = AE_INVALID_PARAMETER;
    }

    return aesm_result;

}
Пример #21
0
void __cdecl CAimProto::aim_proxy_helper(void* param)
{
	file_transfer *ft = (file_transfer*)param;

	if (ft->requester) 
	{
		if (proxy_initialize_send(ft->hConn, username, ft->icbm_cookie))
			return;//error
	}
	else
	{
		if (proxy_initialize_recv(ft->hConn, username, ft->icbm_cookie, ft->port)) 
			return;//error
	}

	//start listen for packets stuff
	NETLIBPACKETRECVER packetRecv = {0};
	packetRecv.cbSize = sizeof(packetRecv);
	packetRecv.dwTimeout = INFINITE;

	HANDLE hServerPacketRecver = (HANDLE) CallService(MS_NETLIB_CREATEPACKETRECVER, (WPARAM)ft->hConn, 2048 * 4);
	for (;;)
	{
		int recvResult = CallService(MS_NETLIB_GETMOREPACKETS, (WPARAM)hServerPacketRecver, (LPARAM)&packetRecv);
		if (recvResult == 0) 
		{
			sendBroadcast(ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
			break;
		}
		if (recvResult == SOCKET_ERROR) 
		{
			sendBroadcast(ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
			break;
		}
		if (recvResult > 0) 
		{
			unsigned short length = _htons(*(unsigned short*)&packetRecv.buffer[0]);
			packetRecv.bytesUsed = length + 2;
			unsigned short type = _htons(*(unsigned short*)&packetRecv.buffer[4]);
			if (type == 0x0001)
			{
				unsigned short error = _htons(*(unsigned short*)&packetRecv.buffer[12]);
				switch (error)
				{
				case 0x000D:
					ShowPopup("Proxy Server File Transfer Error: Bad Request.", ERROR_POPUP);
					break;

				case 0x0010:
					ShowPopup("Proxy Server File Transfer Error: Initial Request Timed Out.", ERROR_POPUP);
					break;

				case 0x001A:
					ShowPopup("Proxy Server File Transfer Error: Accept Period Timed Out.", ERROR_POPUP);
					break;

				case 0x000e:
					ShowPopup("Proxy Server File Transfer Error: Incorrect command syntax.", ERROR_POPUP);
					break;

				case 0x0016:
					ShowPopup("Proxy Server File Transfer Error: Unknown command issued.", ERROR_POPUP);
					break;
				}

			}
			else if (type == 0x0003)
			{
				unsigned short port = _htons(*(unsigned short*)&packetRecv.buffer[12]);
				unsigned long  ip   = _htonl(*(unsigned long*)&packetRecv.buffer[14]);
				
				aim_send_file(hServerConn, seqno, ip, port, true, ft);
				LOG("Stage %d Proxy ft and we are not the sender.", ft->req_num);
			}
			else if (type == 0x0005) 
			{
				if (!ft->requester) 
				{
					aim_file_ad(hServerConn, seqno, ft->sn, ft->icbm_cookie, false, ft->max_ver);
					ft->accepted = true;
				}

				sendBroadcast(ft->hContact, ACKTYPE_FILE, ACKRESULT_CONNECTED, ft, 0);

				int i;
				for (i = 21; --i; )
				{
					if (Miranda_Terminated()) return;
					Sleep(100);
					if (ft->accepted) break;
				}
				if (i == 0) 
				{
					sendBroadcast(ft->hContact, ACKTYPE_FILE, ACKRESULT_FAILED, ft, 0);
					break;
				}

				packetRecv.dwTimeout = 350000;

				int result;
				if (ft->sending)//we are sending
					result = sending_file(ft, hServerPacketRecver, packetRecv);
				else 
					result = receiving_file(ft, hServerPacketRecver, packetRecv);

				sendBroadcast(ft->hContact, ACKTYPE_FILE, result ? ACKRESULT_FAILED : ACKRESULT_SUCCESS, ft, 0);
				break;
			}
		}
	}
	Netlib_CloseHandle(hServerPacketRecver);
	Netlib_CloseHandle(ft->hConn);

	ft_list.remove_by_ft(ft);
}
Пример #22
0
unsigned long SNAC::ulong(int pos)
{
	return _htonl(*(unsigned long*)&value_[pos]);
}
Пример #23
0
extern "C" __declspec(dllexport) const PLUGININFOEX* MirandaPluginInfoEx(DWORD mirandaVersion)
{
	*(unsigned long*)(&AIM_CAP_MIRANDA[8]) = _htonl(mirandaVersion);
	*(unsigned long*)(&AIM_CAP_MIRANDA[12]) = _htonl(PLUGIN_MAKE_VERSION(__MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM));
	return &pluginInfo;
}
Пример #24
0
/**
 * \brief Main application function.
 *
 * Initialize system, UART console, network then start time client.
 *
 * \return Program return value.
 */
int main(void)
{
	tstrWifiInitParam param;
	int8_t ret;
	struct sockaddr_in addr_in;

	/* Initialize the board. */
	system_init();

	/* Initialize the UART console. */
	configure_console();
	printf(STRING_HEADER);

	/* Initialize the BSP. */
	nm_bsp_init();

	/* Initialize Wi-Fi parameters structure. */
	memset((uint8_t *)&param, 0, sizeof(tstrWifiInitParam));

	/* Initialize Wi-Fi driver with data and status callbacks. */
	param.pfAppWifiCb = wifi_cb;
	ret = m2m_wifi_init(&param);
	if (M2M_SUCCESS != ret) {
		printf("main: m2m_wifi_init call error!(%d)\r\n", ret);
		while (1) {
		}
	}

	/* Turn LED0 off initially. */
	port_pin_set_output_level(LED_0_PIN, true);

	/* Initialize Socket module */
	socketInit();

	/* Register socket handler, resolve handler */
	registerSocketCallback(socket_cb, resolve_cb);

	/* Connect to router. */
	m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID),
			MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL);

	while (1) {
		/* Handle pending events from network controller. */
		m2m_wifi_handle_events(NULL);

		if (gbConnectedWifi) {
			/*
			 * Create the socket for the first time.
			 */
			if (udp_socket < 0) {
				udp_socket = socket(AF_INET, SOCK_DGRAM, 0);
				if (udp_socket < 0) {
					printf("main: UDP Client Socket Creation Failed.\r\n");
					continue;
				}

				/* Initialize default socket address structure. */
				addr_in.sin_family = AF_INET;
				addr_in.sin_addr.s_addr = _htonl(MAIN_DEFAULT_ADDRESS);
				addr_in.sin_port = _htons(MAIN_DEFAULT_PORT);

				bind(udp_socket, (struct sockaddr *)&addr_in, sizeof(struct sockaddr_in));
			}
		}
	}

	return 0;
}
Пример #25
0
// used when requesting a regular file transfer
int CAimProto::aim_send_file(HANDLE hServerConn, unsigned short &seqno,
                             unsigned long ip, unsigned short port,
                             bool force_proxy, file_transfer *ft)
{
    char msg_frag[2048];
    unsigned short frag_offset = 0;

    aim_writeshort(0, frag_offset, msg_frag);                        // request type
    aim_writegeneric(8, ft->icbm_cookie, frag_offset, msg_frag);     // icbm cookie
    aim_writegeneric(AIM_CAPS_LENGTH, AIM_CAP_FILE_TRANSFER,
                     frag_offset, msg_frag);                                       // uuid
    aim_writetlvshort(0x0a, ++ft->req_num, frag_offset, msg_frag);   // request number

    aim_writetlvlong(0x02, ip, frag_offset, msg_frag);               // ip
    aim_writetlvlong(0x16, ~ip, frag_offset, msg_frag);              // ip check

    aim_writetlvshort(0x05, port, frag_offset, msg_frag);            // port
    aim_writetlvshort(0x17, ~port, frag_offset, msg_frag);           // port ip check

    if (force_proxy)
        aim_writetlv(0x10, 0, 0, frag_offset, msg_frag);              // request proxy transfer
    else
        aim_writetlvlong(0x03, m_internal_ip, frag_offset, msg_frag); // ip

    if (ft->req_num == 1) {
        if (ft->message) {
            aimString dscr(ft->message);

            const char* charset = dscr.isUnicode() ? "unicode-2-0" : "us-ascii";
            const unsigned short charset_len = (unsigned short)mir_strlen(charset);

            const char* desc_msg = dscr.getBuf();
            const unsigned short desc_len = dscr.getSize();

            aim_writetlv(0x0e, 2, "en", frag_offset, msg_frag);             // language used by the data
            aim_writetlv(0x0d, charset_len, charset, frag_offset, msg_frag);// charset used by the data
            aim_writetlv(0x0c, desc_len, desc_msg, frag_offset, msg_frag);  // invitaion text
        }

        aim_writetlv(0x0f, 0, 0, frag_offset, msg_frag);                    // request host check

        const char* fname = get_fname(ft->file);
        const unsigned short fnlen = (unsigned short)mir_strlen(fname);

        char* fblock = (char*)alloca(9 + fnlen);
        *(unsigned short*)&fblock[0] = _htons(ft->pfts.totalFiles > 1 ? 2 : 1);     // single file transfer
        *(unsigned short*)&fblock[2] = _htons(ft->pfts.totalFiles);     // number of files
        *(unsigned long*)&fblock[4] = _htonl(ft->pfts.totalBytes);     // total bytes in files
        memcpy(&fblock[8], fname, fnlen + 1);

        const char* enc = is_utf(fname) ? "utf-8" : "us-ascii";
        aim_writetlv(0x2711, 9 + fnlen, fblock, frag_offset, msg_frag);               // extra data, file names, size
        aim_writetlv(0x2712, 8, enc, frag_offset, msg_frag);                        // character set used by data
//        aim_writetlvlong64(0x2713,ft->pfts.totalBytes,frag_offset,msg_frag);    // file length

        debugLogA("Attempting to Send a file to a buddy.");
    }
    else {
        aim_writetlvshort(0x14, 0x0a, frag_offset, msg_frag);              // Counter proposal reason
    }

    unsigned short offset = 0;
    unsigned short sn_length = (unsigned short)mir_strlen(ft->sn);
    char* buf = (char*)alloca(SNAC_SIZE + TLV_HEADER_SIZE * 2 + 12 + frag_offset + sn_length);
    aim_writesnac(0x04, 0x06, offset, buf);                                // msg to host
    aim_writegeneric(8, ft->icbm_cookie, offset, buf);                     // icbm cookie
    aim_writeshort(2, offset, buf);                                       // icbm channel
    aim_writechar((unsigned char)sn_length, offset, buf);                 // screen name length
    aim_writegeneric(sn_length, ft->sn, offset, buf);                      // screen name
    aim_writetlv(0x05, frag_offset, msg_frag, offset, buf);                 // icbm tags
    aim_writetlv(0x03, 0, 0, offset, buf);                                  // request ack

    char cip[20];
    long_ip_to_char_ip(ip, cip);
    debugLogA("IP for Buddy to connect to: %s:%u", cip, port);
    return aim_sendflap(hServerConn, 0x02, offset, buf, seqno) == 0;
}
Пример #26
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;
}
Пример #27
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;
}
Пример #28
0
/**
 * \brief Main application function.
 *
 * Initialize system, UART console, network then start function of UDP socket.
 *
 * \return program return value.
 */
int main(void)
{
	tstrWifiInitParam param;
	int8_t ret;
	struct sockaddr_in addr;

	/* Initialize the board. */
	sysclk_init();
	board_init();

	/* Initialize the UART console. */
	configure_console();
	printf(STRING_HEADER);

	/* Initialize the BSP. */
	nm_bsp_init();

	/* Initialize socket address structure. */
	addr.sin_family = AF_INET;
	addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT);
	addr.sin_addr.s_addr = _htonl(MAIN_WIFI_M2M_SERVER_IP);

	/* Initialize Wi-Fi parameters structure. */
	memset((uint8_t *)&param, 0, sizeof(tstrWifiInitParam));

	/* Initialize Wi-Fi driver with data and status callbacks. */
	param.pfAppWifiCb = wifi_cb;
	ret = m2m_wifi_init(&param);
	if (M2M_SUCCESS != ret) {
		printf("main: m2m_wifi_init call error!(%d)\r\n", ret);
		while (1) {
		}
	}

	/* Initialize socket module */
	socketInit();
	registerSocketCallback(socket_cb, NULL);

	/* Connect to router. */
	m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID), MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL);

	packetCnt = 0;
	while (1) {
		if (packetCnt >= MAIN_WIFI_M2M_PACKET_COUNT) {
			printf("UDP Server test Complete!\r\n");
			close(rx_socket);
			rx_socket = -1;
			break;
		}

		m2m_wifi_handle_events(NULL);

		if (wifi_connected == M2M_WIFI_CONNECTED) {
			/* Create socket for Rx UDP */
			if (rx_socket < 0) {
				if ((rx_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
					printf("main : failed to create RX UDP Client socket error!\r\n");
					continue;
				}

				/* Socket bind */
				bind(rx_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in));
			}
		}
	}

	return 0;
}