Exemple #1
0
bool HttpSession::onReceive()
{
    int n;

    if (status == HTTP_STATUS_CONNECT) {
        n = recv(sock, buf, sizeof(buf), 0);
        if (n <= 0)
            goto failed;

        buf[n] = '\0';

        char *p1 = strchr(buf, ' ');
        char *p2 = strchr(buf, '\r');
        if (!p1 || !p2)
            goto failed;

        ++p1;
        if (strnicmp(p1, "200 Connection established", p2 - p1) != 0)
            goto failed;

        status = HTTP_STATUS_ESTABLISHED;
        listener->sessionFinished(true);

    } else if (status == HTTP_STATUS_ESTABLISHED)
        return recvPacket();

    return true;
failed:
    IcqSocket::closeSocket(sock);
    sock = -1;
    listener->sessionFinished(false);
    return false;
}
Exemple #2
0
int RtpCtrlThread::recvPackets( unsigned char *buffer, ssize_t nBytes )
{
    unsigned char *bufferPtr = buffer;

    // u_int32 len;        /* length of compound RTCP packet in words */
    // rtcp_t *r;          /* RTCP header */
    // rtcp_t *end;        /* end of compound RTCP packet */

    // if ((*(u_int16 *)r & RTCP_VALID_MASK) != RTCP_VALID_VALUE) {
        // /* something wrong with packet format */
    // }
    // end = (rtcp_t *)((u_int32 *)r + len);

    // do r = (rtcp_t *)((u_int32 *)r + r->common.length + 1);
    // while (r < end && r->common.version == 2);

    // if (r != end) {
        // /* something wrong with packet format */
    // }

    while ( nBytes > 0 )
    {
        int consumed = recvPacket( bufferPtr, nBytes );
        if ( consumed <= 0 )
            break;
        bufferPtr += consumed;
        nBytes -= consumed;
    }
    return( nBytes );
}
Exemple #3
0
DWORD serverThread(void* ptr) {
#else
void* serverThread(void *ptr) {
#endif
	char buffer[2048];
	int length;
	int result;

	do {
		int ms = qbTickCount();
		
		LOCK(lock);
		length=recvPacket(buffer);
		if(length>0) {
			result=processServerPacket((unsigned char *)buffer,length);
			cs->timestamp=_GetTickCount();
		} else {
			result=0;
		}
		UNLOCK(lock);

		int elapsed = qbTickCount() - ms;
		throttle( elapsed, QB_MIN_FRAMETIME );
		
	} while(result==0 && ! kill_server_thread);
	if(online) {
		qbLog("*** Server Disconnected ***");
	}
	online=false;
	return 0;
}
int RtpDataThread::run()
{
  Debug( 2, "Starting data thread %d on port %d", mRtpSource.getSsrc(), mRtpSource.getLocalDataPort() );

  SockAddrInet localAddr;
  UdpInetServer rtpDataSocket;
  if ( mRtpSource.getLocalHost() != "" ) {
    if ( !rtpDataSocket.bind( mRtpSource.getLocalHost().c_str(), mRtpSource.getLocalDataPort() ) )
      Fatal( "Failed to bind RTP server" );
    Debug( 3, "Bound to %s:%d",  mRtpSource.getLocalHost().c_str(), mRtpSource.getLocalDataPort() );
  }
  else
  {
    if ( !rtpDataSocket.bind( mRtspThread.getAddressFamily() == AF_INET6 ? "::" : "0.0.0.0", mRtpSource.getLocalDataPort() ) )
      Fatal( "Failed to bind RTP server" );
    Debug( 3, "Bound to %s:%d",  mRtpSource.getLocalHost().c_str(), mRtpSource.getLocalDataPort() );
  }

  Select select( 3 );
  select.addReader( &rtpDataSocket );

  unsigned char buffer[ZM_NETWORK_BUFSIZ];
  while ( !mStop && select.wait() >= 0 )
  {
     if ( mStop )
      break;
     Select::CommsList readable = select.getReadable();
     if ( readable.size() == 0 )
     {
       Error( "RTP timed out" );
       mStop = true;
       break;
     }
     for ( Select::CommsList::iterator iter = readable.begin(); iter != readable.end(); iter++ )
     {
       if ( UdpInetServer *socket = dynamic_cast<UdpInetServer *>(*iter) )
       {
         int nBytes = socket->recv( buffer, sizeof(buffer) );
         Debug( 4, "Got %d bytes on sd %d", nBytes, socket->getReadDesc() );
         if ( nBytes )
         {
            recvPacket( buffer, nBytes );
         }
         else
         {
          mStop = true;
          break;
         }
       }
       else
       {
         Panic( "Barfed" );
       }
     }
  }
  rtpDataSocket.close();
  mRtspThread.stop();
  return( 0 );
}
Exemple #5
0
bool TcpSession::onReceive()
{
	if (status == TCP_STATUS_ESTABLISHED || status == TCP_STATUS_HELLO_WAIT)
		return recvPacket();

	int n = recv(sock, buf, sizeof(buf), 0);

	switch (status) {
	case TCP_STATUS_SOCKS_METHOD:
		if (n != 2 || buf[0] != 5 || (buf[1] != 0 && buf[1] != 2))
			return false;
		if (buf[1] == 0)
			status = TCP_STATUS_SOCKS_CONNECT;
		else {
			status = TCP_STATUS_SOCKS_AUTH;

			ProxyInfo &socks = icqLink->options.proxy[PROXY_SOCKS];
			char *p = buf;
			*p++ = 1;
			*p++ = n = socks.username.length();
			memcpy(p, socks.username.c_str(), n);
			p += n;
			*p++ = n = socks.passwd.length();
			memcpy(p, socks.passwd.c_str(), n);
			p += n;
			send(sock, buf, p - buf, 0);
		}
		break;

	case TCP_STATUS_SOCKS_AUTH:
		if (n != 2 || buf[0] != 1 || buf[1] != 0)
			return false;
		status = TCP_STATUS_SOCKS_CONNECT;
		break;

	case TCP_STATUS_SOCKS_CONNECT:
		if (n != 10 || buf[0] != 5 || buf[1] != 0)
			return false;
		onTcpEstablished();
		break;

	default:
		return false;
	}

	if (status == TCP_STATUS_SOCKS_CONNECT) {
		buf[0] = 5;
		buf[1] = 1;
		buf[2] = 0;
		buf[3] = 1;
		*(uint32 *) &buf[4] = htonl(destIP);
		*(uint16 *) &buf[8] = htons(destPort);
		send(sock, buf, 10, 0);
	}
	return true;
}
Client::State Client::recvPackets() {
    packet inpkt;
    packet outpkt;

    // Check for timeout
    switch (recvPacket(inpkt)) {
    case 1:
        // Receive error.
        return ERROR;
    case 2:
        // Bad checksum or timeout.
        outpkt = rejpkt(mvSequence);
        break;
    default:
        // if sequence is less than or equal to our own, send RR.  Even if it's
        // lower than it's supposed to be, we'll just send the RR to make the
        // server feel better about itself.
        if (inpkt.sequence <= mvSequence) {
            mvRetries = PKT_TRNSMAX;
            outpkt = rrpkt(inpkt.sequence);
            
            if (inpkt.sequence == mvSequence) {
                mvSequence++;
                
                if (writeTo(inpkt) == 1) {
                    return ERROR;
                }
                
                if (inpkt.type == PKT_TYPE_DAT && inpkt.size < mvBufferSize) {
                    // A valid, less-than-maximum sized packet indicates
                    // end-of-file
                    return DONE;
                }
            }
        } else {
            // if the sequence is outright wrong, however...
            std::cout << "Received packet with incorrect sequence.  Expected "
                      << mvSequence << " or lower.  Received " << inpkt.sequence
                      << std::endl;
            outpkt = rejpkt(mvSequence);
        }
    }
    
    // Send response packet
    if (sendtoErr(mvSocket, &outpkt, sizeof(packet), 0, (sockaddr *)&mvAddr,
                  mvAddrLen) == -1)
    {
        std::cerr << "sendto (" << __LINE__ << "): " << strerror(errno)
                  << std::endl;
        return ERROR;
    }
    
    return RECV_PACKETS;
}
Exemple #7
0
void input(void)
{
   uint8_t command;
   uint8_t size;
   uint8_t *data;

   while(recvPacket(&command, &size, &data))
   {
      switch(command)
      {
         case 'r':
         {
            cli();
            for(;;);
            break;
         }
         case 'c':
         {
            channel[data[0]] = data[1];
            break;
         }
         case 'p':
         {
            pchannel = data[0];
            break;
         }
         case 'i':
         {
            switch(pchannel)
            {
               #include "../ptable.inc"
            }
            break;
         }
         case 'm':
         {
            measurementOut = true;
            break;
         }
         case 's':
         {
            measurementOut = false;
            break;
         }
         case 'x':
         {
            measurementOut = !measurementOut;
            break;
         }
      }
   }
}
 void runMap(int socketID, int num, __cilkrts_ivar* iv){
  frame f;
  my_timer_t t;

  f.data = num;
  printf("calling %d..\n", socketID);
  TIMER_START(t);
  sendPacket(socketID, &f, sizeof(f));

  recvPacket(socketID, &f, sizeof(f));
  TIMER_STOP(t);

  printf("returned: %d\ttime: %f\tsocket: %d\n", f.data, TIMER_EVAL(t), socketID);
  cilk_spawn __cilkrts_ivar_write(iv, f.data);
} 
Exemple #9
0
int runMap(int socketID, int num){
  frame f;
  my_timer_t t;

  f.data = num;
  printf("calling %d..\n", socketID);
  TIMER_START(t);
  sendPacket(socketID, &f, sizeof(f));

  recvPacket(socketID, &f, sizeof(f));
  TIMER_STOP(t);

  printf("returned: %d\ttime: %f\tsocket: %d\n", f.data, TIMER_EVAL(t), socketID);
  return f.data;
} 
Exemple #10
0
void *Connection::query(const char *_query, size_t _cbQuery)
{
  m_dbgMethodProgress ++;

  if (m_dbgMethodProgress > 1)
  {
    /*
    NOTE: We don't call setError here because it will close the socket worsening the concurrent access error making it impossible to trace */
    m_errorMessage = "Concurrent access in query method";
    m_errno = 0;
    m_errorType = UME_OTHER;
    m_dbgMethodProgress --;
    return NULL;
  }

  if (m_sockInst == NULL)
  {
    PRINTMARK();
    setError ("Not connected", 0, UME_OTHER);
    m_dbgMethodProgress --;
    return NULL;
  }

  size_t len = _cbQuery;

  if (len > m_writer.getSize () - (MYSQL_PACKET_HEADER_SIZE + 1))
  {
    PRINTMARK();
    setError ("Query too big", 0, UME_OTHER);
    m_dbgMethodProgress --;
    return NULL;
  }

  m_writer.reset();
  m_writer.writeByte(MC_QUERY);
  m_writer.writeBytes ( (void *) _query, len);
  m_writer.finalize(0);

  if (!sendPacket())
  {
    PRINTMARK();
    m_dbgMethodProgress --;
    return NULL;
  }

  if (!recvPacket())
  {
    PRINTMARK();
    m_dbgMethodProgress --;
    return NULL;
  }

  UINT8 result = m_reader.readByte();

  switch (result)
  {
  case 0x00:
    PRINTMARK();
    m_dbgMethodProgress --;
    return handleOKPacket();

  case 0xff:
    PRINTMARK();
    handleErrorPacket();
    m_dbgMethodProgress --;
    return NULL;

  case 0xfe:
    PRINTMARK();
    setError ("Unexpected EOF when decoding result", 0, UME_OTHER);
    m_dbgMethodProgress --;
    return NULL;


  default:
    PRINTMARK();
    m_dbgMethodProgress --;
    return handleResultPacket((int)result);
  }

  PRINTMARK();
  m_dbgMethodProgress --;
  return NULL;
}
Exemple #11
0
bool Connection::connect(const char *_host, int _port, const char *_username, const char *_password, const char *_database, int *_autoCommit, MYSQL_CHARSETS _charset)
{
  m_dbgMethodProgress ++;

  if (m_dbgMethodProgress > 1)
  {
    /*
    NOTE: We don't call setError here because it will close the socket worsening the concurrent access error making it impossible to trace */
    m_errorMessage = "Concurrent access in connect method";
    m_errno = 0;
    m_errorType = UME_OTHER;
    m_dbgMethodProgress --;
    return false;
  }


  if (m_sockInst != NULL)
  {
    m_dbgMethodProgress --;
    setError ("Socket already connected", 0, UME_OTHER);
    return false;
  }

  m_host = _host ? _host : "localhost";
  m_port = _port ? _port : 3306;
  m_username = _username ? _username : "";
  m_password = _password ? _password : "";
  m_database = _database ? _database : "";
  m_autoCommit = _autoCommit ? (*_autoCommit) != 0 : false;
  m_charset = _charset;

  PRINTMARK();
  m_sockInst = m_capi.getSocket();

  if (m_sockInst == NULL)
  {
    m_dbgMethodProgress --;
    return false;
  }

  if (m_timeout != -1)
  {
    if (!setTimeout (m_timeout))
    {
      m_dbgMethodProgress --;
      return false;
    }
  }

  if (!connectSocket())
  {
    m_dbgMethodProgress --;
    return false;
  }

  PRINTMARK();
  if (!recvPacket())
  {
    m_dbgMethodProgress --;
    return false;
  }

  PRINTMARK();
  if (!processHandshake())
  {
    m_dbgMethodProgress --;
    return false;
  }

  PRINTMARK();
  if (!sendPacket())
  {
    m_dbgMethodProgress --;
    return false;
  }

  PRINTMARK();
  m_writer.reset();

  if (!recvPacket())
  {
    m_dbgMethodProgress --;
    return false;
  }

  PRINTMARK();
  UINT8 result = m_reader.readByte();
  if (result == 0xff)
  {
    handleErrorPacket();
    m_dbgMethodProgress --;
    return false;
  }

  m_reader.skip();

  PRINTMARK();
  if (_autoCommit)
  {
    PRINTMARK();
    char strTemp[256 + 1];
    PRINTMARK();
    size_t len = snprintf (strTemp, 256, "SET AUTOCOMMIT = %d", *_autoCommit);
    PRINTMARK();
    m_writer.reset();
    m_writer.writeByte(MC_QUERY);
    m_writer.writeBytes ( (void *) strTemp, len);
    m_writer.finalize(0);

    PRINTMARK();
    if (!sendPacket())
    {
      m_dbgMethodProgress --;
      return false;
    }

    PRINTMARK();
    if (!recvPacket())
    {
      m_dbgMethodProgress --;
      return false;
    }
    m_reader.skip();
  }

  PRINTMARK();
  m_state = QUERY_WAIT;
  m_dbgMethodProgress --;

  return true;
}
void authentificationThread()
{
	// initialisation de la structure sockaddr_in d'ecoute.

	AccountsList *list = loadAccountsFromFile(ACCOUNTS_FILE); // ajouter la détection de l'existence du fichier.
	if(list == NULL)
	{
		errorMessage("Accounts file is corrupted");
		return;
	}

	struct sockaddr_in server;
	initServerSocketAddress(&server);
	int listen_socket = createServerListenSocket(&server);


	ConnectionList connection_list;
	connection_list.nb_connections = 0;

	// initialisation de la fine d'attente des joueurs à charger sur la map et des joueurs déconnectés.
	PlayersQueue players_queues[2];
	initPlayersQueue(&players_queues[0]);
	initPlayersQueue(&players_queues[1]);

	PlayersQueue *new_players_queue = players_queues;
	PlayersQueue *disconnected_players_queue = &players_queues[1];

	// lancement du thread s'occupant de la gestion du déroulement du jeu.

#ifdef RUN_GAME_MANAGEMENT_THREAD
	runGameManagementThread(players_queues);
#endif
	int _continue, return_value;
	char *login, *password;
	Player *player;
	Connection * current_connection;
	int connection_index, account_index;
	GenericPacket packet;
	Buffer recv_buffer, send_buffer;
	initBuffer(&recv_buffer);
	initBuffer(&send_buffer);

	// utilise pour rendr le thread inactif pendant un certain temps.
	int no_activity = 0;
	struct timespec wait_time = {0, 150000}, sleep_return;

	long last_save_time = getTime();
	char save_needed = FALSE;

	while(1)
	{
		no_activity = TRUE;

		acceptNewConnections(listen_socket, &connection_list);
		/// il reste a traiter les packets éventuels de chaque connexion.
		for(connection_index = 0; connection_index < connection_list.nb_connections; connection_index++)
		{
			current_connection = & connection_list.connections[connection_index];
			_continue = TRUE;
			while(_continue)
			{
				return_value = recvPacket(current_connection, &packet, &recv_buffer);
				if(return_value == 1) // traitement du packet recu.
				{
					no_activity = FALSE;
					if(packet.type == AUTHENTIFICATION_REQUEST)
					{
						if(extractLoginAndPassword(&packet, &recv_buffer, &login, &password) < 0) // si la forme des donnees du paquet est incorrecte, on rejette la demande d'authentification.
							sendAuthentificationAnswer(current_connection, &send_buffer, REJECT_AUTHENTIFICATION);
						else if(!isCorrectLoginOrPassword(login)) // si le login est syntaxiquement incorrecte, on rejette la demande d'authentification.
						{
							debugMessage("Authentication has failed : login \"%s\" is syntactically false", login);
							if((return_value = sendAuthentificationAnswer(current_connection, &send_buffer, REJECT_AUTHENTIFICATION)) == -2)
							{
								warningMessage("Current connection is lost.");
								removeConnectionFromList(& connection_list, connection_index);
								connection_index--;
								_continue = FALSE;
							}
						}
						else if(!isCorrectLoginOrPassword(password)) // si le mot de passe est syntaxiquement incorrecte, on rejette la demande d'authentification.
						{
							debugMessage("Authentication has failed : password \"%s\" is syntactically false", password);
							if((return_value = sendAuthentificationAnswer(current_connection, &send_buffer, REJECT_AUTHENTIFICATION)) == -2)
							{
								warningMessage("Current connection is lost.");
								removeConnectionFromList(& connection_list, connection_index);
								connection_index--;
								_continue = FALSE;
							}
						}
						else if((account_index = getAccountPosition(list, login)) < 0) // Si le login ne correspond à aucun compte, on rejette la demande d'authentification.
						{
							debugMessage("Authentication has failed : none account matching with login \"%s\".", login);
							if((return_value = sendAuthentificationAnswer(current_connection, &send_buffer, REJECT_AUTHENTIFICATION)) == -2)
							{
								warningMessage("Current connection is lost.");
								removeConnectionFromList(& connection_list, connection_index);
								connection_index--;
								_continue = FALSE;
							}
						}
						else if(list->accounts[account_index].opened) // Si le compte correspondant au login est deja ouvert, on rejette la demande d'authentification.
						{
							debugMessage("Authentication has failed : account \"%s\" is already opened.", login);
							if((return_value = sendAuthentificationAnswer(current_connection, &send_buffer, REJECT_AUTHENTIFICATION)) == -2)
							{
								warningMessage("Current connection is lost.");
								removeConnectionFromList(& connection_list, connection_index);
								connection_index--;
								_continue = FALSE;
							}
						}
						else if(list->accounts[account_index].opened) // Si le compte correspondant est deja utilise, on rejette la demande d'authentification.
						{
							debugMessage("Authentication has failed : account \"%s\" is already opened.", password, login);
							if((return_value = sendAuthentificationAnswer(current_connection, &send_buffer, REJECT_AUTHENTIFICATION)) == -2)
							{
								warningMessage("Current connection is lost.");
								removeConnectionFromList(& connection_list, connection_index);
								connection_index--;
								_continue = FALSE;
							}
						}
						else if(strcmp(password, list->accounts[account_index].password)) // Si le compte correspondant au login a un mot de passe different de celui recu, on rejette la demande d'authentification.
						{
							debugMessage("Authentication has failed : password \"%s\" is incorrect for account \"%s\".", password, login);
							if((return_value = sendAuthentificationAnswer(current_connection, &send_buffer, REJECT_AUTHENTIFICATION)) == -2)
							{
								warningMessage("Current connection is lost.");
								removeConnectionFromList(& connection_list, connection_index);
								connection_index--;
								_continue = FALSE;
							}
						}
						else // l'authentification a reussi, on supprime donc la connection du service de comptes.
						{
							if((return_value = sendAuthentificationAnswer(current_connection, &send_buffer, ACCEPT_AUTHENTIFICATION)) == -2)
								warningMessage("Current connection is lost.");

							if(addPlayerToQueue(new_players_queue, (player = createPlayerForAccount(& list->accounts[account_index], current_connection))) < 0) // Si la file d'attente des noueaux joueurs en attente de chargement sur la map est pleine, on rejette la demande d'authentification.
							{
								destroyPlayer(player);
								debugMessage("Authentication has failed : new players queue is full.");
								if((return_value = sendAuthentificationAnswer(current_connection, &send_buffer, REJECT_AUTHENTIFICATION)) == -2)
								{
									warningMessage("Current connection is lost.");
									removeConnectionFromList(& connection_list, connection_index);
									connection_index--;
									_continue = FALSE;
								}
							}
							else
							{
								removeConnectionFromList(& connection_list, connection_index);
								connection_index--;
								_continue = FALSE;
								list->accounts[account_index].opened = TRUE;
								debugMessage("player %s is authenticated", login);
							}
						}
					}
					else // le type du paquet ne concerne pas le service de comptes, donc on l'ignore.
						warningMessage("packet received is not for account management : type is %d", packet.type);
				}
				else if(return_value == 0) // aucun nouveau paquet recu, donc on traite l'eventuelle connexion suivante.
					_continue = FALSE;
				else if(return_value == -1)
					_continue = FALSE;
				else // la connexion est perdue, donc on la supprime de la liste des connexions et on traite l'eventuelle connexion suivante.
				{
					no_activity = FALSE;
					removeConnectionFromList(& connection_list, connection_index);
					connection_index--;
					_continue = FALSE;
				}
			}
		}

		// on traite l'ensemble des joueurs deconnectes.
		while((player = removePlayerFromQueue(disconnected_players_queue)) != NULL)
		{
			no_activity = FALSE;

			account_index = getAccountPosition(list, player->login); // on recupere l'indice du compte associe au joueur 'player'
			if(account_index >= 0) // si le compte est retrouve, on le met a jour.
			{
				list->accounts[account_index].opened = FALSE;
				list->accounts[account_index].pos_x = player->position.x;
				list->accounts[account_index].pos_y = player->position.y;
				save_needed = TRUE;
			}
			destroyPlayer(player);
		}

		if(save_needed && getTime() - last_save_time > 30000000) // sauvegarde des comptes toutes les 30 secondes.
		{
			saveAccountsFile(ACCOUNTS_FILE, list);
			save_needed = FALSE;
			last_save_time = getTime();
		}

		// si aucune activite (reception de paquet ou demande de connexion) n'a eu lieu, alors on rend le thread inactif pendant un certain temps afin de limiter la consommation des ressouces processeur.
		if(no_activity == TRUE)
			nanosleep(&wait_time, &sleep_return);
	}
}
Exemple #13
0
/////////////////////////////////////////////////////////////////////////
// The thread process the user's conversation: Get user's request command, send it
// to scheduler, Get the response code and return it to user.
// The parameter "lpvParam" if the NamedPipe instance handle value.
DWORD WINAPI TcpipClientAgentThread( LPVOID lpvParam )
{
	LPTS_COM_PROPS lptsComProps;
	REQUEST 	Request;
	CHAR 		szBuffer[PIPE_BUFFER_SIZE];
	DWORD 		cbWriten, cbReaded;
	DWORD 		dwRetCode;
	int 		iRet;
	BOOL 		fDirect = TRUE;
	MSG 		Msg;
	SOCKET 		iSocket;

	iSocket = (SOCKET)lpvParam;

	// If the parameter lpvParam is an invalid pipe handle.
	//if( iSocket == SOCKET_ERROR )
	//	ExitThread( ERROR_INVALID_PARAMETER );

	GetQueueStatus( QS_SENDMESSAGE );

	lprintfs( "Client agent thread starts.\n" );

	_try {
	// Wait and read the message send by the client, until the client post.

	cbReaded = recvPacket(iSocket, szBuffer, PIPE_BUFFER_SIZE);
	//if( cbReaded == SOCKET_ERROR ) {
	if( cbReaded <= 0 ) {
		ExitThread( GetLastError() );
	}

	// Get the packet header, analyse the packet information.
	lptsComProps = (LPTS_COM_PROPS)szBuffer;

	// If the user's first packet is not logon information packet,
	// Reject the user's request.
	if( lptsComProps->packetType != pkTS_SYNC_PIPE ||
						lptsComProps->msgType != msgTS_CLIENT_LOGON ) {
		ZeroMemory( szBuffer, PIPE_BUFFER_SIZE );
		lptsComProps->packetType = pkTS_ERROR;
		lptsComProps->msgType = msgTS_ERROR_MSG;

		lptsComProps->len = wsprintfA( (LPSTR)(szBuffer+sizeof( TS_COM_PROPS )),
				"User can not access the server before logon." );

		iRet = sendPacket(iSocket, szBuffer,
							 lptsComProps->len+sizeof( TS_COM_PROPS ) );
		//if( iRet == SOCKET_ERROR ) {
		if( iRet <= 0 ) {
			ExitThread( GetLastError() );
		}

		ExitThread( TERR_NOT_LOGON );
	}

#ifndef TREESVR_STANDALONE
	// Add by Jingyu Niu, 2000.08.25, for support single user mode.
	if( singleUserMode ) {
		ZeroMemory( szBuffer, PIPE_BUFFER_SIZE );
		lptsComProps->packetType = pkTS_SYNC_PIPE;
		lptsComProps->msgType = msgTS_LOGON_ERROR;
		lptsComProps->lp = 0x10000;
		
		lptsComProps->len = wsprintfA( (LPSTR)(szBuffer+sizeof( TS_COM_PROPS )),
			"Server now running in single user mode, not accept connect request." );

		cbWriten = sendPacket( iSocket, szBuffer,
							 lptsComProps->len+sizeof(TS_COM_PROPS) );
		//if( cbWriten == SOCKET_ERROR ) {
		if( cbWriten <= 0 ) {
			ExitThread( GetLastError() );
		}

		ExitThread( 0x10000 );
	}
#endif
	
	// If the user's logon information packet is invalid,
	// Reject the user's request.
	dwRetCode = MsgToRequest( (LPCSTR)(szBuffer+sizeof( TS_COM_PROPS )), &Request );
	if( dwRetCode != TERR_SUCCESS ) {
		ZeroMemory( szBuffer, PIPE_BUFFER_SIZE );
		lptsComProps->packetType = pkTS_SYNC_PIPE;
		lptsComProps->msgType = msgTS_LOGON_ERROR;
		lptsComProps->lp = dwRetCode;
		
		lptsComProps->len = wsprintfA( (LPSTR)(szBuffer+sizeof( TS_COM_PROPS )),
			"Logon information error(error code:%ld).", dwRetCode );

		cbWriten = sendPacket( iSocket, szBuffer,
							 lptsComProps->len+sizeof(TS_COM_PROPS) );
		//if( cbWriten == SOCKET_ERROR ) {
		if( cbWriten <= 0 ) {
			ExitThread( GetLastError() );
		}

		ExitThread( dwRetCode );
	}
	
	// Send the request to scheduler.
	dwRetCode = SendRequest( &Request );
	if( dwRetCode != TERR_SUCCESS ) {
		ZeroMemory( szBuffer, PIPE_BUFFER_SIZE );
		lptsComProps->packetType = pkTS_ERROR;
		lptsComProps->msgType = msgTS_LOGON_ERROR;
		lptsComProps->lp = dwRetCode;
		
		lptsComProps->len = wsprintfA( (LPSTR)(szBuffer+sizeof( TS_COM_PROPS )),
			"Can not logon the server(error code:%ld).", dwRetCode );

		cbWriten = sendPacket( iSocket, szBuffer,
							 lptsComProps->len+sizeof(TS_COM_PROPS) );
		//if( cbWriten == SOCKET_ERROR ) {
		if( cbWriten <= 0 ) {
			ExitThread( GetLastError() );
		}

		ExitThread( dwRetCode );
	}


	ZeroMemory( szBuffer, PIPE_BUFFER_SIZE );
	lptsComProps->packetType = pkTS_SYNC_PIPE;

	if( Request.dwRequest == TERR_SUCCESS ) {
		lptsComProps->msgType = msgTS_LOGON_OK;
		lptsComProps->lp = Request.dwRequestId;
	}
	else {
		lptsComProps->msgType = msgTS_LOGON_ERROR;
		lptsComProps->lp = Request.dwRequest;
	}

	cbWriten = sendPacket( iSocket, szBuffer, sizeof(TS_COM_PROPS) );
	//if( cbWriten == SOCKET_ERROR ) {
	if( cbWriten <= 0 ) {
		ExitThread( GetLastError() );
	}

	if( Request.dwRequest != TERR_SUCCESS ) {
		ExitThread( TERR_SUCCESS );
	}

	// Add by NiuJingyu, 1998.03
	GetMessage( &Msg, NULL, TS_SERVICE_START, TS_SERVICE_START );

	dwRetCode = TERR_SUCCESS;

	while( 1 ) {
		if( fDirect ) {
			cbReaded = recvPacket(iSocket, szBuffer, PIPE_BUFFER_SIZE);
			//if( cbReaded == SOCKET_ERROR ) {
			if( cbReaded <= 0 ) {
				dwRetCode = GetLastError();
				CliSetExchBufError( Request.lpExchangeBuf );
				dwRetCode = TERR_CLIENT_CLOSE;
				break;
			}

			lptsComProps = (LPTS_COM_PROPS)szBuffer;
			if( lptsComProps->endPacket == '\x0' )
				fDirect = FALSE;

			if( lptsComProps->packetType == pkTS_SYNC_PIPE ) {
				if( lptsComProps->msgType == msgTS_PIPE_CLOSE ) {
					dwRetCode = TERR_SUCCESS;
					break;
				}
			} 

#ifndef TREESVR_STANDALONE
			// Add by Jingyu Niu, 2000.08.25, for support single user mode.
			if( singleUserMode && singleUserThread != GetCurrentThreadId() ) {
				if( fDirect )
					continue;
				else {
					dwRetCode = TERR_SUCCESS;
					break;
				}
			}

#endif
			
//			lprintfs( "########################## Client write exchange buffer.\n" );
			dwRetCode = CliWriteExchngBuf( Request.lpExchangeBuf, szBuffer, 4096 );
			if( dwRetCode != TERR_SUCCESS ) {
				break;
			}
		}
		else {
			// Service thread is voluntary.
			// Read the packet from service thread.
			dwRetCode = CliReadExchngBuf( Request.lpExchangeBuf, szBuffer, 4096 );
			if( dwRetCode != TERR_SUCCESS )
				break;

			lptsComProps = (LPTS_COM_PROPS)szBuffer;
			if( lptsComProps->endPacket == '\x0' )
				fDirect = TRUE;
	
			if( lptsComProps->packetType == pkTS_SYNC_PIPE ) {
				if( lptsComProps->msgType == msgTS_NO_DATA )
					continue;
			}

#ifndef TREESVR_STANDALONE
			// Add by Jingyu Niu, 2000.08.25, for support single user mode.
			if( singleUserMode && singleUserThread != GetCurrentThreadId() && fDirect ) {
				lptsComProps->packetType = pkTS_SYNC_PIPE;
				lptsComProps->msgType = msgTS_PIPE_CLOSE;
				lptsComProps->lp = 0;
				lptsComProps->len = 0;
				lptsComProps->leftPacket = '\x0';
				lptsComProps->endPacket = '\x0';

				dwRetCode = CliWriteExchngBuf( Request.lpExchangeBuf, szBuffer, 4096 );
				break;
			}
#endif

			cbWriten = sendPacket( iSocket, szBuffer,
								 lptsComProps->len+sizeof(TS_COM_PROPS) );
			//if( cbWriten == SOCKET_ERROR ) {
			if( cbWriten <= 0 ) {
				dwRetCode = GetLastError();
				CliSetExchBufError( Request.lpExchangeBuf );
				break;
			}
		}

		dwRetCode = TERR_SUCCESS;
	}

	if( dwRetCode == TERR_SUCCESS ) {
		ZeroMemory( szBuffer, 4096 );
		lptsComProps->packetType = pkTS_SYNC_PIPE;
		lptsComProps->msgType = msgTS_CLIENT_LOGOFF;
		dwRetCode = CliWriteExchngBuf( Request.lpExchangeBuf, szBuffer, 4096 );
		if( dwRetCode != TERR_SUCCESS )
			CliSetExchBufError( Request.lpExchangeBuf );
	}

	lprintfs( "Client agent thread ends.\n" );

	}
	_except ( EXCEPTION_EXECUTE_HANDLER ) {
		char szBuffer[256];

		wsprintf( szBuffer, "Client adent thread cause an exception.\n" );
		MessageBox( NULL, szBuffer, "Inspector", MB_OK | MB_ICONSTOP );
	}

	closesocket( iSocket );
	ExitThread( TERR_SUCCESS );

	return  0;

}
void intf_sys_t::handleMessages()
{
    unsigned i_received = 0;
    uint8_t p_packet[PACKET_MAX_LEN];
    bool b_pingTimeout = false;

    int i_waitdelay = PING_WAIT_TIME;
    int i_retries = PING_WAIT_RETRIES;

    bool b_msgReceived = false;
    uint32_t i_payloadSize = 0;
    int i_ret = recvPacket(p_stream, b_msgReceived, i_payloadSize, i_sock_fd,
                           p_tls, &i_received, p_packet, &b_pingTimeout,
                           &i_waitdelay, &i_retries);

    int canc = vlc_savecancel();
    // Not cancellation-safe part.

#if defined(_WIN32)
    if ((i_ret < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_ret == 0))
#else
    if ((i_ret < 0 && errno != EAGAIN) || i_ret == 0)
#endif
    {
        msg_Err(p_stream, "The connection to the Chromecast died (receiving).");
        vlc_mutex_locker locker(&lock);
        setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
        vlc_restorecancel(canc);
        return;
    }

    if (b_pingTimeout)
    {
        msgPing();
        msgReceiverGetStatus();
    }

    if (b_msgReceived)
    {
        castchannel::CastMessage msg;
        msg.ParseFromArray(p_packet + PACKET_HEADER_LEN, i_payloadSize);
        processMessage(msg);
    }

    // Send the answer messages if there is any.
    if (!messagesToSend.empty())
    {
        i_ret = sendMessages();
#if defined(_WIN32)
        if ((i_ret < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_ret == 0))
#else
        if ((i_ret < 0 && errno != EAGAIN) || i_ret == 0)
#endif
        {
            msg_Err(p_stream, "The connection to the Chromecast died (sending).");
            vlc_mutex_locker locker(&lock);
            setConnectionStatus(CHROMECAST_CONNECTION_DEAD);
        }
    }

    vlc_restorecancel(canc);
}
int tuntap_read(struct net_device *net_dev, void *buf, size_t count)
{
	if(net_dev->priv == NULL) return -1;
	return recvPacket((tap_win32*)net_dev->priv, buf, count);
}
Exemple #16
0
/*****************************************************************************
 * Chromecast thread
 *****************************************************************************/
static void* chromecastThread(void* p_data)
{
    int canc = vlc_savecancel();
    // Not cancellation-safe part.
    sout_stream_t* p_stream = (sout_stream_t*)p_data;
    sout_stream_sys_t* p_sys = p_stream->p_sys;

    unsigned i_received = 0;
    char p_packet[PACKET_MAX_LEN];
    bool b_pingTimeout = false;

    int i_waitdelay = PING_WAIT_TIME;
    int i_retries = PING_WAIT_RETRIES;

    msgAuth(p_stream);
    sendMessages(p_stream);
    vlc_restorecancel(canc);

    while (1)
    {
        bool b_msgReceived = false;
        uint32_t i_payloadSize = 0;
        int i_ret = recvPacket(p_stream, b_msgReceived, i_payloadSize, p_sys->i_sock_fd,
                               p_sys->p_tls, &i_received, p_packet, &b_pingTimeout,
                               &i_waitdelay, &i_retries);

        canc = vlc_savecancel();
        // Not cancellation-safe part.

#if defined(_WIN32)
        if ((i_ret < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_ret == 0))
#else
        if ((i_ret < 0 && errno != EAGAIN) || i_ret == 0)
#endif
        {
            msg_Err(p_stream, "The connection to the Chromecast died.");
            vlc_mutex_locker locker(&p_sys->lock);
            p_sys->i_status = CHROMECAST_CONNECTION_DEAD;
            atomic_store(&p_sys->ab_error, true);
            break;
        }

        if (b_pingTimeout)
        {
            msgPing(p_stream);
            msgStatus(p_stream);
        }

        if (b_msgReceived)
        {
            castchannel::CastMessage msg;
            msg.ParseFromArray(p_packet + PACKET_HEADER_LEN, i_payloadSize);
            processMessage(p_stream, msg);
        }

        // Send the answer messages if there is any.
        if (!p_sys->messagesToSend.empty())
        {
            i_ret = sendMessages(p_stream);
#if defined(_WIN32)
            if ((i_ret < 0 && WSAGetLastError() != WSAEWOULDBLOCK) || (i_ret == 0))
#else
            if ((i_ret < 0 && errno != EAGAIN) || i_ret == 0)
#endif
            {
                msg_Err(p_stream, "The connection to the Chromecast died.");
                vlc_mutex_locker locker(&p_sys->lock);
                p_sys->i_status = CHROMECAST_CONNECTION_DEAD;
            }
        }

        vlc_mutex_lock(&p_sys->lock);
        if ( p_sys->i_status == CHROMECAST_CONNECTION_DEAD )
        {
            atomic_store(&p_sys->ab_error, true);
            vlc_mutex_unlock(&p_sys->lock);
            break;
        }
        vlc_mutex_unlock(&p_sys->lock);

        vlc_restorecancel(canc);
    }

    return NULL;
}
Client::State Client::init() {
    // Build packets
    packet pkt[5];
    
    // connection packet
    memset(&pkt[0], PKT_TYPE_CXN, sizeof(packet));
    pkt[0].checksum = 0;
    pkt[0].sequence = 0;
    pkt[0].checksum = in_cksum((unsigned short *)&pkt[0], sizeof(packet));
    
    // 2nd stage connection response
    memset(&pkt[1], PKT_TYPE_CXN2, sizeof(packet));
    pkt[1].sequence = 1;
    pkt[1].checksum = 0;
    pkt[1].checksum = in_cksum((unsigned short *)&pkt[1], sizeof(packet));
    
    // buffer size packet
    memset(&pkt[2], PKT_TYPE_BUF, sizeof(packet));
    pkt[2].size = mvBufferSize;
    pkt[2].sequence = 2;
    pkt[2].checksum = 0;
    pkt[2].checksum = in_cksum((unsigned short *)&pkt[2], sizeof(packet));

    // window size packet
    memset(&pkt[3], PKT_TYPE_WIN, sizeof(packet));
    pkt[3].size = mvWindowSize;
    pkt[3].sequence = 3;
    pkt[3].checksum = 0;
    pkt[3].checksum = in_cksum((unsigned short *)&pkt[3], sizeof(packet));

    // file name packet
    memset(&pkt[4], PKT_TYPE_FLN, sizeof(packet));
    memcpy(pkt[4].data, mvFromName.c_str(), mvFromName.length()+1);
    pkt[4].data[mvFromName.length()] = '\0';
    pkt[4].sequence = 4;
    pkt[4].checksum = 0;
    pkt[4].checksum = in_cksum((unsigned short *)&pkt[4], sizeof(packet));
    
    // Send packets
    int sk; // new socket
    mvOldSocket = mvSocket;
    sockaddr_storage addr;
    for (int i = 0; i < 5 && mvRetries > 0; i++) {
        packet inpkt;
        int r;
        
        // Send packet
        if (sendtoErr(mvSocket, &pkt[i], sizeof(packet), 0, (sockaddr *)&mvAddr,
                      mvAddrLen) == -1) {
            std::cerr << "sendto (" << __LINE__ << "): " << strerror(errno)
                      << std::endl;
            return ERROR;
        }
        
        // Receive packet
        if ((r = recvPacket(inpkt)) == 1) {
            return ERROR;
        } else if (r == 2) {
            i--;
            continue;
        }
        mvRetries = PKT_TRNSMAX;
        
        // Check for RRs
        switch (inpkt.type) {
        case PKT_TYPE_RR:
            if (inpkt.sequence == i && pkt[i].type == PKT_TYPE_CXN) {
                mvRemotePort = inpkt.size; // Extract new port number
                if ((sk = GetSocket(*(sockaddr_in *)&addr)) == -1) {
                    std::cerr << "GetSocket (" << __LINE__ << "): "
                              << strerror(errno) << std::endl;
                    return ERROR;
                }
                mvAddrLen = sizeof(mvAddr);
            } else if (inpkt.sequence == i && pkt[i].type == PKT_TYPE_CXN2) {
                // Apply new port changes
                mvSocket = sk;
                mvAddr = addr;
            } else if (inpkt.sequence != i) {
                // Incorrect sequence number: resend packet
                i--;
                continue;
            }
            break;
        case PKT_TYPE_REJ:
            if (inpkt.sequence <= i) {
                i = inpkt.sequence - 1;
            }
            break;
        }
    }
    
    if (mvRetries <= 0) {
        return ERROR;
    }
    
    mvSequence = 0;
    mvRetries = PKT_TRNSMAX;
    
    return RECV_PACKETS;
}
int main(int argc, char *argv[])
{

    int ret_status;
    int i, res;
    char local_ip[IP4_MAX_LEN], remote_ip[IP4_MAX_LEN];
    uint16_t local_port = PORT_NUM, remote_port;
    uint16_t send_port, recv_port, fax_rem_port;
    uint32_t fax_rem_ip;
    char buffer[512];
    char tiff_filename[64], recv_filename[64];
    int buflen;
    int len;
    int ses_count = 0;
    int sock;
    char call_id_str[FAX_MAX_SESSION_CNT];
    sig_message_t *msg_req = NULL;
    sig_message_t *msg_resp = NULL;
    fax_session_t *f_session[FAX_MAX_SESSION_CNT][2];
    pthread_t      f_thread[FAX_MAX_SESSION_CNT][2];
    struct stat st;

    if (argc < 5) {
        printf("Not enough arguments: [REMOTE_HOST] [REMOTE_PORT] [SESSION_COUNT] [TIFF_FILE_TO_SEND]\n");
        ret_status = EXIT_FAILURE;
        goto _exit;
    }

    ses_count = strtoul(argv[3], NULL, 10);

    if (ses_count > FAX_MAX_SESSION_CNT) {
        printf("Too many sessions! No more then %d supported\n", FAX_MAX_SESSION_CNT);
        ret_status = EXIT_FAILURE;
        goto _exit;
    }

    strncpy(tiff_filename, argv[4], sizeof(tiff_filename));
    if (stat(tiff_filename, &st)) {
        printf("Tiff file error ('%s'): %s\n", tiff_filename, strerror(errno));
        ret_status = EXIT_FAILURE;
        goto _exit;
    }

    strcpy(local_ip, getLocalIP("eth0"));

    printf("Local IP is '%s:%d'\n", local_ip, local_port);

    if ((sock = socket_init(local_ip, local_port)) < 0) {
        ret_status = EXIT_FAILURE;
        goto _exit;
    }

    if ((res = getHostAddr(argv[1], argv[2], &remote_addr))) {
        printf("getaddrinfo() error: %s\n", gai_strerror(res));
        ret_status = EXIT_FAILURE;
        goto _exit;
    }


    strcpy(remote_ip, inet_ntoa(remote_addr.sin_addr));
    remote_port = ntohs(remote_addr.sin_port);

    printf("Remote IP is '%s:%d'\n", remote_ip, remote_port);

    for(i = 0; i < ses_count; i++)
    {
        sprintf(call_id_str, "0000000%d", i + 1);

        send_port = FAX_SEND_PORT_START + i;
        recv_port = FAX_RECV_PORT_START + i;

        f_session[i][0] = f_session[i][1] = NULL;

        sig_msgCreateSetup(call_id_str,
                           ntohl(inet_addr(local_ip)), send_port,
                           ntohl(inet_addr(local_ip)), recv_port,
                           FAX_MODE_GW_GW, (sig_message_setup_t **)(&msg_req));


        sig_msgCompose(msg_req, buffer, sizeof(buffer));

        buflen = strlen(buffer);
        printf("buffer_len: %d buffer: '%.*s'", buflen, buflen, buffer);

        if ((len = sendPacket((uint8_t *)buffer, buflen)) != -1) {
            printf("Data sent to %s:%d: len=%d buf='%s'\n",
                   inet_ntoa(remote_addr.sin_addr), ntohs(remote_addr.sin_port),
                   buflen, buffer);
        } else {
            perror("sendPacket() failed");
            ret_status = EXIT_FAILURE;
            goto _exit;
        }

        if ((len = recvPacket((uint8_t *)buffer, sizeof(buffer))) != -1) {
            printf("Data received form %s:%d len=%d buf='%s'\n",
                   inet_ntoa(remote_addr.sin_addr), ntohs(remote_addr.sin_port),
                   len, buffer);
        } else {
            perror("recvfrom() failed");
            ret_status = EXIT_FAILURE;
        }

        sig_msgParse(buffer, &msg_resp);
        sig_msgPrint(msg_resp, buffer, sizeof(buffer));

        printf("MSG Response: %s\n", buffer);

        fax_rem_ip = ((sig_message_ok_t *)msg_resp)->ip;
        fax_rem_port = ((sig_message_ok_t *)msg_resp)->port;

        /* Sending thread */
        f_thread[i][0] = start_fax_session(SEND, call_id_str, send_port,
                                           fax_rem_ip, fax_rem_port,
                                           tiff_filename,
                                           &(f_session[i][0]));

        /* If we do without fork() - received filed will be distorted,
         * don't know why.
         *
         * Most of all - spandsp bug, not sure
         */
        if(!fork())
        {
            if(msg_resp->type != FAX_MSG_OK) exit(1);


            sprintf(recv_filename, "received_fax_%02d.tif", i);

            /* Receiving thread */
            f_thread[i][1] = start_fax_session(RECV, call_id_str, recv_port, 0,
                                               0, recv_filename,
                                               &f_session[i][0]);

            pthread_join(f_thread[i][1], NULL);
            if(f_session[i][1]) free(f_session[i][1]);

            exit(0);
        }

        sig_msgDestroy(msg_req);
        sig_msgDestroy(msg_resp);

        msg_req = NULL;
        msg_resp = NULL;
    }

    for(i = 0; i < ses_count; i++)
    {
        pthread_join(f_thread[i][0], NULL);
    }

    for(i = 0; i < ses_count; i++)
    {
        if(f_session[i][0]) free(f_session[i][0]);
    }

_exit:
    if (sock > -1) {
        shutdown(sock, SHUT_RDWR);
        close(sock);
    }

    return ret_status;
}
void CALLBACK CSocketTcpServer::CompleteRoutine(DWORD dwError,
        DWORD dwTrans,
        LPWSAOVERLAPPED Overlppad,
        DWORD dwFlags)
{
    int nIndex = 0;
    for(; nIndex<g_scoketTcpServer->m_index; nIndex++)
    {
        if(&g_scoketTcpServer->m_ol[nIndex]->ol == Overlppad)
        {
            break;
        }
    }
    CString ipAddress;
    g_scoketTcpServer->m_convert.CharToCstring(ipAddress,
            inet_ntoa(g_scoketTcpServer->m_ol[nIndex]->addr.sin_addr));
    CString errCode;
    if(0 != dwError || 0 == dwTrans)
    {
#ifdef _DEBUG
        errCode.Format(_T("Client: <%s : %d> leave...."),
                       ipAddress,
                       ntohs(g_scoketTcpServer->m_ol[nIndex]->addr.sin_port));
        MyWriteConsole(errCode);
#endif
        closesocket(g_scoketTcpServer->m_ol[nIndex]->sock);
#ifdef _DEBUG
        errCode.Format(_T("%d nIndex from array"),nIndex);
        MyWriteConsole(errCode);
#endif
        delete g_scoketTcpServer->m_ol[nIndex];
        // Error or closesocket by peer
        for(int i=nIndex; i<g_scoketTcpServer->m_index-1; i++)
        {
            g_scoketTcpServer->m_ol[i] = g_scoketTcpServer->m_ol[i+1];
        }
        g_scoketTcpServer->m_index--;
    }
    else
    {
        switch(g_scoketTcpServer->m_ol[nIndex]->nOpType)
        {
        case OP_READ:
        {
#ifdef _DEBUG
            CString msg;
            g_scoketTcpServer->m_convert.CharToCstring(msg,
                    g_scoketTcpServer->m_ol[nIndex]->szBuf);
            errCode.Format(_T("recv <%s : %d> data: %s"),
                           ipAddress,
                           ntohs(g_scoketTcpServer->m_ol[nIndex]->addr.sin_port),
                           msg);
            MyWriteConsole(errCode);
#endif
            g_scoketTcpServer->m_ol[nIndex]->nOpType = OP_WRITE;
            memset(&(g_scoketTcpServer->m_ol[nIndex]->ol), 0,
                   sizeof(g_scoketTcpServer->m_ol[nIndex]->ol));
            //////////把接收到的报文拷贝到string
            std::string recvPacket(g_scoketTcpServer->m_ol[nIndex]->szBuf);
            ///判断报文
            CProducePacket producePacket;
            int iErrCode = producePacket.JudgeSendPacket(recvPacket);
            switch(iErrCode)
            {
            case 1:
            case 26:
            case 27:
            case 28:
            case 32:
            case 33:
            case 34:
            case 35:
                g_scoketTcpServer->m_pDealData->AddPacket(recvPacket);
                break;
            }
            //返回报文
            std::string retPacket;
            retPacket = producePacket.ProduceSendRet(iErrCode,recvPacket);
            int size = retPacket.size();
            strncpy_s(g_scoketTcpServer->m_ol[nIndex]->szBuf,MAX_BUFFER,retPacket.c_str(),MAX_BUFFER-1);
            g_scoketTcpServer->m_ol[nIndex]->wsaBuf.buf = g_scoketTcpServer->m_ol[nIndex]->szBuf;
            g_scoketTcpServer->m_ol[nIndex]->wsaBuf.len=MAX_BUFFER;

            if(SOCKET_ERROR  == WSASend(g_scoketTcpServer->m_ol[nIndex]->sock,
                                        &(g_scoketTcpServer->m_ol[nIndex]->wsaBuf), 1,
                                        &(g_scoketTcpServer->m_ol[nIndex]->dwTrans),
                                        g_scoketTcpServer->m_ol[nIndex]->dwFlags,
                                        &(g_scoketTcpServer->m_ol[nIndex]->ol),
                                        CompleteRoutine))
            {
                if(WSA_IO_PENDING != WSAGetLastError())
                {
#ifdef _DEBUG
                    errCode.Format(_T("WSASend failed with error code: %d"),
                                   WSAGetLastError());
                    MyWriteConsole(errCode);
#endif
                    closesocket(g_scoketTcpServer->m_ol[nIndex]->sock);
                    // Error or closesocket by peer
                    for(int i=nIndex; i<g_scoketTcpServer->m_index-1; i++)
                    {
                        g_scoketTcpServer->m_ol[i] = g_scoketTcpServer->m_ol[i+1];
                    }
                    g_scoketTcpServer->m_index--;
                }
            }
        }
        break;
        case OP_WRITE:
        {
            g_scoketTcpServer->m_ol[nIndex]->nOpType = OP_READ;
            dwFlags = 0;
            memset(&(g_scoketTcpServer->m_ol[nIndex]->ol), 0,
                   sizeof(g_scoketTcpServer->m_ol[nIndex]->ol));
            memset(g_scoketTcpServer->m_ol[nIndex]->szBuf, 0,
                   sizeof(g_scoketTcpServer->m_ol[nIndex]->szBuf));
            g_scoketTcpServer->m_ol[nIndex]->wsaBuf.buf =
                g_scoketTcpServer->m_ol[nIndex]->szBuf;
            dwTrans = g_scoketTcpServer->m_ol[nIndex]->wsaBuf.len = MAX_BUFFER;
            if(SOCKET_ERROR == WSARecv(g_scoketTcpServer->m_ol[nIndex]->sock,
                                       &(g_scoketTcpServer->m_ol[nIndex]->wsaBuf), 1,
                                       &dwTrans, &dwFlags,
                                       &(g_scoketTcpServer->m_ol[nIndex]->ol),
                                       CompleteRoutine))
            {
                if(WSA_IO_PENDING != WSAGetLastError())
                {
#ifdef _DEBUG
                    errCode.Format(_T("WSARecv failed with error code: %d"),
                                   WSAGetLastError());
                    MyWriteConsole(errCode);
#endif
                    closesocket(g_scoketTcpServer->m_ol[nIndex]->sock);
                    // Error or closesocket by peer
                    for(int i=nIndex; i<g_scoketTcpServer->m_index-1; i++)
                    {
                        g_scoketTcpServer->m_ol[i] = g_scoketTcpServer->m_ol[i+1];
                    }
                    g_scoketTcpServer->m_index--;
                }
            }
        }
        break;
        }
    }
}