Ejemplo n.º 1
0
SessionData* SessionManager::getSession( const Falcon::String& sSID, uint32 token )
{
   SessionData* sd = 0;
   bool bCreated;
   
   // Should we start a new thread for this?
   if( timeout() > 0 )
      expireOldSessions();

   m_mtx.lock();
   SessionMap::iterator iter = m_smap.find( sSID );
   if( iter != m_smap.end() )
   {
      sd = iter->second;
      if ( sd == 0 || sd->isAssigned() )
      {
         m_mtx.unlock();
         return 0;
      }

      sd->assign( token );
      // We must manipulate m_susers in the lock to prevent concurrent update
      // from other threads.
      m_susers[token].push_back( sd->getWeakRef() );

      // now that the session is assigned, we are free to manipulate it outside the lock.
      m_mtx.unlock();

      bCreated = false;
   }
   else
   {
      // create the session (fast)
      sd = createSession( sSID );
      // assign to our maps
      m_smap[sSID] = sd;
      m_susers[token].push_back( sd->getWeakRef() );
      // assign the session
      sd->assign( token );

      // try to resume after unlock
      m_mtx.unlock();

      bCreated = true;
   }

   // can we resume this session?
   if( ! sd->resume() )
   {
      // all useless work.
      m_mtx.lock();
      m_smap.erase( sSID );
      sd->clearRefs();
      m_mtx.unlock();

      //If the session was created, we should have done it.
      if( ! bCreated )
      {
         sd->setInvalid();
      }
      else
      {
         delete sd;
         sd = 0;
      }
   }

   return sd;
}
void setUp(void){
  s1 = createSession();
  s2 = createSession();
}
Ejemplo n.º 3
0
// Fonction qu'execute les threads de gestion de client
void *gestionClient(void *argThread) {
  ArgThread *arg = (ArgThread *)argThread;
  int sock = arg->socket;
  Session *session = NULL;// = arg->session;
  ListeJoueurs *listeJ = NULL;//session->liste;
  pthread_t tmp;
  char *nomSession;
  int nbRead;
  char buf[TBUF];
  char *req;
  int cpt=0;
  int decoProprement = 0;
  Joueur *myJoueur = NULL; /* Joueur du thread courant */
  free(arg); 

  while((!decoProprement) && (cpt<TBUF) && (nbRead=read(sock, &buf[cpt++], 1)) > 0) {
    /* Lecture d'une ligne */
    if(buf[cpt-1] != '\n') 
      continue;
    buf[cpt-1] = '\0';
    cpt = 0;
  
    printf("[Receive] : %s\n", buf); 
    req = strtok(buf, "/");

    switch(hash_protocole(req)) {
    case 1: /* CONNEX */
      pthread_mutex_lock(&mutexAllSession); // Au cas ou une destruction en cours
      pthread_mutex_lock(&(sessionDeBase->mutex));
      session = sessionDeBase;
      listeJ = session->liste;
      myJoueur = connex(sock, listeJ); 
      if(myJoueur == NULL) {
        pthread_mutex_unlock(&(sessionDeBase->mutex));
	pthread_mutex_unlock(&mutexAllSession);  
	sprintf(buf, "Erreur/Pseudo deja present/\n");
	write(sock, buf, strlen(buf));
	break;
      }
      indiquerConnexion(session, myJoueur); // Aux autres joueurs de la session
      pthread_mutex_unlock(&(sessionDeBase->mutex));
      pthread_mutex_unlock(&mutexAllSession);      
      break;
    case 2: /* SORT */
      printf("[Deconnexion] '%s'\n", myJoueur->pseudo);
      sort(listeJ, myJoueur);
      decoProprement = 1;
      break;
    case 3: // SOLUTION // Reflexion ou resolution
      pthread_mutex_lock(&(session->mutex));       
      if(session->phase == REFLEXION) {
	pthread_mutex_unlock(&(session->mutex));
	trouve(session, myJoueur);
      }
      else if(session->phase == RESOLUTION) {
	pthread_mutex_unlock(&(session->mutex));
	resolution(session, myJoueur);
      }
      else {
	printf("WHAT not reflexion or resolution... bad client...\n"); // Client mal fait
      }
      break;
    case 4: // ENCHERE
      enchere(session, myJoueur);
      break;
    case 6: // CHAT
      chat(session, myJoueur);
      break;
    case 7: // CREERSESSION
      session = creerSession(arg->listeSession, myJoueur);
      if(session == NULL) {
	sprintf(buf, "Erreur/Session deja existante/\n");
	write(sock, buf, strlen(buf));
	break;
      }
      printf("[Creation Session] name = %s, mdp = %s\n", session->nomSession, session->mdp);
      pthread_create(&tmp, NULL, gestionSession, session); // On lance le thread de gestion
      session->thread = tmp; 
      listeJ = session->liste;
      myJoueur = connex(sock, listeJ); 
      indiquerConnexion(session, myJoueur); // Au cas ou une connexion entre temps
      break;
    case 8: // CONNEXIONPRIVEE
      nomSession = strtok(NULL, "/");
      char *mdp = strtok(NULL, "/");
      printf("[Connexion privee] nomSession = %s, mdp = %s\n", nomSession, mdp);
      pthread_mutex_lock(&mutexAllSession); //////////////////////////////
      session = getSession(arg->listeSession, nomSession);
      if(session == NULL) {
	pthread_mutex_unlock(&mutexAllSession); ////////////////////////////////
	sprintf(buf, "Erreur/Session inexistante/\n");
	write(sock, buf, strlen(buf));
        break;
      }
      if(strcmp(mdp, session->mdp)) {
	pthread_mutex_unlock(&mutexAllSession);
	sprintf(buf, "Erreur/Mauvais mot de passe/\n");
	write(sock, buf, strlen(buf));
	break;
      }
      pthread_mutex_lock(&(session->mutex)); ///////////////:
      listeJ = session->liste;
      myJoueur = connex(sock, listeJ); 
      if(myJoueur == NULL) {
	pthread_mutex_unlock(&(session->mutex));
	pthread_mutex_unlock(&mutexAllSession);
	sprintf(buf, "Erreur/Pseudo deja present/\n");
	write(sock, buf, strlen(buf));
        break;
      }
      indiquerConnexion(session, myJoueur);
      pthread_mutex_unlock(&(session->mutex));
      pthread_mutex_unlock(&mutexAllSession);
      break;
    default:
      printf("[Requete inconnue] '%s'\n", req);
      break;
    }
  }

  if(myJoueur == NULL || myJoueur->pseudo == NULL) {
    printf("Un truc est null WARNING !!!\n");
    return NULL;
  }
  
  if(!decoProprement) { /* Cas ou fermeture socket sans SORT */
    printf("[Deconnexion] '%s'\n", myJoueur->pseudo);
    sort(listeJ, myJoueur);
  }

  pthread_mutex_lock(&mutexAllSession);
  pthread_mutex_lock(&(session->mutex));
  if(session->liste->nbJoueur == 0) { // Dernier joueur de la session Faudrait un mutex global
    pthread_mutex_unlock(&(session->mutex));
    printf("[Dernier joueur] destruction de la session '%s'\n", session->nomSession);
    pthread_cancel(session->thread); // Annuler le thread de gestion de la session
    if(session != sessionDeBase)
      suppSessionListe(arg->listeSession, session); // Si pas la public, on la supprime de la liste des session privees

    // Si sessionDeBase on le reinitialise pour pas devoir attendre la fin du tour lors des prochaines connexions
    if(session == sessionDeBase) {  // Prendre le mutex de sessionDeBase ou je sais pas quoi 
      printf("[Re-init session public]\n");
      sessionDeBase = createSession("Session_1", "");
      pthread_create(&tmp, NULL, gestionSession, sessionDeBase);
      sessionDeBase->thread = tmp;
    }
  }
  else {
    pthread_mutex_unlock(&(session->mutex));
  }
  pthread_mutex_unlock(&mutexAllSession);

  printf("Quit\n");
  return NULL;
}
Ejemplo n.º 4
0
/**********************************************************************
*%FUNCTION: relayHandlePADS
*%ARGUMENTS:
* iface -- interface on which packet was received
* packet -- the PADS packet
*%RETURNS:
* Nothing
*%DESCRIPTION:
* Receives and processes a PADS packet.
***********************************************************************/
void
relayHandlePADS(PPPoEInterface const *iface,
                PPPoEPacket *packet,
                int size)
{
    PPPoETag tag;
    unsigned char *loc;
    int ifIndex;
    int acIndex;
    PPPoESession *ses = NULL;
    SessionHash *sh;

    /* Can a server legally be behind this interface? */
    if (!iface->acOK) {
        syslog(LOG_ERR,
               "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not permitted",
               packet->ethHdr.h_source[0],
               packet->ethHdr.h_source[1],
               packet->ethHdr.h_source[2],
               packet->ethHdr.h_source[3],
               packet->ethHdr.h_source[4],
               packet->ethHdr.h_source[5],
               iface->name);
        return;
    }

    acIndex = iface - Interfaces;

    /* Source address must be unicast */
    if (NOT_UNICAST(packet->ethHdr.h_source)) {
        syslog(LOG_ERR,
               "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s not from a unicast address",
               packet->ethHdr.h_source[0],
               packet->ethHdr.h_source[1],
               packet->ethHdr.h_source[2],
               packet->ethHdr.h_source[3],
               packet->ethHdr.h_source[4],
               packet->ethHdr.h_source[5],
               iface->name);
        return;
    }

    /* Destination address must be interface's MAC address */
    if (memcmp(packet->ethHdr.h_dest, iface->mac, ETH_ALEN)) {
        return;
    }

    /* Find relay tag */
    loc = findTag(packet, TAG_RELAY_SESSION_ID, &tag);
    if (!loc) {
        syslog(LOG_ERR,
               "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s does not have Relay-Session-Id tag",
               packet->ethHdr.h_source[0],
               packet->ethHdr.h_source[1],
               packet->ethHdr.h_source[2],
               packet->ethHdr.h_source[3],
               packet->ethHdr.h_source[4],
               packet->ethHdr.h_source[5],
               iface->name);
        return;
    }

    /* If it's the wrong length, ignore it */
    if (ntohs(tag.length) != MY_RELAY_TAG_LEN) {
        syslog(LOG_ERR,
               "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s does not have correct length Relay-Session-Id tag",
               packet->ethHdr.h_source[0],
               packet->ethHdr.h_source[1],
               packet->ethHdr.h_source[2],
               packet->ethHdr.h_source[3],
               packet->ethHdr.h_source[4],
               packet->ethHdr.h_source[5],
               iface->name);
        return;
    }

    /* Extract interface index */
    memcpy(&ifIndex, tag.payload, sizeof(ifIndex));

    if (ifIndex < 0 || ifIndex >= NumInterfaces ||
            !Interfaces[ifIndex].clientOK ||
            iface == &Interfaces[ifIndex]) {
        syslog(LOG_ERR,
               "PADS packet from %02x:%02x:%02x:%02x:%02x:%02x on interface %s has invalid interface in Relay-Session-Id tag",
               packet->ethHdr.h_source[0],
               packet->ethHdr.h_source[1],
               packet->ethHdr.h_source[2],
               packet->ethHdr.h_source[3],
               packet->ethHdr.h_source[4],
               packet->ethHdr.h_source[5],
               iface->name);
        return;
    }

    /* If session ID is zero, it's the AC respoding with an error.
       Just relay it; do not create a session */
    if (packet->session != htons(0)) {
        /* Check for existing session */
        sh = findSession(packet->ethHdr.h_source, packet->session);
        if (sh) ses = sh->ses;

        /* If already an existing session, assume it's a duplicate PADS.  Send
           the frame, but do not create a new session.  Is this the right
           thing to do?  Arguably, should send an error to the client and
           a PADT to the server, because this could happen due to a
           server crash and reboot. */

        if (!ses) {
            /* Create a new session */
            ses = createSession(iface, &Interfaces[ifIndex],
                                packet->ethHdr.h_source,
                                loc + TAG_HDR_SIZE + sizeof(ifIndex), packet->session);
            if (!ses) {
                /* Can't allocate session -- send error PADS to client and
                   PADT to server */
                PPPoETag hostUniq, *hu;
                if (findTag(packet, TAG_HOST_UNIQ, &hostUniq)) {
                    hu = &hostUniq;
                } else {
                    hu = NULL;
                }
                relaySendError(CODE_PADS, htons(0), &Interfaces[ifIndex],
                               loc + TAG_HDR_SIZE + sizeof(ifIndex),
                               hu, "RP-PPPoE: Relay: Unable to allocate session");
                relaySendError(CODE_PADT, packet->session, iface,
                               packet->ethHdr.h_source, NULL,
                               "RP-PPPoE: Relay: Unable to allocate session");
                return;
            }
        }
        /* Replace session number */
        packet->session = ses->sesNum;
    }

    /* Remove relay-ID tag */
    removeBytes(packet, loc, MY_RELAY_TAG_LEN + TAG_HDR_SIZE);
    size -= (MY_RELAY_TAG_LEN + TAG_HDR_SIZE);

    /* Set destination address to MAC address in relay ID */
    memcpy(packet->ethHdr.h_dest, tag.payload + sizeof(ifIndex), ETH_ALEN);

    /* Set source address to MAC address of interface */
    memcpy(packet->ethHdr.h_source, Interfaces[ifIndex].mac, ETH_ALEN);

    /* Send the PADS to the proper client */
    sendPacket(NULL, Interfaces[ifIndex].discoverySock, packet, size);
}
Ejemplo n.º 5
0
void AmSessionContainer::startSessionUAS(AmSipRequest& req)
{
  try {
      // Call-ID and From-Tag are unknown: it's a new session
      auto_ptr<AmSession> session;
      string app_name;

      session.reset(createSession(req,app_name));
      if(session.get() != 0){

	// update session's local tag (ID) if not already set
	session->setLocalTag();
	const string& local_tag = session->getLocalTag();
	// by default each session is in its own callgroup
	session->setCallgroup(local_tag);

	if (AmConfig::LogSessions) {
	  INFO("Starting UAS session %s\n",
	       local_tag.c_str());
	}

	switch(addSession(req.callid,req.from_tag,local_tag,
			  req.via_branch,session.get())) {

	case AmSessionContainer::Inserted:
	  // successful case
	  break;
	  
	case AmSessionContainer::ShutDown:
	  throw AmSession::Exception(AmConfig::ShutdownModeErrCode,
				     AmConfig::ShutdownModeErrReason);
	  
	case AmSessionContainer::AlreadyExist:
	  throw AmSession::Exception(482,
				     SIP_REPLY_LOOP_DETECTED);
	  
	default:
	  ERROR("adding session to session container\n");
	  throw string(SIP_REPLY_SERVER_INTERNAL_ERROR);
	}

	MONITORING_LOG4(local_tag.c_str(), 
			"dir", "in",
			"from", req.from.c_str(),
			"to", req.to.c_str(),
			"ruri", req.r_uri.c_str());

	try {
	  session->start();
	} catch (...) {
	  AmEventDispatcher::instance()->
	    delEventQueue(local_tag);
	  throw;
	}

	session->postEvent(new AmSipRequestEvent(req));
	session.release();
      }
  } 
  catch(const AmSession::Exception& e){
    ERROR("%i %s %s\n",e.code,e.reason.c_str(), e.hdrs.c_str());
    AmSipDialog::reply_error(req,e.code,e.reason, e.hdrs);
  }
  catch(const string& err){
    ERROR("startSession: %s\n",err.c_str());
    AmSipDialog::reply_error(req,500,err);
  }
  catch(...){
    ERROR("unexpected exception\n");
    AmSipDialog::reply_error(req,500,"unexpected exception");
  }
}
Ejemplo n.º 6
0
string AmSessionContainer::startSessionUAC(const AmSipRequest& req, string& app_name, AmArg* session_params) {

  auto_ptr<AmSession> session;
  try {
    session.reset(createSession(req, app_name, session_params));
    if(session.get() != 0) {
      session->dlg->initFromLocalRequest(req);
      session->setCallgroup(req.from_tag);
      
      switch(addSession(req.from_tag,session.get())) {
	
      case AmSessionContainer::Inserted:
	// successful case
	break;
	
      case AmSessionContainer::ShutDown:
	throw AmSession::Exception(AmConfig::ShutdownModeErrCode,
				   AmConfig::ShutdownModeErrReason);
	
      case AmSessionContainer::AlreadyExist:
	throw AmSession::Exception(482,
				   SIP_REPLY_LOOP_DETECTED);
	
      default:
	ERROR("adding session to session container\n");
	throw string(SIP_REPLY_SERVER_INTERNAL_ERROR);
      }
      
      MONITORING_LOG5(req.from_tag, 
		      "app", app_name.c_str(),
		      "dir", "out",
		      "from", req.from.c_str(),
		      "to", req.to.c_str(),
		      "ruri", req.r_uri.c_str());
      
      if (int err = session->sendInvite(req.hdrs)) {
	ERROR("INVITE could not be sent: error code = %d.\n", err);
	AmEventDispatcher::instance()->delEventQueue(req.from_tag);
	MONITORING_MARK_FINISHED(req.from_tag.c_str());
	return "";
      }
      
      if (AmConfig::LogSessions) {      
	INFO("Starting UAC session %s app %s\n",
	     req.from_tag.c_str(), app_name.c_str());
      }
      try {
	session->start();
      } catch (...) {
	AmEventDispatcher::instance()->delEventQueue(req.from_tag);
	throw;
      }
    }
  } 
  catch(const AmSession::Exception& e){
    ERROR("%i %s\n",e.code,e.reason.c_str());
    return "";
  }
  catch(const string& err){
    ERROR("startSession: %s\n",err.c_str());
    return "";
  }
  catch(...){
    ERROR("unexpected exception\n");
    return "";
  }

  session.release();
  return req.from_tag;
}
Ejemplo n.º 7
0
KSession::KSession(QObject *parent) :
    QObject(parent), m_session(createSession("KSession"))
{
    connect(m_session, SIGNAL(finished()), this, SLOT(sessionFinished()));
    connect(m_session, SIGNAL(titleChanged()), this, SIGNAL(titleChanged()));
}
Ejemplo n.º 8
0
enum ccn_upcall_res
andana_server_session_listener(
    struct ccn_closure *selfp,
    enum ccn_upcall_kind kind,
    struct ccn_upcall_info *info)
{
    int res;
    struct andana_server *server = selfp->data;

    const unsigned char * const_encrypted = NULL;
    unsigned char *encrypted = NULL;
    size_t enc_size;

    /*
     * Extract the client's randomness (aka the symmetric key it sent us.
     * Should be the last component of the incoming Interest.
     */

    struct ccn_charbuf *request_name = NULL;
    struct ccn_indexbuf *request_comps = NULL;


    DEBUG_PRINT("IN %d %s\n", __LINE__, __func__);

    switch (kind) {
    case CCN_UPCALL_INTEREST:
        DEBUG_PRINT("%d %s received session request\n", __LINE__, __func__);
        break;
    case CCN_UPCALL_INTEREST_TIMED_OUT:
        DEBUG_PRINT("%d %s received session request time out\n", __LINE__, __func__);
        /* Fall through */
    default:
        DEBUG_PRINT("OUT %d %s\n", __LINE__, __func__);
        return(CCN_UPCALL_RESULT_OK);
    }

    printf("here now mk?\n");

    res = ccn_util_extract_name(info->interest_ccnb, info->interest_comps, &request_name, &request_comps);

    if (res < 0) {
        DEBUG_PRINT("%d %s Failed to extract session request name\n", __LINE__, __func__);
        ccn_charbuf_destroy(&request_name);
        ccn_indexbuf_destroy(&request_comps);
        return(CCN_UPCALL_RESULT_ERR);
    }

    printf("passed util extract name\n");

    res = ccn_name_comp_get(request_name->buf,
                            request_comps,
                            (unsigned int)request_comps->n - 2,
                            &const_encrypted,
                            &enc_size);

    if (res < 0) {
        DEBUG_PRINT("%d %s Failed to extract session creation data\n", __LINE__, __func__);
        ccn_charbuf_destroy(&request_name);
        ccn_indexbuf_destroy(&request_comps);
        return(CCN_UPCALL_RESULT_ERR);
    }


    encrypted = calloc(enc_size, sizeof(unsigned char));

    printf("encryption size = %d\n", enc_size);
    if (encrypted == NULL) printf("invalid pointer return from calloc\n");

    memcpy(encrypted, const_encrypted, enc_size);

    struct ccn_pkey *symkey = NULL;
    struct ccn_charbuf *decrypted = NULL;
    struct ccn_indexbuf *decrypted_comps = ccn_indexbuf_create();

    printf("trying asymmetric decryption\n");

    ccn_crypto_name_asym_decrypt(server->privkey, encrypted, &symkey, &decrypted, &decrypted_comps);
    // ccn_crypto_name_sym_decrypt(server->node_key, encrypted, encrypted_size, &decrypted, &decrypted_comps);

    /*
cn_crypto_name_sym_decrypt(server->node_key,
                                    encrypted,
                                    encrypted_size,
                                    &symkey,
                                    &decrypted,
                                    &decrypted_comps);
    */

    printf("good - now creating a session\n");


    unsigned char *session_id = NULL;
    unsigned char *session_key = NULL;
    unsigned char *server_rand = NULL;

    /*
     * Create a new session id and session key using the client's randomness.
     * The server is also responsible for contributing randomness of its own for security.
     */

    createSession(&session_id,
                  &session_key,
                  &server_rand,
                  ccn_crypto_symkey_key(symkey),
                  (unsigned int)ccn_crypto_symkey_bytes(symkey),
                  ccn_crypto_symkey_key(server->node_key));

    printf("Session made!\n");

    /* Construct the response message using a ccn name (for convenience). */

    struct ccn_charbuf *session_info = ccn_charbuf_create();
    ccn_name_init(session_info);
    ccn_name_append(session_info, session_id, SESSIONID_LENGTH);
    ccn_name_append(session_info, session_key, SESSION_KEYLEN);
    ccn_name_append(session_info, server_rand, SESSIONRAND_LENGTH);

    /**
     * Encrypt the response message using the symmetric key
     * provided by the client and send it out.
     */

    unsigned char *enc_info = NULL;
    ccn_crypto_content_encrypt(symkey, session_info->buf, session_info->length, &enc_info, &enc_size);

    struct ccn_charbuf *signed_enc_info = ccn_charbuf_create();
    struct ccn_signing_params sp = CCN_SIGNING_PARAMS_INIT;
    sp.type = CCN_CONTENT_DATA;


    res = ccn_sign_content(server->proxy->handle,
                           signed_enc_info,
                           request_name,
                           &sp,
                           enc_info,
                           enc_size);

    if (res < 0) {
        DEBUG_PRINT("%d %s Failed to signed session creation response\n", __LINE__, __func__);
    } else {
        res = ccn_put(server->proxy->handle, signed_enc_info->buf, signed_enc_info->length);
    }



    ccn_charbuf_destroy(&decrypted);
    ccn_indexbuf_destroy(&decrypted_comps);
    ccn_crypto_symkey_destroy(&symkey);
    free(session_id);
    free(session_key);
    free(server_rand);
    free(enc_info);
    ccn_charbuf_destroy(&signed_enc_info);

    if (res < 0) {
        DEBUG_PRINT("%d %s Error writing session creation response\n", __LINE__, __func__);
        return(CCN_UPCALL_RESULT_ERR);
    }

    DEBUG_PRINT("OUT %d %s Created new session. Response sent\n", __LINE__, __func__);

    return(CCN_UPCALL_RESULT_INTEREST_CONSUMED);
}