Exemplo n.º 1
0
void someMessageClient::Connect(const QString &ip)
{
    ServerAddress = ip;
    socket->connectToHost(ServerAddress,ServerPort);
    connect(socket,SIGNAL(readyRead()),this,SLOT(FetchMessage()));
    connect(socket,SIGNAL(error(QAbstractSocket::SocketError)),this,SIGNAL(ConnectionFailed(QAbstractSocket::SocketError)));
}
Exemplo n.º 2
0
void
Client::Announce()
{
  try {
    // Once connected we send our request for connection
    SendMessage(SocketMessage(ADD_CLIENT, static_cast<int>(GetType())));
    
    // Then we wait for to the server to send us a connection acknowledgement
    // + an id
    SocketMessage ack(FetchMessage());
    
    switch (ack.GetKey()) {
      case SET_CLIENT_ID:
        fClientId = ack.GetIntValue();
        break;
      case INVALID_KEY:
      default:
        throw Exception(__PRETTY_FUNCTION__, "Received an invalid answer from server", JustWarning);
    }
    
  } catch (Exception& e) {
    e.Dump();
  }
  
  std::cout << __PRETTY_FUNCTION__ << " connected to socket at port " << GetPort() << ", received id \"" << fClientId << "\""<< std::endl;
}
Exemplo n.º 3
0
NS_IMETHODIMP
nsMailboxService::StreamMessage(const char *aMessageURI,
                                nsISupports *aConsumer,
                                nsIMsgWindow *aMsgWindow,
                                nsIUrlListener *aUrlListener,
                                bool /* aConvertData */,
                                const nsACString &aAdditionalHeader,
                                bool aLocalOnly,
                                nsIURI **aURL)
{
    // The mailbox protocol object will look for "header=filter" or
    // "header=attach" to decide if it wants to convert the data instead of
    // using aConvertData. It turns out to be way too hard to pass aConvertData
    // all the way over to the mailbox protocol object.
    nsCAutoString aURIString(aMessageURI);
    if (!aAdditionalHeader.IsEmpty())
    {
      aURIString.FindChar('?') == -1 ? aURIString += "?" : aURIString += "&";
      aURIString += "header=";
      aURIString += aAdditionalHeader;
    }

    return FetchMessage(aURIString.get(), aConsumer, aMsgWindow, aUrlListener, nsnull,
                                        nsIMailboxUrl::ActionFetchMessage, nsnull, aURL);
}
// this method streams a message to the passed in consumer, with an optional stream converter
// and additional header (e.g., "header=filter")
NS_IMETHODIMP MailEwsMsgMessageService::StreamMessage(const char *aMessageURI, 
                                                      nsISupports *aConsumer, 
                                                      nsIMsgWindow *aMsgWindow,
                                                      nsIUrlListener *aUrlListener, 
                                                      bool aConvertData,
                                                      const nsACString &aAdditionalHeader,
                                                      bool aLocalOnly,
                                                      nsIURI **aURL)
{
  NS_ENSURE_ARG_POINTER(aMessageURI);

  mailews_logger << "Stream Message"
            << std::endl;

  nsAutoCString aURIString(aMessageURI);
  if (!aAdditionalHeader.IsEmpty())
  {
    aURIString.FindChar('?') == -1 ? aURIString += "?" : aURIString += "&";
    aURIString += "header=";
    aURIString += aAdditionalHeader;
  }

  return FetchMessage(aURIString.get(),
                      aConsumer,
                      aMsgWindow,
                      aUrlListener,
                      nullptr,
                      nsIMailboxUrl::ActionFetchMessage,
                      nullptr,
                      aURL);
}
Exemplo n.º 5
0
NS_IMETHODIMP nsMailboxService::DisplayMessage(const char* aMessageURI,
                                               nsISupports * aDisplayConsumer,
                                               nsIMsgWindow * aMsgWindow,
                                               nsIUrlListener * aUrlListener,
                                               const char * aCharsetOveride,
                                               nsIURI ** aURL)
{
  return FetchMessage(aMessageURI, aDisplayConsumer,
    aMsgWindow,aUrlListener, nsnull,
    nsIMailboxUrl::ActionFetchMessage, aCharsetOveride, aURL);
}
Exemplo n.º 6
0
nsresult nsMailboxService::DisplayMessageForPrinting(const char* aMessageURI,
                                                     nsISupports * aDisplayConsumer,
                                                     nsIMsgWindow * aMsgWindow,
                                                     nsIUrlListener * aUrlListener,
                                                     nsIURI ** aURL)
{
  mPrintingOperation = PR_TRUE;
  nsresult rv = FetchMessage(aMessageURI, aDisplayConsumer, aMsgWindow,aUrlListener, nsnull, 
    nsIMailboxUrl::ActionFetchMessage, nsnull, aURL);
  mPrintingOperation = PR_FALSE;
  return rv;
}
Exemplo n.º 7
0
nsresult nsMailboxService::CopyMessage(const char * aSrcMailboxURI,
                              nsIStreamListener * aMailboxCopyHandler,
                              PRBool moveMessage,
                              nsIUrlListener * aUrlListener,
                              nsIMsgWindow *aMsgWindow,
                              nsIURI **aURL)
{
    nsMailboxAction mailboxAction = nsIMailboxUrl::ActionMoveMessage;
    if (!moveMessage)
        mailboxAction = nsIMailboxUrl::ActionCopyMessage;
  return FetchMessage(aSrcMailboxURI, aMailboxCopyHandler, aMsgWindow, aUrlListener, nsnull, mailboxAction, nsnull, aURL);
}
Exemplo n.º 8
0
SocketMessage
Client::Receive(const MessageKey& key)
{
  SocketMessage msg;
  try {
    msg = FetchMessage();
    if (msg.GetKey()==key) { return msg; }
  } catch (Exception& e) {
    if (e.ErrorNumber()==11000) // client has been disconnected
      throw Exception(__PRETTY_FUNCTION__, "Some other socket asked for this client's disconnection. Obtemperating...", Fatal);
    e.Dump();
  }
  return msg;
}
Exemplo n.º 9
0
void
Messenger::AddClient()
{
  Socket s;
  try {
    AcceptConnections(s);
    Message message = FetchMessage(s.GetSocketId());
    SocketMessage m(message);
    if (m.GetKey()==ADD_CLIENT) {
      SocketType type = static_cast<SocketType>(m.GetIntValue());
      if (type!=CLIENT) SwitchClientType(s.GetSocketId(), type);
    }
    // Send the client's unique identifier
    Send(SocketMessage(SET_CLIENT_ID, s.GetSocketId()), s.GetSocketId());
  } catch (Exception& e) {
    e.Dump();
  }
}
NS_IMETHODIMP MailEwsMsgMessageService::DisplayMessage(const char *aMessageURI,
                                                       nsISupports *aDisplayConsumer,  
                                                       nsIMsgWindow *aMsgWindow,
                                                       nsIUrlListener *aUrlListener,
                                                       const char *aCharsetOverride,
                                                       nsIURI **aURL)
{
  mailews_logger << "Display Message:"
            << aMessageURI
            << ","
            << (aCharsetOverride ? aCharsetOverride : "")
            << aDisplayConsumer
            << std::endl;

  return FetchMessage(aMessageURI, aDisplayConsumer, aMsgWindow,
                      aUrlListener,
                      nullptr, nsIMailboxUrl::ActionFetchMessage,
                      aCharsetOverride, aURL);
}
Exemplo n.º 11
0
void
Client::Disconnect()
{
  std::cout << "===> Disconnecting the client from socket" << std::endl;
  if (!fIsConnected) return;
  try {
    SendMessage(SocketMessage(REMOVE_CLIENT, fClientId), -1);
  } catch (Exception& e) {
    e.Dump();
  }
  try {
    SocketMessage ack(FetchMessage());
    if (ack.GetKey()==THIS_CLIENT_DELETED or ack.GetKey()==OTHER_CLIENT_DELETED) {
      fIsConnected = false;
    }
  } catch (Exception& e) {
    if (e.ErrorNumber()!=11000) // client has been disconnected
      e.Dump();
    else return;
  }
}
Exemplo n.º 12
0
void
Messenger::Receive()
{
  Message msg;
  SocketMessage m;
  
  // We start by copying the master file descriptors list to the
  // temporary list for readout
  fReadFds = fMaster;
  
  try { SelectConnections(); } catch (Exception& e) {
    e.Dump();
    throw Exception(__PRETTY_FUNCTION__, "Impossible to select the connections!", Fatal);
  }
  
  // Looking for something to read!
  for (SocketCollection::const_iterator s=fSocketsConnected.begin(); s!=fSocketsConnected.end(); s++) {
    if (!FD_ISSET(s->first, &fReadFds)) continue;
    
    // First check if we need to handle new connections
    if (s->first==GetSocketId()) { AddClient(); return; }
    
    // Handle data from a client
    try { msg = FetchMessage(s->first); } catch (Exception& e) {
      //std::cout << "exception found..." << e.OneLine() << ", "<< e.ErrorNumber() << std::endl;
      e.Dump();
      if (e.ErrorNumber()==11000) { DisconnectClient(s->first, THIS_CLIENT_DELETED); return; }
    }
    m = SocketMessage(msg.GetString());
    // Message was successfully decoded
    fNumAttempts = 0;
    
    try { ProcessMessage(m, s->first); } catch (Exception& e) {
      if (e.ErrorNumber()==11001) break;
    }
  }
}
Exemplo n.º 13
0
void
Client::Receive()
{
  SocketMessage msg;
  try {
    msg = FetchMessage();
  } catch (Exception& e) {
    if (e.ErrorNumber()==11000) // client has been disconnected
      throw Exception(__PRETTY_FUNCTION__, "Some other socket asked for this client's disconnection. Obtemperating...", Fatal);
  }
  if (msg.GetKey()==MASTER_DISCONNECT) {
    throw Exception(__PRETTY_FUNCTION__, "Master disconnected!", Fatal);
  }
  else if (msg.GetKey()==OTHER_CLIENT_DELETED) {
    throw Exception(__PRETTY_FUNCTION__, "Some other socket asked for this client's disconnection. Obtemperating...", Fatal);
  }
  else if (msg.GetKey()==GET_CLIENT_TYPE) {
    Send(SocketMessage(CLIENT_TYPE, static_cast<int>(GetType())));
  } 
  else if (msg.GetKey()==PING_CLIENT) {
    std::ostringstream os; os << "Pong. My name is " << GetSocketId() << " and I feel fine, thank you!";
    Send(SocketMessage(PING_ANSWER, os.str()));
    PrintInfo("Got a ping, answering...");
  } 
  else if (msg.GetKey()==CLIENTS_LIST) {
    VectorValue vals = msg.GetVectorValue();
    int i = 0; std::ostringstream o; o << "List of members on the socket:\n\t";
    for (VectorValue::const_iterator v=vals.begin(); v!=vals.end(); v++, i++) {
      if (i!=0) o << ", ";
      o << *v;
    }
    PrintInfo(o.str());
  }
  else {
    ParseMessage(msg);
  }
}
Exemplo n.º 14
0
void
Messenger::ProcessMessage(SocketMessage m, int sid)
{
  if (m.GetKey()==REMOVE_CLIENT) {
    if (m.GetIntValue()==GetSocketId()) {
      std::ostringstream o;
      o << "Some client (id=" << sid << ") asked for this master's disconnection!"
        << "\n\tIgnoring this request...";
      throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning);
      return;
    }
    const MessageKey key = (sid==m.GetIntValue()) ? THIS_CLIENT_DELETED : OTHER_CLIENT_DELETED;
    DisconnectClient(m.GetIntValue(), key);
    throw Exception(__PRETTY_FUNCTION__, "Removing socket client", Info, 11001);
  }
  else if (m.GetKey()==PING_CLIENT) {
    const int toping = m.GetIntValue();
    Send(SocketMessage(PING_CLIENT), toping);
    SocketMessage msg; int i=0;
    do { msg = FetchMessage(toping); i++; } while (msg.GetKey()!=PING_ANSWER && i<MAX_SOCKET_ATTEMPTS);
    try { Send(SocketMessage(PING_ANSWER, msg.GetValue()), sid); } catch (Exception& e) { e.Dump(); }
  }
  else if (m.GetKey()==GET_CLIENTS) {
    int i = 0; std::ostringstream os;
    for (SocketCollection::const_iterator it=fSocketsConnected.begin(); it!=fSocketsConnected.end(); it++, i++) {
      if (i!=0) os << ";";
      os << it->first << " (type " << static_cast<int>(it->second) << ")";
    }
    try { Send(SocketMessage(CLIENTS_LIST, os.str()), sid); } catch (Exception& e) { e.Dump(); }
  }
  else if (m.GetKey()==WEB_GET_CLIENTS) {
    int i = 0; SocketType type; std::ostringstream os;
    for (SocketCollection::const_iterator it=fSocketsConnected.begin(); it!=fSocketsConnected.end(); it++, i++) {
      type = (it->first==GetSocketId()) ? MASTER : it->second;
      if (i!=0) os << ";";
      os << it->first << ",";
      if (it->first==GetSocketId()) os << "Master,";
      else os << "Client" << it->first << ",";
      os << static_cast<int>(type) << "\0";
    }
    try { Send(SocketMessage(CLIENTS_LIST, os.str()), sid); } catch (Exception& e) { e.Dump(); }
  }
  else if (m.GetKey()==START_ACQUISITION) {
    try { StartAcquisition(); } catch (Exception& e) {
      e.Dump();
      SendAll(DAQ, e);
    }
  }
  else if (m.GetKey()==STOP_ACQUISITION) {
    try { StopAcquisition(); } catch (Exception& e) {
      e.Dump();
      SendAll(DAQ, e);
    }
  }
  else if (m.GetKey()==NEW_RUN) {
    try {
      OnlineDBHandler().NewRun();
      int last_run = OnlineDBHandler().GetLastRun();
      SendAll(DQM, SocketMessage(RUN_NUMBER, last_run)); SendAll(DAQ, SocketMessage(RUN_NUMBER, last_run));
    } catch (Exception& e) {
      e.Dump();
    }
  }
  else if (m.GetKey()==GET_RUN_NUMBER) {
    int last_run = 0;
    try { last_run = OnlineDBHandler().GetLastRun(); } catch (Exception& e) { last_run = -1; }
    try { Send(SocketMessage(RUN_NUMBER, last_run), sid); } catch (Exception& e) { e.Dump(); }
  }
  else if (m.GetKey()==SET_NEW_FILENAME) {
    try {
      std::cout << "---> " << m.GetValue() << std::endl;
      SendAll(DQM, SocketMessage(NEW_FILENAME, m.GetValue().c_str()));
    } catch (Exception& e) { e.Dump(); }
  }
  else if (m.GetKey()==NUM_TRIGGERS or m.GetKey()==HV_STATUS) {
    try {
      SendAll(DAQ, m);
    } catch (Exception& e) { e.Dump(); }
  }
  else if (m.GetKey()==NEW_DQM_PLOT or m.GetKey()==UPDATED_DQM_PLOT) {
    try {
      SendAll(DAQ, m);
    } catch (Exception& e) { e.Dump(); }
  }
  else if (m.GetKey()==EXCEPTION) {
    try {
      SendAll(DAQ, m);
      std::cout << "--> " << m.GetValue() << std::endl;
    } catch (Exception& e) { e.Dump(); }
  }
  /*else {
    try { Send(SocketMessage(INVALID_KEY), sid); } catch (Exception& e) { e.Dump(); }
    std::ostringstream o;
    o << "Received an invalid message: " << m.GetString();
    throw Exception(__PRETTY_FUNCTION__, o.str(), JustWarning);
  }*/
}
Exemplo n.º 15
0
/*
 * read specified amount of bytes from given desc/offset to buffer
 * return amount of read bytes or negative error code if call failed
 */
static int32_t ZVMReadHandle(struct NaClApp *nap,
    int ch, char *buffer, int32_t size, int64_t offset)
{
  struct ChannelDesc *channel;
  int64_t tail;
  char *sys_buffer;
  int32_t retcode = -1;

  assert(nap != NULL);
  assert(nap->system_manifest != NULL);
  assert(nap->system_manifest->channels != NULL);

  /* check the channel number */
  if(ch < 0 || ch >= nap->system_manifest->channels_count)
  {
    ZLOGS(LOG_DEBUG, "channel_id=%d, buffer=0x%lx, size=%d, offset=%ld",
        ch, (intptr_t)buffer, size, offset);
    return -EINVAL;
  }
  channel = &nap->system_manifest->channels[ch];
  ZLOGS(LOG_DEBUG, "channel %s, buffer=0x%lx, size=%d, offset=%ld",
      channel->alias, (intptr_t)buffer, size, offset);

  /* check buffer and convert address */
  if(CheckRAMAccess(nap, (uintptr_t)buffer, size, PROT_READ) == -1) return -EINVAL;
  sys_buffer = (char*)NaClUserToSys(nap, (uintptr_t) buffer);

  /* ignore user offset for sequential access read */
  if(CHANNEL_SEQ_READABLE(channel))
    offset = channel->getpos;
  else
    /* prevent reading beyond the end of the random access channels */
    size = MIN(channel->size - offset, size);

  /* check arguments sanity */
  if(size == 0) return 0; /* success. user has read 0 bytes */
  if(size < 0) return -EFAULT;
  if(offset < 0) return -EINVAL;

  /* check for eof */
  if(channel->eof) return 0;

  /* check limits */
  if(channel->counters[GetsLimit] >= channel->limits[GetsLimit])
    return -EDQUOT;
  if(CHANNEL_RND_READABLE(channel))
    if(offset >= channel->limits[PutSizeLimit] - channel->counters[PutSizeLimit]
      + channel->size) return -EINVAL;

  /* calculate i/o leftovers */
  tail = channel->limits[GetSizeLimit] - channel->counters[GetSizeLimit];
  if(size > tail) size = tail;
  if(size < 1) return -EDQUOT;

  /* read data and update position */
  switch(channel->source)
  {
    case ChannelRegular:
      retcode = pread(channel->handle, sys_buffer, (size_t)size, (off_t)offset);
      if(retcode == -1) retcode = -errno;
      break;
    case ChannelCharacter:
    case ChannelFIFO:
     retcode = fread(sys_buffer, 1, (size_t)size, (FILE*)channel->socket);
      if(retcode == -1) retcode = -errno;
      break;
    case ChannelTCP:
      retcode = FetchMessage(channel, sys_buffer, size);
      if(retcode == -1) retcode = -EIO;
      break;
    default: /* design error */
      ZLOGFAIL(1, EFAULT, "invalid channel source");
      break;
  }

  /* update the channel counter, size, position and tag */
  ++channel->counters[GetsLimit];
  if(retcode > 0)
  {
    channel->counters[GetSizeLimit] += retcode;
    UpdateChannelTag(channel, (const char*)sys_buffer, retcode);

    /*
     * current get cursor. must be updated if channel have seq get
     * but there is nothing wrong to update it even it have random get
     */
    channel->getpos = offset + retcode;

    /* if channel have random put update put cursor. not allowed for cdr */
    if(CHANNEL_RND_WRITEABLE(channel)) channel->putpos = offset + retcode;
  }

  /*
   * set eof if 0 bytes has been read. it is safe because
   * 1. if user asked for a 0 bytes control will not reach this code
   * 2. if user asked more then 0 bytes and got 0 that means end of data
   * 3. if quota exceeded user will get an error before an actual read
   */
  if(retcode == 0) channel->eof = 1;

  return retcode;
}
Exemplo n.º 16
0
int PrefetchChannelDtor(struct ChannelDesc *channel)
{
  char url[BIG_ENOUGH_STRING];  /* debug purposes only */

  assert(channel != NULL);
  assert(channel->socket != NULL);

  /* log parameters and channel internals */
  MakeURL(url, BIG_ENOUGH_STRING, channel, GetChannelConnectionInfo(channel));
  ZLOGS(LOG_DEBUG, "%s has url %s", channel->alias, url);

  /* close "PUT" channel */
  if(channel->limits[PutsLimit] && channel->limits[PutSizeLimit])
  {
    int size = CHANNELS_ETAG_ENABLED ? TAG_DIGEST_SIZE - 1 : 0;

    /* prepare digest */
    if(TagEngineEnabled())
    {
      TagDigest(channel->tag, channel->digest);
      TagDtor(channel->tag);
    }

    /* send eof */
    channel->eof = 1;
    SendMessage(channel, channel->digest, size);
    ZLOGS(LOG_DEBUG, "%s closed with tag %s, putsize %ld",
        channel->alias, channel->digest, channel->counters[PutSizeLimit]);
  }

  /* close "GET" channel */
  if(channel->limits[GetsLimit] && channel->limits[GetSizeLimit])
  {
    /* wind the channel to the end */
    while(channel->eof == 0)
    {
      char buf[NET_BUFFER_SIZE];
      int32_t size = FetchMessage(channel, buf, NET_BUFFER_SIZE);
      ++channel->counters[GetsLimit];
      channel->counters[GetSizeLimit] += size;

      /* update tag if enabled */
      if(TagEngineEnabled())
        TagUpdate(channel->tag, buf, size);
    }

    /* test integrity (if etag enabled) */
    if(TagEngineEnabled())
    {
      /* prepare digest */
      TagDigest(channel->tag, channel->digest);
      TagDtor(channel->tag);

      /* raise the error if the data corrupted */
      if(memcmp(channel->control, channel->digest, TAG_DIGEST_SIZE) != 0)
      {
        ZLOG(LOG_ERROR, "%s corrupted, control: %s, local: %s",
            channel->alias, channel->control, channel->digest);
        SetExitState("data corrupted");
        SetExitCode(EPIPE);
      }

      ZLOGS(LOG_DEBUG, "%s closed with tag %s, getsize %ld",
          channel->alias, channel->digest, channel->counters[GetSizeLimit]);
    }

    zmq_msg_close(&channel->msg);
    zmq_close(channel->socket);
  }

  /* will destroy context and netlist after all network channels closed */
  NetDtor();

  return 0;
}