Ejemplo n.º 1
0
int
HTML_Body_Iterator::next (ACE_CString &url)
{
  size_t len = BUFSIZ;
  const char *buf;
  ACE_CString buffer;
  int href_index = 0;

  for (buf = this->url_.stream ().recv (len);
       buf > 0;
       buf = this->url_.stream ().recv (len))
    {

      buffer.set (buf, BUFSIZ, 1);

      href_index = ACE_Utils::truncate_cast<int> (buffer.find ("HREF"));

      if (href_index < 0)
        href_index = ACE_Utils::truncate_cast<int> (buffer.find ("href"));

      // Grep fpr " and grab the string until end-"
      if ( href_index > 0)
        {
          // Get back to buffer start location.
          this->url_.stream ().seek (-1 * static_cast<ACE_OFF_T> (len),
                                     SEEK_CUR);

          int start_index =
            ACE_Utils::truncate_cast<int> (
              buffer.find ('\"', href_index));

          if (start_index <= 0)
            break;

          start_index += href_index;

          int end_index =
            ACE_Utils::truncate_cast<int> (
              buffer.find ('\"', start_index + 1));

          if (end_index <= 0)
            break;

          end_index += start_index + 1;

          ssize_t url_len = end_index - (start_index + 1);

          ACE_CString temp = buffer.substring (start_index + 1,
                                               url_len);
          url.set (temp.c_str (), len, 1);

          this->url_.stream ().seek (end_index + 1);

          return url_len;
        }
    }
  return 0;

}
Ejemplo n.º 2
0
Server_Info_Ptr
Locator_Repository::get_active_server (const ACE_CString& name, int pid)
{
  sync_load ();
  ACE_CString key;
  Server_Info_Ptr si;
  if (name.length() == 0)
    {
      return si;
    }
  Server_Info::fqname_to_key (name.c_str(), key);
  servers ().find (key, si);
  if (si.null())
    {
      if (this->opts_.debug() > 5)
        {
          ORBSVCS_DEBUG ((LM_DEBUG,
                          ACE_TEXT ("(%P|%t) get_active_server could not find %C\n"),
                          name.c_str()));
        }
      si = find_by_poa (key);
      if (si.null())
        {
          if (name.find ("JACORB:") == ACE_CString::npos)
            {
              ACE_CString jo_key ("JACORB:");
              ACE_CString::size_type pos = name.find (':');
              if (pos == ACE_CString::npos)
                {
                  jo_key += name;
                }
              else
                {
                  jo_key += name.substring (0, pos);
                  jo_key += '/';
                  jo_key += name.substring (pos+1);
                }
              return this->get_active_server (jo_key, pid);
            }
          else
            {
              return si;
            }
        }
    }

  if (pid != 0 && si->pid != 0 && si->pid != pid)
    {
      if (this->opts_.debug() > 5)
        {
          ORBSVCS_DEBUG ((LM_DEBUG,
                          ACE_TEXT ("(%P|%t) get_active_server could not")
                          ACE_TEXT (" find %C, %d != %d\n"),
                          name.c_str(), pid, si->pid));
        }
      si.reset ();
    }
  return si;
}
Ejemplo n.º 3
0
Identifier::Identifier (const char *s)
  : pv_string (0),
    escaped_ (false)
{
  bool shift = false;

  if (*s == '_')
    {
      // Only one leading underscore is allowed.
      if (s[1] == '_')
        {
          idl_global->err ()->error0 (UTL_Error::EIDL_UNDERSCORE);
        }

      shift = true;
      this->escaped_ = true;
      ACE_CString str (s);
      const char *c_prefix = "_cxx_";

      if (str.find ("_tc_") == 0
          || str.find ("_tao_") == 0)
        {
          shift = false;
        }
      else if (str.find (c_prefix) == 0)
        {
          str = str.substr (ACE_OS::strlen (c_prefix));
          const char *eh_suffix = "_excep";
          ACE_CString::size_type pos =
            str.length () - ACE_OS::strlen (eh_suffix);

          // If we have an AMI exception holder suffix, strip it off.
          if (str.find (eh_suffix) == pos)
            {
              str = str.substr (0, pos);
            }

          TAO_IDL_CPP_Keyword_Table cpp_key_tbl;
          unsigned int len =
            static_cast<unsigned int> (str.length ());
          const TAO_IDL_CPP_Keyword_Entry *entry =
            cpp_key_tbl.lookup (str.c_str (), len);

          if (entry != 0)
            {
              shift = false;
            }
        }
    }

  if (shift)
    {
      this->pv_string = ACE::strnew (s + 1);
    }
  else
    {
      this->pv_string = ACE::strnew (s);
    }
}
Ejemplo n.º 4
0
bool BACIValue::fromString(const ACE_CString value, bool specifyType)
{

  ACE_CString strType;
  ACE_CString strContent;
  const char *szType;
  const char *szContent;
  unsigned long ulBound = 0;

  if (specifyType)
    {
      ACE_CString::size_type nPos0 = value.find('<');
      ACE_CString::size_type nPos1 = value.find(':');
      ACE_CString::size_type nPos2 = value.find('>');

      if((nPos1 != ACE_CString::npos) && (nPos1 < (nPos2-1)))
		ulBound = atoi(value.substr(nPos1+1, nPos2-nPos1-1).c_str());
      else
		nPos1 = nPos2;

      strType = value.substr(nPos0+1, nPos1-nPos0-1);
      strContent = value.substr(nPos2+1);
      szType = strType.c_str();
      szContent = strContent.c_str();

    }
  else
    {
      strType = typeName[type_m];
      strContent = value;
      szType = strType.c_str();
      szContent = strContent.c_str();
    }

/// User defined

  // special threathment for string (no conversion needed)
  if(strType.compare(BACIValue::typeName[type_string]) == 0)
    {
      if ((ulBound != 0) && (strContent.length() > ulBound))
	return false;
      if(!setType(type_string, ulBound))
	return 0;
      return stringValue(szContent);
    }

   PROCESS_INLINE_TYPE(double, BACIdouble)
   PROCESS_INLINE_TYPE(float, BACIfloat)
   PROCESS_INLINE_TYPE(long, BACIlong)
   PROCESS_INLINE_TYPE(longLong, BACIlongLong)
   PROCESS_INLINE_TYPE(uLongLong, BACIuLongLong)
//TBDeleted   PROCESS_INLINE_TYPE(pattern, BACIpattern)

  return false;

}
Ejemplo n.º 5
0
    bool GetCmdLine(const ACE_CString& input, ACE_CString& cmd, ACE_CString& remain_input)
    {
        if(input.find('\n') != ACE_TString::npos)
        {
            size_t pos = input.find('\n');
            cmd = input.substr(0, pos+1);
            size_t len = input.length();
            remain_input = input.substr(pos+1, len-pos+1);

            return true;
        }
        return false;
    }
Ejemplo n.º 6
0
UTL_ScopedName *
FE_Utils::string_to_scoped_name (const char *s)
{
  UTL_ScopedName *retval = 0;
  ACE_CString str (s);
  Identifier *id = 0;
  UTL_ScopedName *sn = 0;

  while (! str.empty ())
    {
      // Skip a leading double colon.
      if (str.find (':') == 0)
        {
          str = str.substr (2);
        }

      // Find the next double colon (if any) and get the next
      // name segment.
      ACE_CString::size_type pos = str.find (':');
      ACE_CString lname (str.substr (0, pos));

      // Construct a UTL_ScopedName segment.
      ACE_NEW_RETURN (id,
                      Identifier (lname.c_str ()),
                      0);

      ACE_NEW_RETURN (sn,
                      UTL_ScopedName (id, 0),
                      0);

      // Either make it the head of a new list or the tail of
      // an existing one.
      if (retval == 0)
        {
          retval = sn;
        }
      else
        {
          retval->nconc (sn);
        }

      // Update the working string.
      str = str.substr (pos);
    }

  return retval;
}
Ejemplo n.º 7
0
void
ImR_DSI_ResponseHandler::send_ior (const char *pior)
{
  ACE_CString ior = pior;

  // Check that the returned ior is the expected partial ior with
  // missing ObjectKey.
  if (ior.find ("corbaloc:") == 0 && ior[ior.length () -1] == '/')
    {
      ior += this->key_str_.in();

      CORBA::Object_var forward_obj = this->orb_->string_to_object (ior.c_str ());

      if (!CORBA::is_nil (forward_obj.in ()))
        {
          this->resp_->invoke_location_forward(forward_obj.in(), false);
          delete this;
          return;
        }
      else
        {
          if (ImR_Locator_i::debug () > 1)
            {
              ORBSVCS_ERROR ((LM_ERROR,
                          ACE_TEXT ("(%P|%t) ImR_DSI_ResponseHandler::send_ior (): Forward_to ")
                          ACE_TEXT ("reference is nil for key <%C> server_name <%C>\n"),
                          key_str_.in (), server_name_.in ()));
            }
        }
    }
  else
    {
      if (ImR_Locator_i::debug () > 1)
        {
          ORBSVCS_ERROR ((LM_ERROR,
                      ACE_TEXT ("(%P|%t) ImR_DSI_ResponseHandler::send_ior (): Invalid corbaloc ior for key <%C> server_name <%C> IOR <%C>\n"),
                      key_str_.in (), server_name_.in (), pior));
        }
    }

  this->invoke_excep_i (new CORBA::OBJECT_NOT_EXIST
                        (CORBA::SystemException::_tao_minor_code
                         ( TAO_IMPLREPO_MINOR_CODE, 0),
                         CORBA::COMPLETED_NO));
}
Ejemplo n.º 8
0
UTL_ScopedName *
ast_visitor_reifying::template_module_rel_name (AST_Decl *d)
{
  AST_Decl *tmp = d;
  ACE_CString name (d->full_name ());

  while (tmp != 0)
    {
      if (AST_Template_Module::narrow_from_decl (tmp) != 0)
        {
          ACE_CString head (tmp->local_name ()->get_string ());

          ACE_CString::size_type start = name.find (head) + 2;

          ACE_CString tail (name.substr (start + head.length ()));

          return FE_Utils::string_to_scoped_name (tail.c_str ());
        }

      tmp = ScopeAsDecl (tmp->defined_in ());
    }

  return 0;
}
Ejemplo n.º 9
0
UTL_ScopedName *
be_visitor_xplicit_pre_proc::xplicit_iface_rel_name (AST_Decl *d)
{
  AST_Decl *tmp = d;
  ACE_CString name (d->full_name ());

  while (tmp != 0)
    {
      if (be_home::narrow_from_decl (tmp) != 0)
        {
          ACE_CString head (tmp->local_name ()->get_string ());

          ACE_CString::size_type start = name.find (head) + 2;

          ACE_CString tail (name.substr (start + head.length ()));

          return FE_Utils::string_to_scoped_name (tail.c_str ());
        }

      tmp = ScopeAsDecl (tmp->defined_in ());
    }

  return 0;
}
Ejemplo n.º 10
0
// Given a comma separated list of preferred interface directives, which
// are of the form <wild_remote>=<wild_local>, this function will retrieve
// the list of preferred local ip addresses by matching wild_local against
// the list of all local ip interfaces, for any directive where wild_remote
// matches the host from our endpoint.
void
TAO_IIOP_Endpoint::find_preferred_interfaces (
  const ACE_CString &host,
  const ACE_CString &csvPreferred,
  ACE_Vector<ACE_CString> &preferred)
{
  ACE_Vector<ACE_CString> local_ips;
  TAO_IIOP_Endpoint_get_ip_interfaces (local_ips);
  if (local_ips.size () == 0)
    return;

  // The outer loop steps through each preferred interface directive
  // and chains a new endpoint if the remote interface matches the
  // current endpoint.
  ACE_CString::size_type index = 0;
  while (index < csvPreferred.length ())
    {
      ACE_CString::size_type comma = csvPreferred.find (',', index);
      ACE_CString::size_type assign = csvPreferred.find ('=', index);

      if (assign == ACE_CString::npos)
        {
          assign = csvPreferred.find (':', index);
          if (assign == ACE_CString::npos)
            {
              ACE_ASSERT (assign != ACE_CString::npos);
              return;
            }
        }

      ACE_CString wild_local;
      if (comma == ACE_CString::npos)
        wild_local = csvPreferred.substr (assign + 1);
      else
        wild_local = csvPreferred.substr (assign + 1, comma - assign - 1);
      ACE_CString wild_remote = csvPreferred.substr (index, assign - index);
      index = comma + 1;

      // For now, we just try to match against the host literally. In
      // the future it might be worthwhile to resolve some aliases for
      // this->host_ using DNS (and possibly reverse DNS) lookups. Then we
      // could try matching against those too.
      if (ACE::wild_match (host.c_str (), wild_remote.c_str (), false))
        {
          // If it's a match, then it means we need to use any/all
          // local interface(s) that matches wild_local.
          const char *const wild_local_cstr =  wild_local.c_str ();
          bool found= false;
          for (size_t i = 0u; i < local_ips.size (); ++i)
            {
              ACE_CString &ret = local_ips[i];
              if (ACE::wild_match (ret.c_str (), wild_local_cstr))
                {
                  found= true;
                  TAO_IIOP_Endpoint_none_duplicate_insert (ret, preferred);
                }
            }

          if (!found)
            {
#if defined (ACE_HAS_IPV6)
              // We interpret the preferred wild_local as an actual interface name/id.
              // This is useful for link local IPv6 multicast

              ACE_CString if_name ("if=");
              if_name += wild_local;
              TAO_IIOP_Endpoint_none_duplicate_insert (if_name, preferred);
#else
              // There is no matching local interface, so we can skip
              // to the next preferred interface directive.
#endif
            }
        }
      else
        {
          // The preferred interface directive is for a different
          // remote endpoint.
        }
      if (comma == ACE_CString::npos)
        break;
    }
}
Ejemplo n.º 11
0
int main(int argc, char *argv[])
{
    int c, instance = -1;
    ACE_CString daemonRef;
    ACE_CString hostName;
    ACE_CString additional;
    for (;;) {
	int option_index = 0;
	c = getopt_long(argc, argv, "hi:d:H:a:",
			long_options, &option_index);
	if (c == -1)
	    break;
	switch (c) {
	case 'h':
	    usage(argv[0]);
	    return 0;
	case 'i':
	    instance = ACE_OS::atoi(optarg);
	    break;
	case 'd':
	    daemonRef = optarg;
	    break;
	case 'H':
	    hostName = optarg;
	    break;
	case 'a':
	    additional = optarg;
	    break;
	}
    }
    if (instance == -1) {
	ACE_OS::printf("Error: instance is a mandatory option try %s -h\n",
		       argv[0]);
	return -1;
    }

	#define DEFAULT_LOG_FILE_NAME "acs_local_log"
	ACE_CString daemonsLogFileName = getTempFileName(0, DEFAULT_LOG_FILE_NAME);

	// replace "ACS_INSTANCE.x" with "acsdaemonStartAcs_" + <timestamp>
	ACE_CString daemonsDir = "acsdaemonStartAcs_" + getStringifiedTimeStamp();

	ACE_CString instancePart("ACS_INSTANCE.");
	ACE_CString::size_type pos = daemonsLogFileName.find(instancePart);
	daemonsLogFileName =
			daemonsLogFileName.substring(0, pos) +
			daemonsDir +
			daemonsLogFileName.substring(pos + instancePart.length() + 1);	// +1 for skipping instance number

	ACE_OS::setenv("ACS_LOG_FILE", daemonsLogFileName.c_str(), 1);

	LoggingProxy *logger = new LoggingProxy(0, 0, 31);
    if (logger) {
	LoggingProxy::init(logger);
	LoggingProxy::ProcessName(argv[0]);
	LoggingProxy::ThreadName("main");
    } else
	ACS_SHORT_LOG((LM_INFO, "Failed to initialize logging."));

    StartCallback* sc = new StartCallback();

    try {
	// Initialize the ORB.
	CORBA::ORB_var orb = CORBA::ORB_init(argc, argv, "TAO");

	// get a reference to the RootPOA
	CORBA::Object_var pobj = orb->resolve_initial_references("RootPOA");
	PortableServer::POA_var root_poa = PortableServer::POA::_narrow(pobj.in());
	PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();
      
	// create policies
	CORBA::PolicyList policy_list;
	policy_list.length(5);
	policy_list[0] = root_poa->create_request_processing_policy(PortableServer::USE_DEFAULT_SERVANT);
	policy_list[1] = root_poa->create_id_uniqueness_policy(PortableServer::MULTIPLE_ID);
	policy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID); 
	policy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN); 
	policy_list[4] = root_poa->create_lifespan_policy(PortableServer::PERSISTENT);
      
	// create a ACSDaemon POA with policies 
	PortableServer::POA_var poa = root_poa->create_POA("DaemonCallback", poa_manager.in(), policy_list);

	// destroy policies
	for (CORBA::ULong i = 0; i < policy_list.length(); ++i)
	    {
	    CORBA::Policy_ptr policy = policy_list[i];
	    policy->destroy();
	    }

	// set as default servant
	poa->set_servant(sc);

	// create reference
	PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId("DaemonCallback");
	pobj = poa->create_reference_with_id (oid.in(), sc->_interface_repository_id());
	CORBA::String_var m_ior = orb->object_to_string(pobj.in());

	// bind to IOR table
      	CORBA::Object_var table_object = orb->resolve_initial_references("IORTable");
	IORTable::Table_var adapter = IORTable::Table::_narrow(table_object.in());
      
	if (CORBA::is_nil(adapter.in()))
	    {
	    ACS_SHORT_LOG ((LM_ERROR, "Nil IORTable"));
	    return -1;
	    }
	else
	    {
	    adapter->bind("DaemonCallback", m_ior.in());
	    }

	// activate POA
	poa_manager->activate();

	ACS_SHORT_LOG((LM_INFO, "%s is waiting for incoming requests.", "DaemonCallback"));


	// construct default one
	if (daemonRef.length() == 0) {
	    if (hostName.length() == 0) {
		hostName = ACSPorts::getIP();
	    }
	    daemonRef = "corbaloc::";
	    daemonRef =
		daemonRef + hostName + ":" +
		ACSPorts::getServicesDaemonPort().c_str() +
		"/" + ::acsdaemon::servicesDaemonServiceName;
	    ACS_SHORT_LOG((LM_INFO,
			   "Using local ACS Services Daemon reference: '%s'",
			   daemonRef.c_str()));

	} else {
	    ACS_SHORT_LOG((LM_INFO,
			   "ACS Services Daemon reference obtained via command line: '%s'",
			   daemonRef.c_str()));
	}

	CORBA::Object_var obj = orb->string_to_object(daemonRef.c_str());
	if (CORBA::is_nil(obj.in())) {
	    ACS_SHORT_LOG((LM_INFO, "Failed to resolve reference '%s'.",
			   daemonRef.c_str()));
	    return -1;
	}

	acsdaemon::ServicesDaemon_var daemon =
	    acsdaemon::ServicesDaemon::_narrow(obj.in());
	if (CORBA::is_nil(daemon.in())) {
	    ACS_SHORT_LOG((LM_INFO, "Failed to narrow reference '%s'.",
			   daemonRef.c_str()));
	    return -1;
	}

	// @todo implement support for callback and wait for completion call
	acsdaemon::DaemonSequenceCallback_var dummyCallback = sc->_this();
	ACS_SHORT_LOG((LM_INFO, "Calling start_acs(%d, %s, dummyCallback).", instance,
		       additional.c_str()));
	daemon->start_acs(dummyCallback.in(), instance, additional.c_str());
	ACS_SHORT_LOG((LM_INFO, "ACS start message issued."));

	while(!sc->isComplete())
	{
	    if (orb->work_pending())
	        orb->perform_work();
	}
    }
    catch(ACSErrTypeCommon::BadParameterEx & ex) {
	ACSErrTypeCommon::BadParameterExImpl exImpl(ex);
	exImpl.log();
	return -1;
    }
    catch(CORBA::Exception & ex) {

	ACS_SHORT_LOG((LM_INFO, "Failed."));
	ex._tao_print_exception("Caught unexpected exception:");
	return -1;
    }

    return 0;
}
Ejemplo n.º 12
0
/*the accept function*/
static ACE_THR_FUNC_RETURN accept_step1(void *arg)
{
  /*ACE_INET_Addr addr;*/
  ACE_SOCK_Stream stream;
  ACE_HANDLE handle = (ACE_HANDLE)(intptr_t) arg;
  stream.set_handle(handle);
  if(stream.disable(ACE_NONBLOCK) == -1){
    ACE_ERROR_RETURN((LM_ERROR,
		      "%p\n","get_remote_addr"),0);
  }
  /*
  ACE_DEBUG ((LM_INFO,
              "(%P|%t) client %s connected from %d\n",
              addr.get_host_name (),
              addr.get_port_number ()));
  */
  char* buf = new char[128];
  ACE_CString* str = new ACE_CString();
  do{
    int bytes= stream.recv(buf,128);
    ACE_DEBUG((LM_INFO,
	       "(%P|%t:%l) bytes = %d\n",bytes));
    if(bytes == -1|| bytes == 0){
      break;
    }
    for(int i=0 ;i < bytes; i++){
      *str += buf[i];
    }
  }while(true);
  delete[] buf;
  
  //the input format is '^^pqr->v1$$';
  int pos = str->find("->");
  int tail = str->find("$$");
  ACE_CString* pqr = new ACE_CString(str->substr(2,pos-2));
  ACE_CString* pv1 = new ACE_CString(str->substr(pos+2, tail - pos - 2));
  ACE_DEBUG((LM_INFO,
	     "(%P|%t:%l) pqr: %s\n pv1:%s\n",pqr->c_str(),pv1->c_str()));
	     
  bn* _pqr = from_hex(pqr);
  bn* _v1 = from_hex(pv1);
  bn* _pr = from_hex(&pr);
  bn* _r = npmod( _v1, _pr, _pqr);

  ACE_CString* result = _r->to_hex();
  ACE_DEBUG((LM_INFO,
	     "(%P|%t:%l)pqr:%s step1:%s ", pqr->c_str(), result->c_str()));
  ACE_CString reply = ACE_CString("ack");
  stream.send(reply.c_str() , reply.length());
  stream.close();
  /*send the step1 result to hub:10007
  */
  ACE_SOCK_Connector connector;
  ACE_INET_Addr hub_addr(port,hub.c_str());
  ACE_DEBUG((LM_DEBUG,
	     "(%P|%t:%l) port:%d host:%s\n", port, hub.c_str()));
  if(connector.connect(stream, hub_addr) == -1){
    ACE_ERROR_RETURN ((LM_ERROR,
                       "(%P|%t) %p\n",
                       "connection failed"),
                      0);
  }
  else
    ACE_DEBUG ((LM_DEBUG,
                "(%P|%t) connected to %s at port %d\n",
                hub_addr.get_host_name (),
                hub_addr.get_port_number ()));

  /*
   * message layout:
^^pqr->digest->senderid$$
  */
  
  ACE_CString input = ACE_CString("^^");
  input += *pqr;
  input += "->";
  input += *result;
  input += "->";
  input += id ;
  input += "$$";
  ACE_DEBUG((LM_INFO,
	     "(%P|%t:%l) input of step1:%s\n", input.c_str()));
  
  if(stream.send(input.c_str(),input.length()) != input.length()){
    ACE_ERROR((LM_ERROR,
	       "%p\n","send"));
  }
  stream.close();
  delete str;
  delete pqr;
  delete pv1;
  delete _pqr;
  delete _v1;
  delete _pr;
  delete _r;
  delete result;
  return 0;
}
Ejemplo n.º 13
0
/*the repo function
  talk to the repo.jg.org at a regular interval, 1 minute,
  and send acknowledgement to repo.jg.org
 */
static ACE_THR_FUNC_RETURN
fetch_step2(void *){
  ACE_INET_Addr addr(repo_port, repo_host.c_str());
  ACE_SOCK_Connector con;
  ACE_SOCK_Stream stream;
  do{
  if(con.connect(stream, addr) == -1){
    ACE_ERROR_RETURN ((LM_ERROR,
                       "(%P|%t:%l) %p\n",
                       "connection failed"),
                      0);
  }
  else
    ACE_DEBUG ((LM_DEBUG,
                "(%P|%t:%l) connected to %s at port %d\n",
                addr.get_host_name (),
                addr.get_port_number ()));
  ACE_CString hb = ACE_CString("^^hb->");
  hb+=id+"$$";
  ACE_DEBUG((LM_INFO,
	     "%l: %s\n", hb.c_str()));
  
  stream.send(hb.c_str(),hb.length());
  stream.close_writer();
  ACE_DEBUG((LM_INFO,
	     "%l\n"));
  
  char* buf = new char[128];
  ACE_CString str;
  do{
    int bytes = stream.recv(buf,128);
    if(bytes == -1 || bytes == 0){
      break;
    }
    for(int i=0; i< bytes; i++){
      str += buf[i];
    }
  }while(true);
  delete[] buf;
  stream.close();

  ACE_CString acks = ACE_CString("^^");
  int p1=2;
  int p2= str.find("->",p1);
  int p3 = str.find("->",p2);
  int p4 = str.find("||",p3);
  node *head=NULL, *tail=NULL;
  while(p1 != -1 && p2 != -1 && p3 != -1){
    ACE_CString* pqr = new ACE_CString(str.substr(p1, p2 - p1));
    ACE_CString* v2 = new ACE_CString(str.substr(p2, p3 - p2));
    ACE_CString txn_id = str.substr(p3, p4 - p3);
    acks+="ack->"+txn_id+"||";
    node* n = new node(pqr, v2);
    if(head == NULL){
      head = n;
      tail = n;
    }else{
      tail->next = n;
      tail = n;
    }
  }
  acks+="$$";
  //  delete str;
  
  if(con.connect(stream, addr) == -1){
    ACE_ERROR_RETURN ((LM_ERROR,
                       "(%P|%t:%l) %p\n",
                       "connection failed"),
                      0);
  }
  else
    ACE_DEBUG ((LM_DEBUG,
                "(%P|%t:%l) connected to %s at port %d\n",
                addr.get_host_name (),
                addr.get_port_number ()));
  //send out the acks
  ACE_DEBUG((LM_INFO,
	     "(%P|%t:%l) %s\n",acks.c_str()));
  stream.send(acks.c_str(),acks.length());
  stream.close();
  node* tmp=head;
  //    ACE_SOCK_Connector connector;
  ACE_INET_Addr _9907addr(9907,"localhost");
  //ACE_SOCK_Stream stream;
  if(con.connect(stream, _9907addr) == -1){
    ACE_ERROR_RETURN((LM_ERROR,
		      "(%P|%t:%l) %p\n",
		      "connection failed"),0);
  }else
    ACE_DEBUG ((LM_DEBUG,
		"(%P|%t) connected to %s at port %d\n",
		_9907addr.get_host_name (),
		_9907addr.get_port_number ()));

  ACE_CString reply = ACE_CString("^^");
  while(tmp!=NULL){
    bn* pqr = from_hex(tmp->pqr);
    bn* v2 = from_hex(tmp->v2);
    bn* prv = from_hex(&pr);
    bn* res = npmod(v2,prv,pqr);
    ACE_CString* resStr = res->to_hex();
    /*send the output to localhost:9907*/
    reply += tmp->pqr->c_str();
    reply += "->" + *resStr + "||";
    ACE_DEBUG((LM_DEBUG,
	       "(%P|%t) %s\n",reply.c_str()));
    delete pqr;
    delete v2;
    delete prv;
    delete res;
    delete resStr;
    tmp = tmp->next;
  }
  reply += "$$";
  stream.send(reply.c_str(),reply.length());
  stream.close();
  reclaim_node(head);
  /*sleep for 1 second, for the next poll;*/
  ACE_OS::sleep(1000);
  }while(true);
  //  delete str;
}
Ejemplo n.º 14
0
int
TAO_ORB_Parameters::parse_and_add_endpoints (const ACE_CString &endpoints,
                                             TAO_EndpointSet &endpoint_set)
{
  // Parse the string into seperate endpoints, where `endpoints' is of
  // the form:
  //
  //    protocol1://V,v@addr1,...,addrN;protocol2://addr1,...,W.w@addrN;...
  //
  // A single endpoint, instead of several, can be added just as well.

  static char const endpoints_delimiter = ';';

  size_t const length = endpoints.length ();

  if (endpoints[0] == endpoints_delimiter ||
      endpoints[length - 1] == endpoints_delimiter)
    {
      return -1;
      // Failure: endpoints string has an empty endpoint at the
      // beginning or the end of the string
      // (e.g. ";uiop://foo;iiop://1.3@bar")
    }

  int status = 0;
  // Return code:  0 = success,  -1 = failure

  if (length > 0)
    {
      int endpoints_count = 1;

      for (size_t j = 0; j != length; ++j)
        {
          if (endpoints[j] == endpoints_delimiter)
            {
              ++endpoints_count;
            }
        }

      ssize_t begin = 0;
      ssize_t end = endpoints.find (endpoints_delimiter);

      for (int i = 0; i < endpoints_count; ++i)
        {
          if (end == 0)
            {
              // Handle case where two consecutive endpoints `;;'
              // delimiters are found within the endpoints set.
              //
              // Is it enough to just skip over it or should we return an
              // error?
              continue;
            }

          ACE_CString const endpt =
            endpoints.substring (begin, end - begin);
          // The substring call will work even if `end' is equal to
          // ACE_CString::npos since that will just extract the substring
          // from the offset `begin' to the end of the string.

          // Check for a valid URL style endpoint set
          ACE_CString::size_type const check_offset = endpt.find ("://");

          if (check_offset > 0 &&
              check_offset != endpt.npos)
            {
              endpoint_set.enqueue_tail (endpt);
              // Insert endpoint into list
            }
          else
            {
              status = -1;  // Error: invalid URL style endpoint set
            }

          begin = end + 1;
          end = endpoints.find (endpoints_delimiter, begin);
        }
    }
  else
    {
      status = -1;
      // Failure:  Empty string
    }

  return status;
}
Ejemplo n.º 15
0
CORBA::ULong
TAO_SCIOP_Endpoint::preferred_interfaces (TAO_ORB_Core *oc)
{
  ACE_CString tmp (
    oc->orb_params ()->preferred_interfaces ());

  ACE_CString::size_type pos = 0;

  pos = tmp.find (this->host_.in ());

  TAO_SCIOP_Endpoint *latest = this;

  CORBA::ULong count = 0;

  while (pos != ACE_CString::npos)
    {
      // Do we have a "," or an '\0'?
      ACE_CString::size_type new_pos = tmp.find (",", pos + 1);

      // Length of the preferred path
      ACE_CString::size_type length = 0;

      if (new_pos == ACE_CString::npos)
        length = tmp.length () - pos;
      else
        length = new_pos - pos;

      ACE_CString rem_tmp = tmp.substr (pos, length);

      // Search for the ":"
      ACE_CString::size_type col_pos = rem_tmp.find (":");

      if (col_pos == ACE_CString::npos)
        {
          pos = tmp.find (latest->host_.in (),
                          pos + length);
          continue;
        }

      ACE_CString path = rem_tmp.substr (col_pos + 1);

      latest->preferred_path_.host =
        CORBA::string_dup (path.c_str ());

      if (TAO_debug_level > 3)
        TAOLIB_DEBUG ((LM_DEBUG,
                    "(%P|%t) Adding path [%C] "
                    " as preferred path for [%C]\n",
                    path.c_str (), this->host_.in ()));

      pos = tmp.find (latest->host_.in (),
                      pos + length);

      if (pos != ACE_CString::npos)
        {
          TAO_Endpoint *tmp_ep =
            latest->duplicate ();

          latest->next_ = dynamic_cast<TAO_SCIOP_Endpoint *> (tmp_ep);

          if (latest->next_ == 0) return count;

          latest = latest->next_;
          ++count;
        }
    }

  if (tmp.length () != 0 &&
      !oc->orb_params ()->enforce_pref_interfaces ())
    {
      TAO_Endpoint *tmp_ep = latest->duplicate ();

      latest->next_ =
        dynamic_cast<TAO_SCIOP_Endpoint *> (tmp_ep);

      if (latest->next_ == 0) return count;

      latest->next_->preferred_path_.host = (const char *) 0;
      ++count;
    }

  return count;
}
Ejemplo n.º 16
0
// receive the heartbeat information, and return back the enquened messages;
static ACE_THR_FUNC_RETURN
commu(void* arg){
  ACE_INET_Addr addr;
  ACE_SOCK_Stream stream;
  ACE_HANDLE handle =(ACE_HANDLE)(intptr_t) arg;
  stream.set_handle(handle);
  if(stream.disable(ACE_NONBLOCK) == -1){
    ACE_ERROR_RETURN((LM_ERROR,
		      "%p\n","disable"),0);
  }
  else if(stream.get_remote_addr(addr)== -1){
    ACE_ERROR_RETURN((LM_ERROR,
		      "%p\n","get_remote_addr"),0);
  }
  ACE_DEBUG((LM_INFO,
	     "(%P|%t) client %s connected from %d\n",
	     addr.get_host_name(),addr.get_port_number()));
  ACE_CString str ;
  char* ch = new char[128];  
  do{
    int bytes = stream.recv(ch, 128);
    if(bytes == -1){
      ACE_ERROR((LM_ERROR,
		 "%p\n","recv"));
      break;
    }
    if(bytes == 0){
      ACE_DEBUG((LM_INFO,
		 "(%P|%t) reached end of input, connection closed by client\n"));
      break;
    }
    for(int i = 0; i< bytes; i++){
      str += ch[i];
    }
  }while(true);
  delete[] ch;
  ACE_DEBUG((LM_INFO,
	     "received message:%s\n", str.c_str()));
  
  /*
    the layout of the heartbeat message:
    ^^hb->senderid$$
   */
  /*if got a heartbeat message*/
  int pos = str.find("^^hb->");
  if( pos >= 0 ){
    int p2 = str.find("$$");
    ACE_CString id= str.substr(6, p2 -6);
    //    delete str;
    ACE_CString sql = "select pqr, v2,txn_id from step2 where recipient='"+ id +"' and transmitted='false' ";
    ACE_DEBUG((LM_DEBUG,
	       "%s\n", sql.c_str()));
    PGconn* con;
    PGresult* res;
    con = PQconnectdb("dbname=pq");
    if(PQstatus(con)!= CONNECTION_OK){
      ACE_DEBUG((LM_INFO,
		 "Connection to database failed:%s\n",
		 PQerrorMessage(con)));
      reclaim_conn(con);
    }
    res = PQexec(con, sql.c_str());
    int n = PQntuples(res);
    if(n == 0){
      /*no pending messages at all, exit immediately*/
      ACE_DEBUG((LM_INFO,
		 "(%P|%t) no pending messages at all\n"));
      PQclear(res);
      reclaim_conn(con);
      stream.close();
      //      delete str;
      return 0;
  }
    /*there are pending messages*/
    else{
      /* the reply message is in format "^^pqr1->v1->txn_id1||pqr2->v2->txn_id2||pqr3->v3->txn_id3||$$"*/
      ACE_CString reply = ACE_CString("^^");
      for(int i=0; i < n ; i++){
	reply += PQgetvalue(res, i, 0);
	reply += "->";
	reply += PQgetvalue(res, i, 1);
	reply += "->";
	reply += PQgetvalue(res, i, 2);
	reply += "||";
      }
      reply += "$$";
      PQclear(res);
      /*    reclaim_conn(con);
       */
      stream.send(reply.c_str(), reply.length());
      ACE_DEBUG((LM_INFO,
		 "(%P|%t:%l) %s\n", reply.c_str()));
      ACE_DEBUG((LM_INFO,
		 "(%P|%t) close the writer\n"));
      stream.close();
      //      delete str;
      return 0;
    }
  }
  
  /*if got an ack message
    '^^ack->txn_id2||ack->txn_id2||$$'
   */
  int p = str.find("^^ack->");
  if( p >= 0){
    PGconn* con;
    PGresult* res;
    con = PQconnectdb("dbname=pq");
    if(PQstatus(con)!= CONNECTION_OK){
      ACE_DEBUG((LM_INFO,
		 "Connection to database failed:%s\n",
		 PQerrorMessage(con)));
      reclaim_conn(con);
    }
    do{
      p += 7;
      int p2 = str.find("||",p);
      if(p2< 0){
	ACE_DEBUG((LM_INFO,
		   "reached the end of the txn_ids\n"));
	break;
      }
      ACE_CString txn_id = str.substr(pos, p2 - p);
      ACE_CString sql = ACE_CString("update step2 set transmitted=TRUE where txn_id='");
      sql += txn_id;
      sql += "'";
      ACE_DEBUG((LM_INFO,
	       "(%P|%t:%l) sql:%s\n" , sql.c_str()));
      res = PQexec(con, sql.c_str());
      PQclear(res);
      p = p2;
    }while(true);
    reclaim_conn(con);
    stream.close();
    //    delete str;
    return 0;
  }
  return 0;
}
Ejemplo n.º 17
0
void
Connection_Manager::load_ep_addr (const char* file_name)
{
  FILE* addr_file = ACE_OS::fopen (file_name, "r");

  if (addr_file == 0)
    {
      ACE_ERROR ((LM_DEBUG,
                  "Cannot open addr file %C\n",
                  file_name));
      return;
    }
  else
    ACE_DEBUG ((LM_DEBUG,
                "Addr file opened successfully\n"));

  while (1)
    {
      char buf [BUFSIZ];

      // Read from the file into a buffer


      /*
      int n = ACE_OS::fread (buf,
                             1,
                             BUFSIZ,
                             addr_file);
      */

      if ((ACE_OS::fgets (buf,BUFSIZ,addr_file)) == 0)
        {
          // At end of file break the loop and end the sender.
          if (TAO_debug_level > 0)
            ACE_DEBUG ((LM_DEBUG,"End of Addr file\n"));
          break;
        }


      if (TAO_debug_level > 0)
        ACE_DEBUG ((LM_DEBUG,
                    "%C\n",
                    buf));

      Endpoint_Addresses* addr;
      ACE_NEW (addr,
               Endpoint_Addresses);

      TAO_Tokenizer addr_tokenizer (buf,'/');

      ACE_CString flowname;

      if (addr_tokenizer [0] == 0)
        {
          ACE_ERROR ((LM_ERROR,
                      "Corresponding flow name not specified for endpoint addresses\n"));
          return;
        }
      else
        flowname += addr_tokenizer [0];

      if (addr_tokenizer [1] != 0)
        {
          ACE_CString token (addr_tokenizer [1]);

          ACE_CString::size_type pos = token.find ('\r');
          if (pos != ACE_CString::npos)
            {
              addr->sender_addr = CORBA::string_dup ((token.substr (0, pos)).c_str ());
            }
          else
            addr->sender_addr = CORBA::string_dup (token.c_str());

          pos = addr->sender_addr.find ('\n');
          if (pos != ACE_CString::npos)
            {
              addr->sender_addr = (addr->sender_addr.substr (0, pos)).c_str ();
            }
        }

      if (addr_tokenizer [2] != 0)
        {
          ACE_CString token (addr_tokenizer [2]);

          ACE_CString::size_type pos = token.find ('\r');
          if (pos != ACE_CString::npos)
            {
              addr->receiver_addr = CORBA::string_dup ((token.substr (0,pos)).c_str ());
            }
          else
            addr->receiver_addr = CORBA::string_dup (token.c_str());

          pos = addr->receiver_addr.find ('\n');
          if (pos != ACE_CString::npos)
            {
              addr->receiver_addr = (addr->receiver_addr.substr (0, pos)).c_str ();
            }
        }

      int result = ep_addr_.bind (flowname,
                                  addr);
      if (result == 0)
        {
          if (TAO_debug_level > 0)
            ACE_DEBUG ((LM_DEBUG,
                        "Flowname %C Bound Successfully\n",
                        flowname.c_str ()));
        }
      else if (result == 1)
        ACE_DEBUG ((LM_DEBUG,
                    "Flowname %C already exists\n",
                    flowname.c_str ()));
      else
        ACE_DEBUG ((LM_DEBUG,
                    "Flowname %C Bound Failed\n",
                    flowname.c_str ()));
    }
}
Ejemplo n.º 18
0
int
TAO_Connector::make_mprofile (const char *string, TAO_MProfile &mprofile)
{
  // This method utilizes the "Template Method" design pattern to
  // parse the given URL style IOR for the protocol being used
  // and create an mprofile from it.
  //
  // The methods that must be defined by all Connector sub-classes are:
  //      make_profile
  //      check_prefix

  // Check for a valid string
  if (!string || !*string)
    {
      throw ::CORBA::INV_OBJREF (
        CORBA::SystemException::_tao_minor_code (
          0,
          EINVAL),
        CORBA::COMPLETED_NO);
    }

  // Check for the proper prefix in the IOR.  If the proper prefix isn't
  // in the IOR then it is not an IOR we can use.
  if (this->check_prefix (string) != 0)
    {
      return 1;
      // Failure: not the correct IOR for this protocol.
      // DO NOT throw an exception here since the Connector_Registry
      // should be allowed the opportunity to continue looking for
      // an appropriate connector.
    }

  if (TAO_debug_level > 0)
    {
      TAOLIB_DEBUG ((LM_DEBUG,
                  ACE_TEXT ("TAO (%P|%t) - TAO_Connector::make_mprofile ")
                  ACE_TEXT ("<%C>\n"),
                  string));
    }

  ACE_CString ior;

  ior.set (string, ACE_OS::strlen (string), 1);

  // Find out where the protocol ends
  ACE_CString::size_type ior_index = ior.find ("://");

  if (ior_index == ACE_CString::npos)
    {
      throw ::CORBA::INV_OBJREF ();
      // No colon ':' in the IOR!
    }
  else
    {
      ior_index += 3;
      // Add the length of the colon and the two forward slashes `://'
      // to the IOR string index (i.e. 3)
    }

  // Find the object key
  const ACE_CString::size_type objkey_index =
    ior.find (this->object_key_delimiter (), ior_index);

  if (objkey_index == 0 || objkey_index == ACE_CString::npos)
    {
      throw ::CORBA::INV_OBJREF ();
      // Failure: No endpoints specified or no object key specified.
    }

  const char endpoint_delimiter = ',';
  // The delimiter used to separate individual addresses.

  // Count the number of endpoints in the IOR.  This will be the number
  // of entries in the MProfile.

  CORBA::ULong profile_count = 1;
  // Number of endpoints in the IOR  (initialized to 1).

  // Only check for endpoints after the protocol specification and
  // before the object key.
  for (ACE_CString::size_type i = ior_index; i < objkey_index; ++i)
    {
      if (ior[i] == endpoint_delimiter)
        ++profile_count;
    }

  // Tell the MProfile object how many Profiles it should hold.
  // MProfile::set(size) returns the number profiles it can hold.
  if (mprofile.set (profile_count) != static_cast<int> (profile_count))
    {
      throw ::CORBA::INV_OBJREF (
        CORBA::SystemException::_tao_minor_code (
          TAO_MPROFILE_CREATION_ERROR,
          0),
        CORBA::COMPLETED_NO);
      // Error while setting the MProfile size!
    }

  // The idea behind the following loop is to split the IOR into several
  // strings that can be parsed by each profile.
  // For example,
  //    `1.3@moo,shu,1.1@chicken/arf'
  // will be parsed into:
  //    `1.3@moo/arf'
  //    `shu/arf'
  //    `1.1@chicken/arf'

  ACE_CString::size_type begin = 0;
  ACE_CString::size_type end = ior_index - 1;
  // Initialize the end of the endpoint index

  for (CORBA::ULong j = 0; j < profile_count; ++j)
    {
      begin = end + 1;

      if (j < profile_count - 1)
        {
          end = ior.find (endpoint_delimiter, begin);
        }
      else
        {
          end = objkey_index;  // Handle last endpoint differently
        }

      if (end < ior.length () && end != ior.npos)
        {
          ACE_CString endpoint = ior.substring (begin, end - begin);

          // Add the object key to the string.
          endpoint += ior.substring (objkey_index);

          // The endpoint should now be of the form:
          //    `N.n@endpoint/object_key'
          // or
          //    `endpoint/object_key'

          TAO_Profile *profile =
            this->make_profile ();
          // Failure:  Problem during profile creation

          // Initialize a Profile using the individual endpoint
          // string.
          // @@ Not exception safe!  We need a TAO_Profile_var!
          profile->parse_string (endpoint.c_str ()
                                );

          // Give up ownership of the profile.
          if (mprofile.give_profile (profile) == -1)
            {
              profile->_decr_refcnt ();

              throw ::CORBA::INV_OBJREF (
                CORBA::SystemException::_tao_minor_code (
                  TAO_MPROFILE_CREATION_ERROR,
                  0),
                CORBA::COMPLETED_NO);
              // Failure presumably only occurs when MProfile is full!
              // This should never happen.
            }
        }
      else
        {
          throw ::CORBA::INV_OBJREF ();
          // Unable to separate endpoints
        }
    }

  return 0;  // Success
}
Ejemplo n.º 19
0
int main(int argc, char *argv[])
{

    CosNaming::NamingContext_var naming_context;
    int  nargc=0;
    char **nargv=0;
    const char *hn=ACSPorts::getIP();
    ACE_CString iorFile;

    if (argc>=2 && !ACE_OS_String::strcmp(argv[1], "-?")) {
        ACE_OS::printf ("USAGE: acsLogSvc  [-ORBInitRef NameService=iiop://yyy:xxxx/NameService] [-ORBEndpoint iiop://ip:port] [-o iorfile] [-silent]\n");
        return -1;
    }

// here we have to unset ACS_LOG_CENTRAL that we prevent filtering of log messages
    char *logCent=getenv("ACS_LOG_CENTRAL");
    if (logCent)
    {
        unsetenv("ACS_LOG_CENTRAL");
        printf("Unset ACS_LOG_CENTRAL which was previously set to %s\n", logCent);
    }//if

// create logging proxy
    LoggingProxy::ProcessName(argv[0]);
    ACE_Log_Msg::instance()->local_host(hn);
    LoggingProxy m_logger (0, 0, 31, 0);
    LoggingProxy::init (&m_logger);
    ACS_SHORT_LOG((LM_INFO, "Logging proxy successfully created !"));

    ACE_CString argStr;

    for(int i=1; i<argc; i++)
    {
        argStr += argv[i];
        argStr += " ";

        if (!ACE_OS_String::strcmp(argv[i], "-o") && (i+1)<argc)
        {
            iorFile = argv[i+1];
        }//if
    }//for

    if (argStr.find ("-ORBEndpoint")==ACE_CString::npos)
    {
        argStr = argStr + "-ORBEndpoint iiop://" + hn + ":" + ACSPorts::getLogPort().c_str();
    }

    ACS_SHORT_LOG((LM_INFO, "New command line is: %s", argStr.c_str()));

    ACE_OS::string_to_argv ((ACE_TCHAR*)argStr.c_str(), nargc, nargv);

    ACE_OS::signal(SIGINT,  TerminationSignalHandler);  // Ctrl+C
    ACE_OS::signal(SIGTERM, TerminationSignalHandler);  // termination request

    try
    {
        // Initialize the ORB
        ACE_OS::printf ("Initialising ORB ... \n");
        orb = CORBA::ORB_init (nargc, nargv, 0);
        ACE_OS::printf ("ORB initialsed !\n");
    }
    catch( CORBA::Exception &ex )
    {
        ex._tao_print_exception("Failed to initalise ORB");
        return -1;
    }


    if (!ACSError::init(orb.in()))
    {
        ACS_SHORT_LOG ((LM_ERROR, "Failed to initalise the ACS Error System"));
        return -1;
    }

// resolve naming service
    try
    {
        ACS_SHORT_LOG((LM_INFO, "Trying to connect to the Naming Service ...."));
        CORBA::Object_var naming_obj = orb->resolve_initial_references ("NameService");

        if (!CORBA::is_nil (naming_obj.in ()))
        {
            naming_context = CosNaming::NamingContext::_narrow (naming_obj.in ());
            ACS_SHORT_LOG((LM_INFO, "Connected to the Name Service"));
        }
        else
        {
            ACS_SHORT_LOG((LM_ERROR, "Could not connect the Name Service!"));
            return -1;
        }//if-else
    }
    catch( CORBA::Exception &_ex )
    {
        ACS_SHORT_LOG((LM_ERROR, "Could not connect the Name Service!"));
        return -1;
    }


    // logging service
    try
    {
        CORBA::Object_var log_obj;
        /*
              if (argStr.find ("-ORBInitRef NameService=")!=ACE_CString::npos)
        	{
        	// Initialize the ORB
        	ACE_OS::printf ("Initialising ORB ... \n");
        	orb = CORBA::ORB_init (nargc, nargv, 0);
        	ACE_OS::printf ("ORB initialsed !\n");
                //Naming Service
        	ACE_OS::printf ("Resolving  Naming service ... \n");
        	CORBA::Object_var naming_obj =
        	  orb->resolve_initial_references ("NameService");
        	if (!CORBA::is_nil (naming_obj.in ()))
        	  {
        	    CosNaming::NamingContext_var naming_context =
        	      CosNaming::NamingContext::_narrow (naming_obj.in ());
        	    ACE_OS::printf ( "Naming Service resolved !\n");
        */

        ACE_OS::printf ( "Resolving Logging Service from Naming service ...\n");
        CosNaming::Name name;
        name.length(1);
        name[0].id = CORBA::string_dup("Log");
        log_obj = naming_context->resolve(name);
        /*
          }
        	else
        	  {
        	    ACS_LOG(LM_SOURCE_INFO, "main", (LM_ERROR,  "Failed to initialise the Name Service!"));
        	  }
        	}//if naming Service

              else
        	{
        	ACE_OS::printf ("Getting Log from the Manager... \n");
        	CORBA::ULong status;
        	maci::Manager_ptr manager = maci::MACIHelper::resolveManager (orb.in(), nargc, nargv, 0, 0);


        	log_obj = manager->get_COB(0, "Log", true,  status);
        	}
        */
        if (!CORBA::is_nil (log_obj.in()))
        {
            Logging::AcsLogService_var logger = Logging::AcsLogService::_narrow(log_obj.in());
            ACE_OS::printf ( "Logging Service resolved !\n");

            m_logger.setCentralizedLogger(logger.in());
        }
        else
        {
            ACS_LOG(LM_SOURCE_INFO, "main", (LM_ERROR, "Failed to initialise the Logging Service!"));
            return -1;
        }//if-else
    }
    catch( CORBA::Exception &__ex )
    {
        __ex._tao_print_exception("Failed to get and set the centralized logger");
        return -1;
    }


    try
    {
        //Get a reference to the RootPOA
        ACE_OS::printf("Creating POA ... \n");
        CORBA::Object_var obj = orb->resolve_initial_references("RootPOA");

        PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in());


        PortableServer::POAManager_var poa_manager = root_poa->the_POAManager();


        CORBA::PolicyList policy_list;
        policy_list.length(5);
        policy_list[0] = root_poa->create_request_processing_policy (PortableServer::USE_DEFAULT_SERVANT);

        policy_list[1] =  root_poa->create_id_uniqueness_policy (PortableServer::MULTIPLE_ID);

        policy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID);

        policy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN);

        policy_list[4] =  root_poa->create_lifespan_policy (PortableServer::PERSISTENT);

        printf("policies are created !\n");

        PortableServer::POA_var poa = root_poa->create_POA("ACSLogSvc", poa_manager.in(), policy_list);

        ACE_OS::printf("POA created !\n");

        for (CORBA::ULong i = 0; i < policy_list.length (); ++i) {
            CORBA::Policy_ptr policy = policy_list[i];
            policy->destroy ();

        }
        printf("Policies are destroyed !\n");

        ACSLogImpl acsLogSvc (m_logger);
        poa->set_servant (&acsLogSvc);


        PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId ("ACSLogSvc");
        obj = poa->create_reference_with_id (oid.in(),  acsLogSvc._interface_repository_id());


        CORBA::String_var ior = orb->object_to_string (obj.in());


        // if ther is file name write ior in it
        if (iorFile.length()!=0)
        {
            FILE *output_file = ACE_OS::fopen (iorFile.c_str(), "w");
            if (output_file == 0)
            {
                ACS_SHORT_LOG ((LM_ERROR,
                                "Cannot open output files for writing IOR: ior.ior"));
                return  -1;
            }//if

            int result = ACE_OS::fprintf (output_file, "%s", ior.in());
            if (result < 0)
            {
                ACS_SHORT_LOG ((LM_ERROR,
                                "ACE_OS::fprintf failed while writing %s to ior.ior", ior.in()));
                return  -1;
            }//if
            ACE_OS::fclose (output_file);
            ACS_SHORT_LOG((LM_INFO, "ACSLogSvc's IOR has been written into: %s", iorFile.c_str()));
        }//if


// adding ACSLog to NamingService
        if (!CORBA::is_nil (naming_context.in ()))
        {
            // register cdb server in Naming service
            CosNaming::Name name (1);
            name.length (1);
            name[0].id = CORBA::string_dup ("ACSLogSvc");
            naming_context->rebind (name, obj.in ());
            ACS_SHORT_LOG((LM_INFO, "ACSLogSvc service registered with Naming Services"));
        }//if

        CORBA::Object_var table_object =
            orb->resolve_initial_references ("IORTable");

        IORTable::Table_var adapter =
            IORTable::Table::_narrow (table_object.in ());

        if (CORBA::is_nil (adapter.in ()))
        {
            ACS_SHORT_LOG ((LM_ERROR, "Nil IORTable"));
        }
        else
        {
            adapter->bind ("ACSLogSvc", ior.in ());
        }

        poa_manager->activate ();


        ACS_SHORT_LOG((LM_INFO, "ACSLogSvc is waiting for incoming log messages ..."));
        if (argStr.find ("-ORBEndpoint")!=ACE_CString::npos)
            m_logger.setStdio(31);
        orb->run ();

        ACSError::done();
        LoggingProxy::done();
    }
    catch( CORBA::Exception &ex )
    {
        ex. _tao_print_exception("EXCEPTION CAUGHT");
        return -1;
    }

    return 0;
}
Ejemplo n.º 20
0
static ACE_THR_FUNC_RETURN
process(void* arg){
  ACE_INET_Addr addr;
  ACE_SOCK_Stream stream;
  ACE_HANDLE handle = (ACE_HANDLE) (intptr_t) arg;
  stream.set_handle(handle);
  /*make sure we're not in non-blocking mode.*/
  if(stream.disable(ACE_NONBLOCK) == -1){
    ACE_ERROR_RETURN ((LM_ERROR,
		       "%p\n",
		       "disable"),
		      0);
  }
  else if(stream.get_remote_addr(addr) == -1){
    ACE_ERROR_RETURN ((LM_ERROR,
		       "%p\n",
		       "get_remote_addr"),
		      0);
  }
  ACE_DEBUG ((LM_INFO,
	      "(%P|%t:%l) client %s connected from %d\n",
	      addr.get_host_name (),
	      addr.get_port_number ()));
  
  int r_bytes = 0;
  char buf[SIZE];
  ACE_CString cs;
  do{
    r_bytes = stream.recv(buf, SIZE);

    if(r_bytes == 0 || r_bytes == -1){
      ACE_DEBUG((LM_INFO,
		 "(%P|%t:%l) r_bytes = %d, exit from the loop\n", r_bytes));
      break;
    }
    for(int i=0; i< r_bytes; i++){
      cs += buf[i];
    }
  }while(true);
  stream.close_reader();
  /*
  ACE_DEBUG((LM_INFO,
	     "%s\n", cs.c_str()));
  */
  /*the layout of the message would be:
   * ^^pq||step1$$
   * 1st step: get the d by pq
   * 2nd calculate
   * 3rd send back the digest
   */
  int p0, p1;
  int len = cs.length();
  p0 = 2;
  p1 = cs.find("||");
  ACE_CString pq = cs.substr(2, p1 - 2);
  ACE_CString step1 = cs.substr(p1 + 2, len - p1 -4);
  /*
  ACE_DEBUG((LM_INFO,
	     "pq = %s\n step1 = %s\n", pq.c_str(), step1.c_str()));
  */
  //get the d
  ACE_CString sql = "select d,textid from player0 where pq='";
  sql += pq;
  sql += "'";
  /*
  ACE_DEBUG((LM_INFO,
	     "sql = %s\n", sql.c_str()));
*/
  PGconn* con;
  con = PQconnectdb("host=45.33.3.188 port=5432 dbname=nv user=dec");
  PGresult* res;
  if(PQstatus(con)!= CONNECTION_OK){
    ACE_DEBUG((LM_INFO,
	       "Connection to database failed:%s\n",
	       PQerrorMessage(con)));
    reclaim_conn(con);
  }
  res = PQexec(con, sql.c_str());
  int n = PQntuples(res);
  if(n != 1){
    ACE_ERROR((LM_ERROR,
	       "there is significant error: %d\n", n));
    //    return 0;
  }
  ACE_CString d = "";
  d += PQgetvalue(res, 0, 0);
  /*
  ACE_DEBUG((LM_INFO,
	     "d = %s\n", d.c_str()));
*/
  bn* pq_ = from_hex(&pq);
  bn* d_ = from_hex(&d);
  bn* step1_ = from_hex(&step1);
  bn* step2_ = npmod(step1_ , d_ , pq_ );
  ACE_CString* step2 = step2_->to_hex();
  
  //check if the pq is taking the ownnership?

  /* if pq is 'centralbank', bypass the check, otherwise check the payer whether has the ownnership of the note;
   * select count(*) from ownership0 o, player0 p where o.owner = p.textid  and o.note='0x12345678' and p.pq='0x12345678';
   */
  bn* e_ = new bn(1);
  e_->addat(0,0x10001);
  bn* step3_ = npmod(step2_ , e_ , pq_ );
  ACE_CString* rawMsg = encode(step3_);
  ACE_DEBUG((LM_INFO,
	     "%T :%l step3 = %s\n", rawMsg->c_str()));
  if(verify_ownership(rawMsg, pq)){
    //update the ownership;
    int pos1 = rawMsg->find("->");
    ACE_CString note = rawMsg->substr(2, pos1 -2);
    int rawlen = rawMsg->length();
    ACE_CString id = rawMsg->substr(pos1 + 2, rawlen - pos1 - 6);
    update_ownership(note, id);
    /*insert the log entry*/
    insert_logentry(pq, *step2, *rawMsg, note, id);
    stream.send( step2->c_str(), step2->length());
    /*
    ACE_DEBUG((LM_INFO,
	       "%T :%l the step2 message is:\n%s\n", step2->c_str()));
    */
  }else{
    ACE_DEBUG((LM_INFO,
	       "%T :%l invalid transfer\n"));
    ACE_CString reply ="invalid transfer\n";
    stream.send( reply.c_str(), reply.length());
  }
  delete step2 ;
  delete pq_;
  delete d_;
  delete step1_;
  delete step2_;
  delete e_;
  delete step3_;
  delete rawMsg;
  /*
  stream.close_writer();
  */
  stream.close();
  ACE_DEBUG((LM_INFO,
	     "%T :%l closed the stream\n"));

}