Beispiel #1
0
int
HTTP_SSL_Server_Session::on_read_complete(ACE_Message_Block& mb, const TRB_Asynch_Read_Stream::Result& result)
{
	//ACE_OS::write_n(ACE_STDOUT, mb.rd_ptr(), mb.length()); //@

	HTTP::Responser http;

	if ( mb.space() == 0 || (mb.length() > 4 && ACE_OS::strncmp(mb.wr_ptr()-4, "\r\n\r\n", 4) == 0) )
	{
		//ACE_Time_Value tv(0, 1 * 1000);
		//timespec_t t  = (timespec_t) tv;
		//ACE_OS::nanosleep(&t);

		int n_err = 0;
		if ( mb.space() == 0 ) n_err = HTTP::Response::Request_Entity_Too_Large;
		
		ACE_Message_Block* out = new (std::nothrow) ACE_Message_Block(BUFSIZE);
		int n_res = http.parse_header(&mb, out, n_err);

		write(*out);
	}
	else
	{
		read(mb);
		return 1;
	}

	return 0;
}
Beispiel #2
0
int
JAWS_IO_Reactive_Transmit::handle_output_source (ACE_HANDLE handle)
{
  ACE_Message_Block *mb = this->source_buf_;

  // Try to read data into the mb if data is still available.
  if (mb->space () && this->source_ != ACE_INVALID_HANDLE)
    {
      ssize_t count;
      count = ACE_OS::read (this->source_, mb->wr_ptr (), mb->space ());

      if (count < 0)
        {
          this->source_ = ACE_INVALID_HANDLE;
          this->source_buf_ = 0;

          if (this->bytes_ == 0)
            {
              JAWS_Event_Result io_result ( 0
                                          , JAWS_Event_Result::JE_ERROR
                                          , JAWS_Event_Result::JE_TRANSMIT_FAIL
                                          );
              this->io_result_ = io_result;
            }
          else if (this->bytes_ > 0)
            {
              JAWS_Event_Result io_result ( this->bytes_
                                          , JAWS_Event_Result::JE_ERROR
                                          , JAWS_Event_Result::JE_TRANSMIT_SHORT
                                          );
              this->io_result_ = io_result;
            }

          return -1;
        }
      else if (count == 0)
        this->source_ = ACE_INVALID_HANDLE;
      else
        mb->wr_ptr (count);
    }

  int result = 0;

  if (mb->length () > 0)
    result = this->handle_output_mb (handle, mb);

  if (result < 0)
    {
      this->source_ = ACE_INVALID_HANDLE;
      this->source_buf_ = 0;
    }
  else if (mb == 0 && this->source_ == ACE_INVALID_HANDLE)
    this->source_buf_ = 0;
  else
    this->source_buf_->crunch ();

  return result;
}
Beispiel #3
0
//get file and store it into ACE message block.
bool ZIP_Wrapper::get_file (char* archive_path, char* filename,
                            ACE_Message_Block &file)
{
  bool return_code = true;
  unzFile uf=0;
  uf = unzOpen(archive_path);
  /* locate the desired file in the zip file and set it as current file*/
  int j=unzLocateFile(uf, filename, 0);
  if (j==UNZ_END_OF_LIST_OF_FILE)
    {
      DANCE_ERROR (DANCE_LOG_ERROR,
                   (LM_DEBUG, ACE_TEXT("File not found in zip archive")));
      return false;
    }
  else if (j==UNZ_OK)
    {
      int k=unzOpenCurrentFile(uf);
      if (k!=UNZ_OK)
        {
          DANCE_ERROR (DANCE_LOG_ERROR,
                       (LM_DEBUG, ACE_TEXT("Error in opening the current")
                        ACE_TEXT(" file using unzOpenCurrentFile")));
          return false;
        }
      else
        {
          int num_read = 0;
          ACE_Message_Block* head = &file;

          //read the file into the ACE_Message_Block
          do
            {
              if (head->space () == 0)
                {
                  ACE_Message_Block* next = 0;
                  ACE_NEW_RETURN (next, ACE_Message_Block (BUFSIZ), false);
                  head = head->cont ();
                }
              num_read = unzReadCurrentFile(archive_path, head->wr_ptr(),
                                                  head->space());
              if (num_read > 0)
                head->wr_ptr (num_read);
            } while (num_read > 0);
          if (num_read < 0)
            return_code = false;
          unzCloseCurrentFile(uf);
          unzClose(uf);
          return return_code;
        }
    }
  return return_code;
}
Beispiel #4
0
bool P2pEndpoint::readMessage(ACE_INET_Addr& peerAddr,
    ACE_Message_Block& mblock)
{
    assert(mblock.size() >= P2pConfig::defaultMtu);

    const ssize_t recvSize =
        udp_->recv(mblock.wr_ptr(), mblock.space(), peerAddr);
    if (recvSize == 0) {
        return false;
    }

    if (recvSize < 0) {
        const int error = ACE_OS::last_error();
        if (error == EWOULDBLOCK) {
            return false;
        }
        //if (error == ECONNRESET) {
        //    return false;
        //}

        NSRPC_LOG_ERROR4(
            ACE_TEXT("P2pEndpoint::readMessage(from: %s:%d) FAILED!!!(%d,%m)"),
            peerAddr.get_host_addr(), peerAddr.get_port_number(),
            ACE_OS::last_error());
        return false;
    }
    mblock.wr_ptr(recvSize);

    return true;
}
int
AIO_SSL_Client_Session::read(ACE_Message_Block& mb)
{
	if ( ssl_ )
	{
		if ( is_cancelling_ ) return -1;
		if ( n_op_r_ != 0 ) // > 0
		{
			mb.release();
			return n_op_r_; // don't start second read, and return # of pending read
		}

		// Inititiate read
		if ( this->ssl_stream_.read(mb, mb.space()) == -1)
		{
			mb.release();
			if ( !is_cancelling_ ) { is_cancelling_ = 1; ssl_stream_.cancel(); }
			return -1;
		}

		++n_op_r_;

		return 0;
	}
	else
	{
		return AIO_Session::read(mb);
	}
}
Beispiel #6
0
//***************************************************************************
//
//    Method:          handle_write_file
//
//    Description:   Callback used when a write completes
//
// Inputs:        write file result structure containing message block
//
// Returns:       none
//
//***************************************************************************
void
FileIOHandler::handle_write_file(const ACE_Asynch_Write_File::Result &result)
{
  ACE_DEBUG((LM_INFO, ACE_TEXT("Finished write\n")));
  // When the write completes, we get the message block. It's been sent,
  // so we just deallocate it.
  result.message_block().release();
#if defined (ACE_WIN32)
  // to circumvent problems on older Win32 (see above) we schedule a read here if none
  // is pending yet.
  if (!this->read_pending_)
  {
    ACE_Message_Block *mb;
    ACE_NEW_NORETURN(mb, ACE_Message_Block(FILE_FRAME_SIZE));
    if (reader_.read(*mb, mb->space(),
                     (this->block_count_ - 1) * FILE_FRAME_SIZE) != 0)
    {
      int errnr = ACE_OS::last_error ();
      ACE_DEBUG(
          (LM_INFO, ACE_TEXT("%p [%d]\n"), ACE_TEXT("FileIOHandler read after write failed"), errnr));
      mb->release();
    }
    else
    {
      this->read_pending_ = true;
    }
  }
#endif
}
Beispiel #7
0
int
PSession::initiate_read (u_long offset_low, u_long offset_high, ACE_Message_Block & mb)
{
    size_t nbytes = mb.space();

    if (nbytes == 0)
    {
        mb.release ();
        this->do_cancel ();

        ACE_ERROR_RETURN((LM_ERROR,
            ACE_TEXT ("(%t) %s Attempt to read 0 bytes\n"),
            this->get_name()),
            -1);
    }

    int rc = this->file_read_.read (mb, nbytes, offset_low, offset_high);

    if (rc < 0)
    {
        mb.release();
        this->do_cancel ();
        return -1;
    }

    this->ref_cnt_r_++;
    this->total_r_++;
    return 0;
}
void
TCP_Client_Connection::read(ACE_Message_Block& mb)
{
	//ACE_GUARD(ACE_Thread_Mutex, guard, lock_);

	if ( timeout_ > 0 )
	{
		timer_.expires_from_now(boost::posix_time::seconds(timeout_));
		timer_.async_wait(
			strand_.wrap(boost::bind(
				&TCP_Client_Connection::handle_socket_timeout,
				this,
				placeholders::error,
				(int) READ,
				timeout_
			)));
	}

	if ( is_ssl_ )
	{
		socket_->async_read_some(
			buffer(mb.wr_ptr(), mb.space()),
			make_custom_alloc_handler(allocator_,
			strand_.wrap(boost::bind(
				&TCP_Client_Connection::handle_read,
				this,
				placeholders::error,
				placeholders::bytes_transferred
			))));
	}
	else
	{
		socket().async_read_some(
			buffer(mb.wr_ptr(), mb.space()),
			make_custom_alloc_handler(allocator_,
			strand_.wrap(boost::bind(
				&TCP_Client_Connection::handle_read,
				this,
				placeholders::error,
				placeholders::bytes_transferred
			))));
	}
}
Beispiel #9
0
void ProactorService::PostRecv()
{
	ACE_Message_Block* pBlock;

	ACE_NEW_NORETURN(pBlock, ACE_Message_Block (2048));
	if(this->m_AsyncReader.read(*pBlock, pBlock->space()) != 0)
	{
		pBlock->release();
		ReserveClose();
	}
}
Beispiel #10
0
int
HTTP_Client_Session::on_open(ACE_Message_Block& mb_open)
{
	ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%t) AIO_Session open(this: %@)\n"), this));//@

	ACE_Message_Block* mb = new (std::nothrow) ACE_Message_Block(BUFSIZE+1);
	if ( !mb ) return -1;

	int n = 0;
	n = ACE_OS::snprintf(mb->wr_ptr(), mb->space(), HTTP::Header::_Request_, "GET", "/no_content.htm", 1.0); mb->wr_ptr(n);
	//n = ACE_OS::snprintf(mb->wr_ptr(), mb->space(), HTTP::Header::Connection, "keep-alive"); mb->wr_ptr(n);
	//n = ACE_OS::snprintf(mb->wr_ptr(), mb->space(), HTTP::Header::Host, "localhost"); mb->wr_ptr(n);
	n = ACE_OS::snprintf(mb->wr_ptr(), mb->space(), HTTP::Header::_End_); mb->wr_ptr(n);

	//ACE_OS::write_n(ACE_STDOUT, mb->rd_ptr(), mb->length()); //@

	if ( write(*mb) != 0 ) return -1;

	return 0;
}
void
SBRS_Server_Connection::read(ACE_Message_Block& mb, long timeout)
{
	ACE_GUARD(ACE_Thread_Mutex, guard, lock_);

	socket_.async_read_some(buffer(mb.wr_ptr(), mb.space()), strand_.wrap(boost::bind(
		&SBRS_Server_Connection::handle_read,
		this,
		placeholders::error,
		placeholders::bytes_transferred)));

	if ( timeout > 0 )
	{
		timer_.expires_from_now(boost::posix_time::seconds(timeout));
		timer_.async_wait(strand_.wrap(boost::bind(
			&SBRS_Server_Connection::handle_socket_timeout,
			this,
			placeholders::error)));
	}
}
Beispiel #12
0
int
PConnection::initiate_read_stream (void)
{
    if (this->get_ref_cnt_r() != 0)
        return 0;

    ACE_Message_Block * mb = this->alloc_msg();

    if (mb == 0)
        return -1;

    // Inititiate read
    if (this->start_asynch_read(*mb, mb->space()) == -1)
    {
        this->free_msg(mb);
        this->cancel();
        return -1;
    }

    this->ref_cnt_r_++;
    this->total_r_++;
    return 0;
}
Beispiel #13
0
void Reciever::open (ACE_HANDLE h, ACE_Message_Block&)  
{  
	//ACE_DEBUG LOG here,print ip,port,establish time

	//client_address.addr_to_string(peer_name, sizeof(peer_name) / sizeof(ACE_TCHAR));
	//ACE_DEBUG((LM_DEBUG, "%s", "\nOne User has established a connection.\n"));
	//ACE_DEBUG((LM_DEBUG,ACE_TEXT("IP Address:%s \n"),peer_name));
	ACE_OS::printf("One User has established a connection.\n");
	ACE_OS::printf("Current time:%s",this->curTime());

	//get remote ip and port
	/*ACE_INET_Addr addr;
	ACE_SOCK_SEQPACK_Association ass = ACE_SOCK_SEQPACK_Association(h); 
	size_t addr_size = 1; 
	ass.get_local_addrs(&addr,addr_size);*/

    this->handle(h);
    if (this->reader_.open(*this) != 0 )  
        {  
            delete this;  
            return;  
        }  
        if (this->writer_.open(*this) != 0 )  
        {  
            delete this;  
            return;  
		}

        ACE_Message_Block *mb = new ACE_Message_Block(buffer,MAX_MSG_LEN);  
        if (this->reader_.read (*mb, mb->space()) != 0)  
        {  
            //ACE_OS::printf("Begin read failed!\n");  
            delete this;  
            return;
        }
        return;  
}  
Beispiel #14
0
int TCPConnectionHandler::handle_input (ACE_HANDLE handle)
{
  ACE_UNUSED_ARG (handle);
  ACE_Message_Block *buffer = new ACE_Message_Block (TCPBytesToSend);
  int bytesReceived = peer_.recv (buffer->wr_ptr (), buffer->space ());

  if (bytesReceived > 0)
    {
      totalReceived_ += bytesReceived;
      if (serverSide_ || --pingsNo_ > 0) // echo received buffer
        {
          buffer->wr_ptr (bytesReceived);
          int result = scheduleSend (buffer);
          if (0 > result)
            ACE_ERROR_RETURN ((LM_ERROR,
                               ACE_TEXT (" (%P) %p\n"),
                               ACE_TEXT ("Cannot schedule TCP reply")),
                              -1);
        }
      else
        buffer->release ();

      return 0;
    }

  if (errno != EWOULDBLOCK)
    ACE_ERROR_RETURN ((LM_ERROR,
                       ACE_TEXT (" (%P:%p (%d)\n"),
                       ACE_TEXT ("TCPConnectionHandler::handle_input call with no data on handle "), handle),
                      -1);

  ACE_ERROR ((LM_WARNING,
              ACE_TEXT (" (%P:%p (%d)\n"),
              ACE_TEXT ("TCPConnectionHandler::handle_input call with no data on handle "), handle));

  return 0;
}
Beispiel #15
0
  virtual int svc () {
    const size_t FileReadSize = 8 * 1024;
    ACE_Message_Block mblk (FileReadSize);

    for (;; mblk.crunch ()) {
      // Read as much as will fit in the message block.
      ssize_t bytes_read = logfile_.recv (mblk.wr_ptr (),
                                          mblk.space ());
      if (bytes_read <= 0)
        break;
      mblk.wr_ptr (static_cast<size_t> (bytes_read));

      // We have a bunch of data from the log file. The data is
      // arranged like so:
      //    hostname\0
      //    CDR-encoded log record
      // So, first we scan for the end of the host name, then
      // initialize another ACE_Message_Block aligned for CDR
      // demarshaling and copy the remainder of the block into it. We
      // can't use duplicate() because we need to be sure the data
      // pointer is aligned properly for CDR demarshaling.  If at any
      // point, there's not enough data left in the message block to
      // extract what's needed, crunch the block to move all remaining
      // data to the beginning and read more from the file.
      for (;;) {
        size_t name_len = ACE_OS::strnlen
                             (mblk.rd_ptr (), mblk.length ());
        if (name_len == mblk.length ()) break;

        char *name_p = mblk.rd_ptr ();
        ACE_Message_Block *rec, *head, *temp;
        ACE_NEW_RETURN
          (head, ACE_Message_Block (name_len, MB_CLIENT), 0);
        head->copy (name_p, name_len);
        mblk.rd_ptr (name_len + 1);   // Skip nul also

        size_t need = mblk.length () + ACE_CDR::MAX_ALIGNMENT;
        ACE_NEW_RETURN (rec, ACE_Message_Block (need), 0);
        ACE_CDR::mb_align (rec);
        rec->copy (mblk.rd_ptr (), mblk.length ());

        // Now rec contains the remaining data we've read so far from
        // the file. Create an ACE_InputCDR to start demarshaling the
        // log record, header first to find the length, then the data.
        // Since the ACE_InputCDR constructor increases the reference count
        // on rec, we release it upon return to prevent leaks.
        // The cdr 'read' methods return 0 on failure, 1 on success.
        ACE_InputCDR cdr (rec); rec->release ();
        ACE_CDR::Boolean byte_order;
        if (!cdr.read_boolean (byte_order)) {
          head->release (); rec->release (); break;
        }
        cdr.reset_byte_order (byte_order);

        // Now read the length of the record. From there, we'll know
        // if rec contains the complete record or not.
        ACE_CDR::ULong length;
        if (!cdr.read_ulong (length)) {
          head->release (); mblk.rd_ptr (name_p); break;
        }
        if (length > cdr.length ()) {
          head->release (); mblk.rd_ptr (name_p); break;
        }

        // The complete record is in rec... grab all the fields into
        // separate, chained message blocks.
        ACE_NEW_RETURN (temp,
                        ACE_Message_Block (length, MB_TEXT),
                        0);
        ACE_NEW_RETURN
          (temp,
           ACE_Message_Block (2 * sizeof (ACE_CDR::Long),
                              MB_TIME, temp),
           0);
        ACE_NEW_RETURN
          (temp,
           ACE_Message_Block (sizeof (ACE_CDR::Long),
                              MB_PID, temp),
           0);
        ACE_NEW_RETURN
          (temp,
           ACE_Message_Block (sizeof (ACE_CDR::Long),
                              MB_TYPE, temp),
           0);
        head->cont (temp);

        // Extract the type
        ACE_CDR::Long *lp;
        lp = reinterpret_cast<ACE_CDR::Long*> (temp->wr_ptr ());
        cdr >> *lp;
        temp->wr_ptr (sizeof (ACE_CDR::Long));
        temp = temp->cont ();

        // Extract the pid
        lp = reinterpret_cast<ACE_CDR::Long*> (temp->wr_ptr ());
        cdr >> *lp;
        temp->wr_ptr (sizeof (ACE_CDR::Long));
        temp = temp->cont ();

        // Extract the timestamp (2 Longs)
        lp = reinterpret_cast<ACE_CDR::Long*> (temp->wr_ptr ());
        cdr >> *lp; ++lp; cdr >> *lp;
        temp->wr_ptr (2 * sizeof (ACE_CDR::Long));
        temp = temp->cont ();

        // Demarshal the length of the message text, then demarshal
        // the text into the block.
        ACE_CDR::ULong text_len;
        cdr >> text_len;
        cdr.read_char_array (temp->wr_ptr (), text_len);
        temp->wr_ptr (text_len);

        // Forward the whole lot to the next module.
        if (put_next (head) == -1) break;

        // Move the file-content block's read pointer up past whatever
        // was just processed. Although the mblk's rd_ptr has not been
        // moved, cdr's has.  Therefore, use its length() to determine
        // how much is left.
        mblk.rd_ptr (mblk.length () - cdr.length ());
      }
    }

    // Now that the file is done, send a block down the stream to tell
    // the other modules to stop.
    ACE_Message_Block *stop;
    ACE_NEW_RETURN
      (stop, ACE_Message_Block (0, ACE_Message_Block::MB_STOP),
       0);
    put_next (stop);
    return 0;
  }
void
JAWS_Config_File_Impl::parse_file (void)
{
  ACE_FILE_Connector fconnector;
  ACE_FILE_IO fio;

  if (fconnector.connect ( fio
                         , this->faddr_
                         , 0
                         , ACE_Addr::sap_any
                         , 0
                         , O_RDONLY
                         ) == -1)
    return;

  ACE_Message_Block buffer (8192);
  ACE_Message_Block line (4096);
  ssize_t count = 0;
  const ACE_TCHAR *sym_name;
  const ACE_TCHAR *sym_value;
  int last_line_was_read = 0;
  ACE_TCHAR *end_of_current_line = 0;
  ACE_TCHAR *p = 0;

  while (last_line_was_read
         || (count = fio.recv (buffer.wr_ptr (), buffer.space () - 2)) >= 0)
    {
      end_of_current_line = 0;

      // Make sure input is newline terminated if it is the last line,
      // and always null terminated.
      if (! last_line_was_read)
        {
          if (count > 0)
            {
              buffer.wr_ptr (count);
              // Scan forward for at least one newline character
              p = buffer.rd_ptr ();
              while (p != buffer.wr_ptr ())
                {
                  if (*p == '\n')
                    break;
                  p++;
                }

              if (p == buffer.wr_ptr ())
                continue;

              end_of_current_line = p;
            }
          else
            {
              if (buffer.wr_ptr ()[-1] != '\n')
                {
                  buffer.wr_ptr ()[0] = '\n';
                  buffer.wr_ptr (1);
                }

              last_line_was_read = 1;
            }

          buffer.wr_ptr ()[0] = '\0';
        }

      if (end_of_current_line == 0)
        {
          end_of_current_line = buffer.rd_ptr ();
          while (*end_of_current_line != '\n')
            end_of_current_line++;
        }

      // If buffer is not pointing to a continuation line, or there is
      // no more input, then can commit the scanned configuration
      // line.
      if (line.length () != 0
          && ((last_line_was_read && buffer.length () == 0)
              || (buffer.rd_ptr ()[0] != ' '
                  && buffer.rd_ptr ()[0] != '\t')))
        {
          ACE_TCHAR *name = 0;
          ACE_TCHAR *value = 0;

          name = line.rd_ptr ();
          for (p = name; *p != '\0'; p++)
            {
              if (*p == '=')
                {
                  line.rd_ptr (p+1);
                  while (p != name && (p[-1] == ' ' || p[-1] == '\t'))
                    p--;
                  *p = '\0';
                }
            }

          if (*name)
            {
              value = line.rd_ptr ();
              while (*value == ' ' || *value == '\t')
                value++;
              p = line.wr_ptr ();
              while (p != value && (p[-1] == ' ' || p[-1] == '\t'))
                p--;
              *p = '\0';

              sym_name = this->strings_->duplicate (name);
              sym_value = this->strings_->duplicate (value);
              this->symbols_->rebind (sym_name, sym_value);
            }

          line.reset ();
        }

      // If we are done, we are done!
      if (last_line_was_read && buffer.length () == 0)
        break;

      // If the buffer is pointing at a comment line, ignore it.
      if (buffer.rd_ptr ()[0] == '#'
          || buffer.rd_ptr ()[0] == '\n'
          || (buffer.rd_ptr ()[0] == '\r' && buffer.rd_ptr ()[1] == '\n'))
        {
          buffer.rd_ptr (end_of_current_line + 1);
          buffer.crunch ();
          continue;
        }

      // Whatever is left is either the start of a name-value-pair or a
      // continuation of one.
      line.copy (buffer.rd_ptr (),
                 end_of_current_line - buffer.rd_ptr ());
      p = line.wr_ptr ();
      while (p != line.rd_ptr () && (p[-1] == ' ' || p[-1] == '\t'))
        p--;
      line.wr_ptr (p);
      line.wr_ptr ()[0] = '\0';
      buffer.rd_ptr (end_of_current_line + 1);
      buffer.crunch ();
    }

  fio.close ();
}
void OpenDDS::DCPS::DataDurabilityCache::init()
{
  ACE_Allocator * const allocator = this->allocator_.get();
  ACE_NEW_MALLOC(
    this->samples_,
    static_cast<sample_map_type *>(
      allocator->malloc(sizeof(sample_map_type))),
    sample_map_type(allocator));

  typedef DurabilityQueue<sample_data_type> data_queue_type;

  if (this->kind_ == DDS::PERSISTENT_DURABILITY_QOS) {
    // Read data from the filesystem and create the in-memory data structures
    // as if we had called insert() once for each "datawriter" directory.
    using OpenDDS::FileSystemStorage::Directory;
    using OpenDDS::FileSystemStorage::File;
    Directory::Ptr root_dir = Directory::create(this->data_dir_.c_str());
    std::vector<std::string> path(4);  // domain, topic, type, datawriter

    for (Directory::DirectoryIterator domain = root_dir->begin_dirs(),
         domain_end = root_dir->end_dirs(); domain != domain_end; ++domain) {
      path[0] = domain->name();
      DDS::DomainId_t domain_id;
      {
        std::istringstream iss(path[0]);
        iss >> domain_id;
      }

      for (Directory::DirectoryIterator topic = domain->begin_dirs(),
           topic_end = domain->end_dirs(); topic != topic_end; ++topic) {
        path[1] = topic->name();

        for (Directory::DirectoryIterator type = topic->begin_dirs(),
             type_end = topic->end_dirs(); type != type_end; ++type) {
          path[2] = type->name();

          key_type key(domain_id, path[1].c_str(), path[2].c_str(),
                       allocator);
          sample_list_type * sample_list = 0;
          ACE_NEW_MALLOC(sample_list,
                         static_cast<sample_list_type *>(
                           allocator->malloc(sizeof(sample_list_type))),
                         sample_list_type(0, static_cast<data_queue_type *>(0),
                                          allocator));
          this->samples_->bind(key, sample_list, allocator);

          for (Directory::DirectoryIterator dw = type->begin_dirs(),
               dw_end = type->end_dirs(); dw != dw_end; ++dw) {
            path[3] = dw->name();

            size_t old_len = sample_list->size();
            sample_list->size(old_len + 1);
            data_queue_type *& slot = (*sample_list)[old_len];

            // This variable is called "samples" in the insert() method be
            // we already have a "samples_" which is the overall data structure.
            data_queue_type * sample_queue = 0;
            ACE_NEW_MALLOC(sample_queue,
                           static_cast<data_queue_type *>(
                             allocator->malloc(sizeof(data_queue_type))),
                           data_queue_type(allocator));

            slot = sample_queue;
            sample_queue->fs_path_ = path;

            for (Directory::FileIterator file = dw->begin_files(),
                 file_end = dw->end_files(); file != file_end; ++file) {
              std::ifstream is;

              if (!file->read(is)) {
                if (DCPS_debug_level) {
                  ACE_ERROR((LM_ERROR,
                             ACE_TEXT("(%P|%t) DataDurabilityCache::init ")
                             ACE_TEXT("couldn't open file for PERSISTENT ")
                             ACE_TEXT("data: %C\n"), file->name().c_str()));
                }
                continue;
              }

              DDS::Time_t timestamp;
              is >> timestamp.sec >> timestamp.nanosec >> std::noskipws;
              is.get(); // consume separator

              const size_t CHUNK = 4096;
              ACE_Message_Block mb(CHUNK);
              ACE_Message_Block * current = &mb;

              while (!is.eof()) {
                is.read(current->wr_ptr(), current->space());

                if (is.bad()) break;

                current->wr_ptr(is.gcount());

                if (current->space() == 0) {
                  ACE_Message_Block * old = current;
                  current = new ACE_Message_Block(CHUNK);
                  old->cont(current);
                }
              }

              sample_queue->enqueue_tail(
                sample_data_type(timestamp, mb, allocator));

              if (mb.cont()) mb.cont()->release();    // delete the cont() chain
            }
          }
        }
      }
    }
  }

  CORBA::ORB_var orb = TheServiceParticipant->get_ORB();
  this->reactor_ = orb->orb_core()->reactor();
}
Beispiel #18
0
int FileIOHandler::Connect()
{
  int result = 0;

  // create an empty temporary file for the test
  if(connector_.connect(peer_,
                        ACE_sap_any_cast (ACE_FILE_Addr &)) != 0)
  {
    ACE_ERROR((LM_ERROR, ACE_TEXT("%p\n"),
            ACE_TEXT("FileIOHandler connect failed to create file")));
    result = -1;
  }

  // close opened file but leave it where it is
  if (peer_.close () != 0)
  {
    ACE_ERROR((LM_ERROR, ACE_TEXT("%p\n"),
            ACE_TEXT("FileIOHandler connect failed to close file")));
    peer_.remove ();
    result = -1;
  }

  // get file address
  ACE_FILE_Addr tmp_addr;
  peer_.get_local_addr (tmp_addr);

  // reopen new file for asynch IO
  if(connector_.connect(peer_,
                        tmp_addr,
                        0, //timeout
                        ACE_Addr::sap_any,
                        0, //reuse
                        O_RDWR |FILE_FLAG_OVERLAPPED) != 0)
  {
    ACE_ERROR((LM_ERROR, ACE_TEXT("%p\n"),
            ACE_TEXT("FileIOHandler connect failed to open file")));
    peer_.remove ();
    result = -1;
  }
  else // device connected successfully
  {
    // keep track of our writes for offset calculations (can't use O_APPEND since
    // this is not supported for the Win32_Asynch implementation) and data verifications
    this->block_count_ = 0; // start counting

    // Set our I/O handle to that of the peer_ object handling our connection
    handle(peer_.get_handle());

    if (writer_.open(*this) != 0 || reader_.open(*this) != 0)
    {
      ACE_ERROR(
          (LM_ERROR, ACE_TEXT("%p\n"), ACE_TEXT("FileIOHandler reader or writer open failed")));
      result = -1;
    }
    else // reader and writer opened successfully
    {
      // Allocate a new message block and initiate a read operation on it
      // to prime the asynchronous read pipeline
      // The message block is sized for the largest message we expect
      ACE_Message_Block *mb;
      ACE_NEW_NORETURN(mb, ACE_Message_Block(FILE_FRAME_SIZE));
      if (reader_.read(*mb, mb->space()) != 0)
      {
        int errnr = ACE_OS::last_error ();
        ACE_DEBUG(
            (LM_INFO, ACE_TEXT("%p [%d]\n"), ACE_TEXT("FileIOHandler begin read failed"), errnr));
        mb->release();
#if defined (ACE_WIN32)
        // On older Win32 versions (WinXP, Win2003/2008) asynch IO with disk files is not
        // reliable and may perform sync IO in certain cases like when the read offset denotes
        // current end of file. Instead of scheduling a write operation the read will immediately
        // return with an EOF error.
        // We circumvent that situation here by not reporting an error and scheduling a read operation
        // later when we are sure data has been written at the offset in question (after the write finishes).
        if (errnr != ERROR_HANDLE_EOF)
#endif
        result = -1;
      }
#if defined (ACE_WIN32)
      else
      {
        this->read_pending_ = true;
      }
#endif
      // If read worked, psMsg is now controlled by Proactor framework.
    }
  }
  return result;
}