Ejemplo n.º 1
0
void connectionHandleRfcommEstablishCfm(const RFC_ESTABLISH_CFM_T* cfm)
{
    /* Get the connection instance data keyed by server channel and mux id */
    conn_instance *conn = getRfcommConnection(NULL, cfm->mux_id, cfm->server_chan);

    if(conn)
    {
        if(cfm->result_code == RFC_SUCCESS)
        {
            /* Move to the modem status phase */
            conn->config.rfcomm.state = modem_status_phase;

            /* 
				Send modem status signal, data cannot be exchanged until both
				sides have exchanged modem status signals 
			*/
            startControlPhase(conn);
        }
        else if (cfm->result_code == DLC_ALREADY_EXISTS)
        {
            /* Send a cfm to the app indicating an error has ocurred*/
            sendRfcommConnectionCfm(conn->config.rfcomm.app_task, rfcomm_connect_channel_already_open, INVALID_SERVER_CHANNEL, 0, 0);

            /* Cancel the connect timeout and clean up the connection state data. */
            (void) MessageCancelFirst(connectionGetCmTask(), CL_INTERNAL_RFCOMM_CONNECT_TIMEOUT_IND);
            (void) deleteRfcommConnection(NULL, cfm->mux_id, cfm->server_chan);
        }
        else if (cfm->result_code == REMOTE_REFUSAL)
        {
            /* Connection establishment failed, clean up */
            endConnection(conn);

			/* Inform the app of the failure */
            sendRfcommConnectionCfm(conn->config.rfcomm.app_task, rfcomm_connect_rejected, INVALID_SERVER_CHANNEL, 0, 0);

			/* Cancel the connect timeout and clean up the connection state data. */
            (void) MessageCancelFirst(connectionGetCmTask(), CL_INTERNAL_RFCOMM_CONNECT_TIMEOUT_IND);
            (void) deleteRfcommConnection(NULL, cfm->mux_id, cfm->server_chan);
        }
        else
        {
			/* Connection establishment failed, clean up */
            endConnection(conn);

			/* Inform the app of the failure */
            sendRfcommConnectionCfm(conn->config.rfcomm.app_task, rfcomm_connect_failed, INVALID_SERVER_CHANNEL, 0, 0);

			/* Cancel the connect timeout and clean up the connection state data. */
            (void) MessageCancelFirst(connectionGetCmTask(), CL_INTERNAL_RFCOMM_CONNECT_TIMEOUT_IND);
            (void) deleteRfcommConnection(NULL, cfm->mux_id, cfm->server_chan);
        }
    }
	/* 
		This could happen if the connect timeout has triggered and cleaned up the connection 
		state entry and then we get an RFC_ESTABLISH_CFM indicating the remote end failed to 
		respond. We should just ignore this cfm. 
	*/
}
Ejemplo n.º 2
0
void TCPServerDispatcher::run()
{
	AutoPtr<TCPServerDispatcher> guard(this, true); // ensure object stays alive

	int idleTime = (int) _pParams->getThreadIdleTime().totalMilliseconds();

	for (;;)
	{
		AutoPtr<Notification> pNf = _queue.waitDequeueNotification(idleTime);
		if (pNf)
		{
			TCPConnectionNotification* pCNf = dynamic_cast<TCPConnectionNotification*>(pNf.get());
			if (pCNf)
			{
				std::unique_ptr<TCPServerConnection> pConnection(_pConnectionFactory->createConnection(pCNf->socket()));
				poco_check_ptr(pConnection.get());
				beginConnection();
				pConnection->start();
				endConnection();
			}
		}
	
		FastMutex::ScopedLock lock(_mutex);
		if (_stopped || (_currentThreads > 1 && _queue.empty()))
		{
			--_currentThreads;
			break;
		}
	}
}
Ejemplo n.º 3
0
void connectionHandleRfcommConnectTimeout(connectionRfcommState *rfcommState, const CL_INTERNAL_RFCOMM_CONNECT_TIMEOUT_IND_T *ind)
{
    /* 
        It's possible to have multiple connections being setup to different 
        devices, therefore first get the connection instance that this 
        message refers.  The mux id will always be invalid at this point
        as it was not known when the message was first posted, therefore we
        search for the connection instance keyed on Bluetooth Device Address
        and server channel 
    */
    conn_instance *conn = getRfcommConnection(&ind->bd_addr, INVALID_MUX_ID, ind->server_channel);

    if(conn)
    {
        /* Depending upon the current state, abort the connection attempt */
        endConnection(conn);

        /* Inform the client application the connection attempt has timed out */
        sendRfcommConnectionCfm(ind->theAppTask, rfcomm_connect_timeout, INVALID_SERVER_CHANNEL, 0, 0);

        /* Remove the connection data entry as its no longer needed */
        (void) deleteRfcommConnection(&ind->bd_addr, INVALID_MUX_ID, ind->server_channel);

        /* Unlock */
        rfcommState->lock = 0;
    }
    else
    {
        /* 
			This should never happen (if we delete the conn data the timeout should 
			be cancelled) so panic.
		*/
        Panic();
    } 
}
Ejemplo n.º 4
0
int qSslChat::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QWidget::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: peerRejectedFileSend(); break;
        case 1: fsCompleted(); break;
        case 2: hostConnection(); break;
        case 3: connectToHost(); break;
        case 4: activateMsgSending(); break;
        case 5: sendMsg((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 6: receiveMessage((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 7: displayMsg(); break;
        case 8: endConnection(); break;
        case 9: sendAnticipation(); break;
        case 10: sendFile((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3]))); break;
        case 11: notifyServer(); break;
        case 12: completeFileSend(); break;
        case 13: selectSmiley(); break;
        case 14: insertSmiley((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break;
        case 15: displayCertificateInfo(); break;
        }
        _id -= 16;
    }
    return _id;
}
Ejemplo n.º 5
0
/**
 * Set up the client tcp socket for an incoming connection
 */
void TCPServer::newConnection()
{
    client = server.nextPendingConnection();
    connect(client, SIGNAL(disconnected()), this, SLOT(endConnection()), Qt::QueuedConnection);
    connect(client, SIGNAL(readyRead()), this, SLOT(clientReadString()), Qt::QueuedConnection);

    emit connectionReady();
}
Ejemplo n.º 6
0
void LCDServer::newConnection(QTcpSocket *socket)
{
    connect(socket, SIGNAL(readyRead()),
            this,   SLOT(  readSocket()));
    connect(socket, SIGNAL(disconnected()),
            this,   SLOT(  endConnection()));

    if (debug_level > 0)
        LOG(VB_NETWORK, LOG_INFO, "LCDServer: new connection");

    if (m_lcd)
        m_lcd->switchToTime();
}
Ejemplo n.º 7
0
qSslChat :: qSslChat()
{
  setupUi(this);
  messageList -> setDisabled(true);
  messageList -> setAcceptDrops(true);
  msgEdit -> setDisabled(true);
  sendButton -> setDisabled(true);
  smileyButton -> setDisabled(true);
  cinfoButton -> setDisabled(true);
  portBox -> setRange(1024,65535);
  portBox -> setValue(7752);
  setWindowTitle("Buddies SSL Chat");
  setWindowIcon(QIcon(":/icons/Logo.png"));
  mode=0;
  server=0;

  cinfoButton -> setIcon(QIcon(":/icons/encrypted.png"));
  cinfoButton -> setIconSize(QSize(20,20));
  cinfoButton -> setToolTip(tr("Display certificate info"));

  connect(cinfoButton,SIGNAL(clicked()),this,SLOT(displayCertificateInfo()));

  smileyButton -> setIcon(QIcon(":/emoticons/01.gif"));
  smileyButton -> setIconSize(QSize(20,20));
  connect(smileyButton,SIGNAL(clicked()),this,SLOT(selectSmiley()));
  emoSelector = new EmoticonSelector(this);
  emoSelector -> hide();
  emoSelector -> alignTo(smileyButton);
  connect(emoSelector,SIGNAL(smileySelected(QString,QString)),this,SLOT(insertSmiley(QString,QString)));

  tableFormat.setBorder(0);
  //systray = new systemTray(this);
  addAnimations();

  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF8"));
  QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF8"));

  connect(hostButton,SIGNAL(clicked()),this,SLOT(hostConnection()));
  connect(connectButton,SIGNAL(clicked()),this,SLOT(connectToHost()));
  connect(disconnectButton,SIGNAL(clicked()),this,SLOT(endConnection()));
  connect(messageList,SIGNAL(fileSendInitiated(QString,int,int)),this,SLOT(sendFile(QString,int,int)));

}
Ejemplo n.º 8
0
Archivo: clstub.c Proyecto: Lelv/SO-TP1
static
int
send_rcv(int opcode, int size)
{
	//COMENTDEBUG
	//printf("sending rcv\n");
	int s = requestConnection(&c);
	int qtyrec, qtysent;
	p.opc = opcode;
	qtysent = sendPacket(&c, &p, size + sizeof(opcode));
	qtyrec = receivePacket(&c, &p, sizeof(PACKET));
	endConnection(&c);
	int ret_opcode = p.opc;
	if(ret_opcode = RET_CURAR) {
		//COMENTDEBUG
		//printf("pokemones curados\n");
		
	}

	return qtyrec - sizeof ( OPC );
}
int TCPReceiver::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: stringRead((*reinterpret_cast< QByteArray(*)>(_a[1]))); break;
        case 1: connectionError((*reinterpret_cast< QString(*)>(_a[1]))); break;
        case 2: connectionReady(); break;
        case 3: connectionNotReady(); break;
        case 4: newConnection(); break;
        case 5: endConnection(); break;
        case 6: clientWriteString((*reinterpret_cast< QByteArray(*)>(_a[1]))); break;
        case 7: { QByteArray _r = clientReadString();
            if (_a[0]) *reinterpret_cast< QByteArray*>(_a[0]) = _r; }  break;
        case 8: stop(); break;
        default: ;
        }
        _id -= 9;
    }
    return _id;
}
Ejemplo n.º 10
0
void connectionHandleRfcommConnectRes(const CL_INTERNAL_RFCOMM_CONNECT_RES_T* res)
{
    map_id id;
    id.channel = res->server_channel;

    if (!connectionFindTaskMap(conn_rfcomm, id))
    {
        /* 
            The local server channel has not been registered, end
            the connection attempt and let the client know 
        */
        sendRfcommConnectionCfm(res->theAppTask, rfcomm_server_channel_not_registered, INVALID_SERVER_CHANNEL, 0, 0);
    }
    else
    {
        /* Determine the connection instance keyed by Mux Id */
        conn_instance *conn = getRfcommConnection(&res->bd_addr, INVALID_MUX_ID, res->server_channel);

        if(conn)
        {
            /* Update connection instance */
            conn->config.rfcomm.params = res->config;

            /* 
                Decide whether the proposed params are acceptable and if so
                accept the connection otherwise reject it, setting the dlc
                params to ones you want 
            */
            if(res->response)
            {
                if (conn->config.rfcomm.state == establish_phase)
                {
                    sendEstablishRes(conn->id.rfcomm_id.mux_id, conn->id.rfcomm_id.server_channel, 1);

                    /* Move to the modem status phase */
                    conn->config.rfcomm.state = modem_status_phase;

                    /* 
                        Send modem status signal, data cannot be exchanged until both
                        sides have exchanged modem status signals 
                    */
                    startControlPhase(conn);
                }   
                else
                {
                    MAKE_PRIM_T(RFC_PARNEG_RES);
                    prim->server_chan = conn->id.rfcomm_id.server_channel;
                    prim->mux_id = conn->id.rfcomm_id.mux_id;

                    /* set the frame size */
                    if (res->config.max_frame_size <= conn->config.rfcomm.maxMtu)
                    {   
                        prim->dlc_pars.max_frame_size = res->config.max_frame_size;
                        conn->config.rfcomm.maxMtu = res->config.max_frame_size;
                    }
                    else
                    {
                        prim->dlc_pars.max_frame_size = conn->config.rfcomm.maxMtu;
                    }                

                    /* set the flow control type */
                    if (conn->config.rfcomm.credit_flow_ctrl)
                        prim->dlc_pars.credit_flow_ctrl = 1;
                    else
                        prim->dlc_pars.credit_flow_ctrl = 0;

                    prim->dlc_pars.initial_credits = 0;

                    VmSendRfcommPrim(prim); 
                }
            }
            else
            {
                if (conn->config.rfcomm.state == establish_phase)
                {
                    sendEstablishRes(conn->id.rfcomm_id.mux_id, conn->id.rfcomm_id.server_channel, 0);
                }
                else
                {
                    conn->config.rfcomm.state = disconnected;

                    /* Client application has rejected connection request */
                    endConnection(conn);
                }
            }
        }
        else
        {
            /* This should never happen */
            Panic();
        }
    }
}
Ejemplo n.º 11
0
/**
 * Stop the server and the connections
 */
void TCPServer::stop()
{
    server.close();
    endConnection();
}
Ejemplo n.º 12
0
Archivo: clstub.c Proyecto: Lelv/SO-TP1
void killClient(int sig) {
	endConnection(&c);
	printf("\nWe hope to see you again!\n");	
	exit(1);
}
Ejemplo n.º 13
0
Network::~Network()
{
  endConnection();
}
Ejemplo n.º 14
0
      t_int httpTransport::read(dBuffer & _buffer, t_int & _connectionID)
      {

#if BTG_TRANSPORT_DEBUG
         BTG_NOTICE("httpTransport::read");
#endif // BTG_TRANSPORT_DEBUG
         t_int status = httpTransport::OPERATION_FAILED;

         _buffer.erase();
         _connectionID = NO_CONNECTION_ID;

         /// Select on all sockets in the group.
         socketGroup.doSelect();

         if (socketGroup.size() == 0)
            {
               // No sockets with data, most likely timeout
               return status;
            }

         switch (this->direction)
            {
            case TO_SERVER:
               {
#if BTG_TRANSPORT_DEBUG
                  BTG_NOTICE("httpTransport::read, TO_SERVER");
#endif // BTG_TRANSPORT_DEBUG
                  // We only have one socket in the socketGroup so no
                  // need to determine which socket it was...

                  // The above comment works for tcp/ip sockets, but
                  // not in this class. Added checks.
                  
                  btg::core::os::Socket* socket = 0;

                  if (!socketGroup.getNext(socket))
                     {
                        return status;
                     }

                  if (client != socket)
                     {
                        return status;
                     }

                  t_int rsize = client->read(sndrec_buffer, buffer_size);
                  if (rsize > 0)
                     {
#if BTG_TRANSPORT_DEBUG
                        BTG_NOTICE("httpTransport::read(), TO_SERVER, read " <<
                                   rsize << " bytes from server");
#endif // BTG_TRANSPORT_DEBUG
                        status = rsize;
                        clientRequest->addBytes(sndrec_buffer, rsize);
                     }

                  if (clientRequest->peek())
                     {
#if BTG_TRANSPORT_DEBUG
                        BTG_NOTICE("httpTransport::read(), TO_SERVER, got a full request.");
#endif // BTG_TRANSPORT_DEBUG
                        status = clientRequest->getContent(_buffer);
                        clientRequest->reset();
                        if ((status == 0) && (clientRequest->abort()))
                           {
                              BTG_NOTICE("httpTransport::read(), TO_SERVER, failed to retreive request! Bad gzip?");
                              // Probably broken gzip compression,
                              // shutdown.
                              client->shutdown();
                           }
                     }

                  break;
               }
            case FROM_SERVER:
               {
#if BTG_TRANSPORT_DEBUG
                  BTG_NOTICE("httpTransport::read, FROM_SERVER");
#endif // BTG_TRANSPORT_DEBUG

                  // Read from all clients.

                  btg::core::os::Socket* socket = 0;

                  while (socketGroup.getNext(socket))
                     {
                        if (socket == server)
                           {
                              // A new connection is here
                              this->acceptNewConnections();
                              continue;
                           }

                        // Got data on a socket
                        httpClient* client = dynamic_cast<httpClient*>( resolve( socket ) );
                        if (client->socket->deleted())
                           {
#if BTG_TRANSPORT_DEBUG
                              BTG_NOTICE("httpTransport::read: deleting dead client " << client);
#endif // BTG_TRANSPORT_DEBUG
                              // Terminate the conneciotn
                              endConnection(client->connectionID);

                              // Client is gone now!!
                              client = 0;

                              // Next socket...
                              continue;
                           }

                        t_int rsize = client->socket->read(sndrec_buffer, buffer_size);
                        if (rsize > 0)
                           {
#if BTG_TRANSPORT_DEBUG
                              BTG_NOTICE("httpTransport::read(), FROM_SERVER, read " << rsize << " bytes from client "<< client);
#endif // BTG_TRANSPORT_DEBUG
                              client->httpRequest.addBytes(sndrec_buffer, rsize);
                              if (client->httpRequest.abort())
                                 {
                                    BTG_NOTICE("httpRequest::read(), Fatal error from client " << client); // << ": " << buff);
                                    // A fatal error occured.

                                    std::stringstream ss;
                                    ss << "HTTP/1.0 400 Bad Request\r\n";
                                    ss << "Server: btg-" << GPD->sBUILD() << "\r\n";
                                    ss << "Date: " << createTimestamp() << "\r\n";
                                    ss << "Connection: close\r\n";
                                    ss << "\r\n";

                                    client->socket->write(reinterpret_cast<t_byteCP>(ss.str().c_str()), ss.str().length());
#if BTG_TRANSPORT_DEBUG
                                    BTG_NOTICE("httpTransport::read(), shutting down socket "<< client->socket->getSockId());
#endif // BTG_TRANSPORT_DEBUG
                                    client->socket->shutdown();
                                 }

                              if (client->httpRequest.peek())
                                 {
                                    rsize = client->httpRequest.getContent(_buffer);
                                    if (rsize > 0)
                                       {
                                          status = rsize;
                                          _connectionID = client->connectionID;
                                          break;
                                       }
                                    else if (client->httpRequest.abort())
                                       {
#if BTG_TRANSPORT_DEBUG
                                          BTG_NOTICE("httpTransport::read(), shutting down socket " <<
                                                     client->socket->getSockId());
#endif // BTG_TRANSPORT_DEBUG
                                          // Probably broken gzip
                                          // compression, shutdown.
                                          client->socket->shutdown();
                                       }
                                 }
                           }
                     } // while can read a socket.

                  break;
               }
            }
         return status;
      }
Ejemplo n.º 15
0
Archivo: server.c Proyecto: Vuzi/SFSS
/* Programme principal serveur */
void startServer(void) {

    /* Socket du serveur */
    SOCKET sock = startConnection(); /* Fonction de lancement du serveur, ici le serveur passe en écoute */
    int max = sock;

    /* Liste des différents comptes */
    Account *accounts = NULL;

    User *users = NULL;
    User *u_cursor = NULL, *tmp = NULL;

    /* Descripteur */
    fd_set rdfs;

    bool quit = false;


    /* A ajouter : commande permettant de quitter §§§ */
    while(!quit) {

        /* On vide le descripteur */
		FD_ZERO(&rdfs);

		/* On ajoute le socket du serveur */
		FD_SET((u_int)sock, &rdfs);

        u_cursor = getFirstUser(users);

        /* On ajoute le socket de chaque User */
        while(u_cursor) {
            FD_SET((u_int)(u_cursor->sock), &rdfs);
            u_cursor = u_cursor->next;
        }

		/* On effectue le select pour lier le descripteur à la lecture sur le socket */
		if(select(max+1, &rdfs, NULL, NULL, NULL) == SOCKET_ERROR) {
            sock_error("select()");
		} else {
			/* Ici on attends un changement d'un des descripteurs */

			/* Si c'est un nouveau client qui effectue une connexion */
			if(FD_ISSET(sock, &rdfs)) {

				HERROR_WRITE(HERROR_DEBUG, "[Serveur] Nouveau client detecte");

				/* Variables du nouveau client */
				SOCKADDR_IN csin;
				size_t sinsize = sizeof csin;

				/* Socket du nouveau client */
				int csock = accept(sock, (SOCKADDR *)&csin, (socklen_t *)&sinsize);

				/* Si erreur */
				if(csock == SOCKET_ERROR)
                    sock_error("accept()");

				/* On ajoute le client en attente de connexion */
				users = addUser(users, (SOCKET)csock, copy(inet_ntoa(csin.sin_addr)));

				/* Nouveau max : */
				max = csock > max ? csock : max;

				HERROR_WRITE(HERROR_INFO, "[Serveur] Nouveau client ajoute ( ip '%s')", users->ip);
			}
			/* Sinon c'est un client qui effectue une action */
			else {
                u_cursor = getFirstUser(users);

				/* Pour chaque Uset */
                while(u_cursor) {
                    /* S'il a envoyé des données */
                    if(FD_ISSET(u_cursor->sock, &rdfs)){

                        if(u_cursor->state == WAITING_MSG || u_cursor->state == WAITING_END_MSG) {
                            if(u_cursor->acc) {
                                HERROR_WRITE(HERROR_INFO, "[Serveur] Message client (ip '%s' | login '%s')", u_cursor->ip, u_cursor->acc->login);
                            } else {
                                HERROR_WRITE(HERROR_INFO, "[Serveur] Message client (ip '%s' | login '--')", u_cursor->ip);
                            }
                        }

                        /* Ici, fonction qui lit la réception du message */
                        if(rcvMsgFromUser(u_cursor, &accounts) == 0) {
                            /* si == 0, client déconnecté */
                            if(u_cursor->acc) {
                                HERROR_WRITE(HERROR_INFO, "[Serveur] Deconnexion client (ip '%s' | login '%s')", u_cursor->ip, u_cursor->acc->login);
                            } else {
                                HERROR_WRITE(HERROR_INFO, "[Serveur] Deconnexion client (ip '%s' | login '--')", u_cursor->ip);
                            }
                            /* On ferme la connexion */
                            closesocket(u_cursor->sock);

                            /* On l'enleve des Users */
                            tmp = u_cursor->next;
                            removeUserAndAccount(&u_cursor, &accounts);
                            users = u_cursor;
                            u_cursor = tmp;
                        } else
                            u_cursor = u_cursor->next;
                    } else
                        u_cursor = u_cursor->next;
                }
			}

		}
	}

	endConnection();

	deleteUser(users);
	deleteAccount(accounts);
}