Пример #1
0
int
bg_ssdp_has_service(const bg_ssdp_root_device_t * dev, const char * type,
                    int version, int * dev_index, int * srv_index)
  {
  int idx, i;

  idx = lookup_service(dev->services, dev->num_services, type, version);

  if(idx >= 0)
    {
    if(dev_index)
      *dev_index = -1;

    if(srv_index)
      *srv_index = idx;
    return 1;
    }

  for(i = 0; i < dev->num_devices; i++)
    {
    idx = lookup_service(dev->devices[i].services, dev->devices[i].num_services, type, version);

    if(idx >= 0)
      {
      if(dev_index)
        *dev_index = i;
      
      if(srv_index)
        *srv_index = idx;
      return 1;
      }
    }
  return 0;
  }
Пример #2
0
resource_service_fn_t *rs_simple_create(void *arg, tbx_inip_file_t *kf, char *section)
{
    service_manager_t *ess = (service_manager_t *)arg;
    rs_simple_priv_t *rss;
    resource_service_fn_t *rs;

    //** Create the new RS list
    tbx_type_malloc_clear(rss, rs_simple_priv_t, 1);

    assert_result(apr_pool_create(&(rss->mpool), NULL), APR_SUCCESS);
    apr_thread_mutex_create(&(rss->lock), APR_THREAD_MUTEX_DEFAULT, rss->mpool);
    apr_thread_mutex_create(&(rss->update_lock), APR_THREAD_MUTEX_DEFAULT, rss->mpool);
    apr_thread_cond_create(&(rss->cond), rss->mpool);
    rss->rid_mapping = apr_hash_make(rss->mpool);
    rss->mapping_updates = apr_hash_make(rss->mpool);

    rss->ds = lookup_service(ess, ESS_RUNNING, ESS_DS);
    rss->da = lookup_service(ess, ESS_RUNNING, ESS_DA);

    //** Set the resource service fn ptrs
    tbx_type_malloc_clear(rs, resource_service_fn_t, 1);
    rs->priv = rss;
    rs->get_rid_config = rss_get_rid_config;
    rs->register_mapping_updates = rss_mapping_register;
    rs->unregister_mapping_updates = rss_mapping_unregister;
    rs->translate_cap_set = rss_translate_cap_set;
    rs->query_new = rs_query_base_new;
    rs->query_dup = rs_query_base_dup;
    rs->query_add = rs_query_base_add;
    rs->query_append = rs_query_base_append;
    rs->query_destroy = rs_query_base_destroy;
    rs->query_print = rs_query_base_print;
    rs->query_parse = rs_query_base_parse;
    rs->get_rid_value = rs_simple_get_rid_value;
    rs->data_request = rs_simple_request;
    rs->destroy_service = rs_simple_destroy;
    rs->type = RS_TYPE_SIMPLE;

    //** This is the file to use for loading the RID table
    rss->fname = tbx_inip_get_string(kf, section, "fname", NULL);
    rss->dynamic_mapping = tbx_inip_get_integer(kf, section, "dynamic_mapping", 0);
    rss->check_interval = tbx_inip_get_integer(kf, section, "check_interval", 300);
    rss->check_timeout = tbx_inip_get_integer(kf, section, "check_timeout", 60);
    rss->min_free = tbx_inip_get_integer(kf, section, "min_free", 100*1024*1024);

    //** Set the modify time to force a change
    rss->modify_time = 0;

    //** Load the RID table
    assert_result(_rs_simple_refresh(rs), 0);

    //** Launch the check thread
    tbx_thread_create_assert(&(rss->check_thread), NULL, rss_check_thread, (void *)rs, rss->mpool);

    return(rs);
}
Пример #3
0
gint ConnmanManager::delete_service(const gchar *a_object_path) {

	ConnmanService *service = NULL;

	DBG3();

	if(a_object_path == NULL) {

		ERR("no object path.");
		return -1;
	}

	if(m_services == NULL) {

		ERR("no services available.");
		return -1;
	}

	service = lookup_service(a_object_path);
	if(service == NULL) {

		DBG("service does not exists.", a_object_path);
		return 0;
	}

	DBG("delete service '%s'.", a_object_path);
	g_hash_table_remove(m_services, a_object_path);
	delete service;

	return 0;
}
Пример #4
0
gint ConnmanManager::add_service(ConnmanService *a_service) {

	ConnmanService *service = NULL;
	gint ret = 0;

	DBG3();

	if(a_service == NULL) {

		ERR("no connman service '%p'", a_service);
		return -1;
	}

	if(m_services == NULL) {

		ERR("no services available.");
		return -1;
	}

	service = lookup_service(a_service->get_object_path());
	if(service != NULL) {

		DBG("service '%s' already exists.", service->get_object_path());
		return 0;
	}

	DBG("add new service '%s'.", a_service->get_object_path());
	g_hash_table_insert(m_services, (gchar *)a_service->get_object_path(), a_service);

	return 0;
}
Пример #5
0
segment_t *load_segment(service_manager_t *ess, ex_id_t id, exnode_exchange_t *ex)
{
    char *type = NULL;
    char name[1024];
    segment_load_t *sload;

    if (ex->type == EX_TEXT) {
        snprintf(name, sizeof(name), "segment-" XIDT, id);
        inip_file_t *fd = ex->text.fd;
        type = inip_get_string(fd, name, "type", "");
    } else if (ex->type == EX_PROTOCOL_BUFFERS) {
        log_printf(0, "load_segment:  segment exnode parsing goes here\n");
    } else {
        log_printf(0, "load_segment:  Invalid exnode type type=%d for id=" XIDT "\n", ex->type, id);
        return(NULL);
    }

    sload = lookup_service(ess, SEG_SM_LOAD, type);
    if (sload == NULL) {
        log_printf(0, "load_segment:  No matching driver for type=%s  id=" XIDT "\n", type, id);
        return(NULL);
    }

    free(type);
    return((*sload)(ess, id, ex));
}
Пример #6
0
void broker_t::handle_receiver(message_pack_t &msg) {
    std::string receiver;
    msg.pop_head(receiver);

    // get or create recipient
    recipient_ptr_t recipient = lookup_recipient(receiver);
    message_part_t command = msg.pop_head();
    if(message::equal_to(*command, codes::control::receiver::ready)) {
        recipient->update_expiration(next_expiration());

        std::string service_name;
        msg.pop_head(service_name);

        // get or create a service and attach recipient
        service_ptr_t service = lookup_service(service_name);
        service->attach_waiter(recipient);
        service->dispatch(m_socket);
    }
    else if(message::equal_to(*command, codes::control::receiver::heartbeat)) {
        recipient->update_expiration(next_expiration());
    }
    else if(message::equal_to(*command, codes::control::receiver::disconnect)) {
        recipient->disconnect();
        m_recipients.erase(receiver);
    }
    else {
        recipient->disconnect(); // we don't need a problem
        throw runtime_error_t("%s", "Message discarded (command part is corrupted)");
    }
}
Пример #7
0
gint ConnmanManager::verdict_ho(const gchar *a_object_path) {

	ConnmanService *service = NULL;
	gint err = 0;
	DBG3();

	g_static_mutex_lock(&services_mutex);

	service = lookup_service(a_object_path);
	if(service == NULL) {

		ERR("service does not exists.", a_object_path);
		err = -1;
		goto end;
	}

	DBG("object path '%s'.", a_object_path);
	if(service->get_active_service() == NULL) {

		ERR("no active service.");
		err = -1;
		goto end;
	}
	else if(service == service->get_active_service()) {

		DBG("service already connected");
		err = 0;
		goto end;
	}

	if((service->get_state() == StateIdle) || (service->get_state() == StateAssociation)) {

		err = service->connect_sync();
		if(err < 0) {

			ERR("connecting");
			goto end;
		}
	}

	if(service->get_state() == StateReady) {

		DBG("active service '%s'", service->get_active_service()->get_object_path());
		err = service->move_before(service->get_active_service()->get_object_path());
		if(err < 0) {

			ERR("handover");
			goto end;
		}
	}

	end:

	g_static_mutex_unlock(&services_mutex);

	return err;
}
Пример #8
0
ConnmanService* ConnmanManager::create_service(const gchar *a_object_path) {

	ConnmanService *service = NULL;
	gint ret = 0;

	DBG3();

	if(a_object_path == NULL) {

		ERR("no object path.");
		return NULL;
	}

	DBG("object path '%s'.", a_object_path);

	if(m_services == NULL) {

		m_services = g_hash_table_new(g_str_hash, g_str_equal);
		if(m_services == NULL) {

			ERR("cannot create hash table for services.");
			return NULL;
		}
	}

	service = lookup_service(a_object_path);
	if(service != NULL) {

		DBG("service '%s' already exists.", a_object_path);
		return service;
	}

	DBG("create new service '%s'.", a_object_path);
	service = new ConnmanService(get_service_name(), a_object_path, CONNMAN_SERVICE_INTERFACE);
	if(service == NULL) {

		ERR("cannot allocate new connman service.");
		return NULL;
	}

	ret = service->create_service_sync();
	if(ret < 0) {

		ERR("cannot create new connman service.");
		delete service;
		return NULL;
	}

	return service;
}
Пример #9
0
void broker_t::handle_sender(message_pack_t& msg) {

    message_part_t command = msg.pop_head();
    if(!message::equal_to(*command, codes::control::sender::put)) {
        throw runtime_error_t("%s", "Message discarded (command part is corrupted)");
    }

    std::string service_name;
    msg.pop_head(service_name);

    // get or create a service
    service_ptr_t service = lookup_service(service_name);

    // the rest of the message is a payload
    service->append_message(std::move(msg));
    service->dispatch(m_socket);
}
Пример #10
0
gint ConnmanManager::request_services_sync() {

	GVariant *ret = NULL;
	GVariantIter *iter, *iter2;
	gchar *object_path;
	GVariant *dict = NULL;
	gsize length = 0;
	ConnmanService *service = NULL, *active_service = NULL;
	GList *list_networks_update = NULL;
	GList *list_networks_invalid = NULL;
	INetwork *network = NULL;
	gint i = 0;
	gboolean first_service = TRUE;

	DBG3();

	ret = call_sync("GetServices", NULL);
	if(ret == NULL) {

		ERR("call error.");
		return -1;
	}

	g_static_mutex_lock(&services_mutex);

	DBG("reply '%p'", ret);

	g_variant_get(ret, "(a(oa{sv}))", &iter);
	while(g_variant_iter_loop(iter, "(oa{sv})", &object_path, &iter2)) {

		gchar *key;
		GVariant *value;

		DBG("service '%s'", object_path);
		service = lookup_service(object_path);
		if(service == NULL) {

			DBG("service '%s' does not yet exist, create one.", object_path);
			service = create_service(object_path);
			if(service != NULL) {

				add_service(service);
				service->set_updated(TRUE);
			}
			else {
				ERR("creating service.");
				continue;
			}
		}
		else {

			DBG("service '%s' exist, update values.", object_path);
		}

		if(first_service == TRUE) {

			first_service = FALSE;
			active_service = service;
		}

		service->set_active_service(active_service);

		while(g_variant_iter_loop(iter2, "{sv}", &key, &value)) {

			if(g_strcmp0(key, "Type") == 0) {

				if(value && g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {

					const gchar *help = g_variant_get_string(value, &length);
					eRat rat = string2Rat(help);
					DBG3("Type string '%s', enum '%u'", help, rat);
					service->set_rat(rat);

				}
				else {

					ERR("parsing 'Type'");
				}
			}
			else if(g_strcmp0(key, "Name") == 0) {

				if(value && g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {

					const gchar *help = g_variant_get_string(value, &length);
					DBG3("Name '%s'", help);
					service->set_name(help);
				}
				else {

					ERR("parsing 'Name'");
				}
			}
			else if(g_strcmp0(key, "State") == 0) {

				if(value && g_variant_is_of_type(value, G_VARIANT_TYPE_STRING)) {

					const gchar *help = g_variant_get_string(value, &length);
					DBG3("State string '%s', enum '%u'", help, string2State(help));
					service->set_state(string2State(help));
				}
				else {

					ERR("parsing 'State'");
				}
			}
			else if(g_strcmp0(key, "Strength") == 0) {

				if(value && g_variant_is_of_type(value, G_VARIANT_TYPE_BYTE)) {

					guint8 help = g_variant_get_byte(value);
					DBG3("Strength '%u'", help);
					service->set_strength(help);
				}
				else {

					ERR("parsing 'Strength'");
				}
			}

		} // End dictionary/ one service

		i++;
		/* set service as visited, to delete invalid services afterwards. */
		service->set_visited(TRUE);

		/* create network */
		if(service->get_updated() == FALSE)
			continue;

		if((service->get_rat() == RatWifi)) {

			DBG2("Network wifi");

			network = new Wlan(service->get_object_path());
			if(network == NULL) {

				ERR("network '%s' with object path '%s'", rat2String(RatWifi), service->get_object_path());
				delete network;
				continue;
			}

		}
		else if(service->get_rat() == RatQmi) {

			DBG2("Network qmi");

			network = new Qmi(service->get_object_path());
			if(network == NULL) {

				ERR("network '%s' with object path '%s'", rat2String(RatQmi), service->get_object_path());
				delete network;
				continue;
			}

		}
		else {

			continue;
		}

		service->set_updated(FALSE);
		network->set_strength(service->get_strength());
		network->set_strength_average((service->get_strength_average()));
		network->set_state(service->get_state());
		network->set_name((service->get_name()));
		list_networks_update = g_list_prepend(list_networks_update, network);


	} // End all services

	DBG2("NETWORKS '%d'", i);
	/* delete not visited (invalid) services and set visited to FALSE */
	list_networks_invalid = delete_invalid_services();
	DataStorage::get_instance()->update_networks(list_networks_update, list_networks_invalid);

	g_static_mutex_unlock(&services_mutex);

	g_list_free(list_networks_update);
	g_list_free(list_networks_invalid);
	g_variant_iter_free(iter);
	g_variant_unref(ret);

	return 0;
}
Пример #11
0
void ares_getnameinfo(ares_channel channel, const struct sockaddr *sa,
                      ares_socklen_t salen,
                      int flags, ares_nameinfo_callback callback, void *arg)
{
  struct sockaddr_in *addr = NULL;
  struct sockaddr_in6 *addr6 = NULL;
  struct nameinfo_query *niquery;
  unsigned int port = 0;

  /* Verify the buffer size */
  if (salen == sizeof(struct sockaddr_in))
    {
      addr = (struct sockaddr_in *)sa;
      port = addr->sin_port;
    }
  else if (salen == sizeof(struct sockaddr_in6))
    {
      addr6 = (struct sockaddr_in6 *)sa;
      port = addr6->sin6_port;
    }
  else
    {
      callback(arg, ARES_ENOTIMP, 0, NULL, NULL);
      return;
    }

  /* If neither, assume they want a host */
  if (!(flags & ARES_NI_LOOKUPSERVICE) && !(flags & ARES_NI_LOOKUPHOST))
    flags |= ARES_NI_LOOKUPHOST;

  /* All they want is a service, no need for DNS */
  if ((flags & ARES_NI_LOOKUPSERVICE) && !(flags & ARES_NI_LOOKUPHOST))
    {
      char buf[33], *service;

      service = lookup_service((unsigned short)(port & 0xffff),
                               flags, buf, sizeof(buf));
      callback(arg, ARES_SUCCESS, 0, NULL, service);
      return;
    }

  /* They want a host lookup */
  if ((flags & ARES_NI_LOOKUPHOST))
    {
     /* A numeric host can be handled without DNS */
     if ((flags & ARES_NI_NUMERICHOST))
      {
        char ipbuf[IPBUFSIZ];
        char srvbuf[33];
        char *service = NULL;
        ipbuf[0] = 0;

        /* Specifying not to lookup a host, but then saying a host
         * is required has to be illegal.
         */
        if (flags & ARES_NI_NAMEREQD)
          {
            callback(arg, ARES_EBADFLAGS, 0, NULL, NULL);
            return;
          }
        if (salen == sizeof(struct sockaddr_in6))
          {
            ares_inet_ntop(AF_INET6, &addr6->sin6_addr, ipbuf, IPBUFSIZ);
            /* If the system supports scope IDs, use it */
#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
            append_scopeid(addr6, flags, ipbuf, sizeof(ipbuf));
#endif
          }
        else
          {
            ares_inet_ntop(AF_INET, &addr->sin_addr, ipbuf, IPBUFSIZ);
          }
        /* They also want a service */
        if (flags & ARES_NI_LOOKUPSERVICE)
          service = lookup_service((unsigned short)(port & 0xffff),
                                   flags, srvbuf, sizeof(srvbuf));
        callback(arg, ARES_SUCCESS, 0, ipbuf, service);
        return;
      }
    /* This is where a DNS lookup becomes necessary */
    else
      {
        niquery = malloc(sizeof(struct nameinfo_query));
        if (!niquery)
          {
            callback(arg, ARES_ENOMEM, 0, NULL, NULL);
            return;
          }
        niquery->callback = callback;
        niquery->arg = arg;
        niquery->flags = flags;
        niquery->timeouts = 0;
        if (sa->sa_family == AF_INET)
          {
            niquery->family = AF_INET;
            memcpy(&niquery->addr.addr4, addr, sizeof(addr));
            ares_gethostbyaddr(channel, &addr->sin_addr, sizeof(struct in_addr), AF_INET,
                               nameinfo_callback, niquery);
          }
        else
          {
            niquery->family = AF_INET6;
            memcpy(&niquery->addr.addr6, addr6, sizeof(addr6));
            ares_gethostbyaddr(channel, &addr6->sin6_addr, sizeof(struct in6_addr), AF_INET6,
                               nameinfo_callback, niquery);
          }
      }
    }
}
Пример #12
0
static void nameinfo_callback(void *arg, int status, int timeouts, struct hostent *host)
{
  struct nameinfo_query *niquery = (struct nameinfo_query *) arg;
  char srvbuf[33];
  char *service = NULL;

  niquery->timeouts += timeouts;
  if (status == ARES_SUCCESS)
    {
      /* They want a service too */
      if (niquery->flags & ARES_NI_LOOKUPSERVICE)
        {
          if (niquery->family == AF_INET)
            service = lookup_service(niquery->addr.addr4.sin_port,
                                     niquery->flags, srvbuf, sizeof(srvbuf));
          else
            service = lookup_service(niquery->addr.addr6.sin6_port,
                                     niquery->flags, srvbuf, sizeof(srvbuf));
        }
      /* NOFQDN means we have to strip off the domain name portion.
         We do this by determining our own domain name, then searching the string
         for this domain name and removing it.
       */
#ifdef HAVE_GETHOSTNAME
      if (niquery->flags & ARES_NI_NOFQDN)
        {
           char buf[255];
           char *domain;
           gethostname(buf, 255);
           if ((domain = strchr(buf, '.')))
             {
               char *end = ares_striendstr(host->h_name, domain);
               if (end)
                 *end = 0;
             }
        }
#endif
      niquery->callback(niquery->arg, ARES_SUCCESS, niquery->timeouts, (char *)(host->h_name),
                        service);
      return;
    }
  /* We couldn't find the host, but it's OK, we can use the IP */
  else if (status == ARES_ENOTFOUND && !(niquery->flags & ARES_NI_NAMEREQD))
    {
      char ipbuf[IPBUFSIZ];
      if (niquery->family == AF_INET)
        ares_inet_ntop(AF_INET, &niquery->addr.addr4.sin_addr, ipbuf, IPBUFSIZ);
      else
        {
          ares_inet_ntop(AF_INET6, &niquery->addr.addr6.sin6_addr, ipbuf, IPBUFSIZ);
#ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID
          append_scopeid(&niquery->addr.addr6, niquery->flags, ipbuf, sizeof(ipbuf));
#endif
        }
      /* They want a service too */
      if (niquery->flags & ARES_NI_LOOKUPSERVICE)
        {
          if (niquery->family == AF_INET)
            service = lookup_service(niquery->addr.addr4.sin_port,
                                     niquery->flags, srvbuf, sizeof(srvbuf));
          else
            service = lookup_service(niquery->addr.addr6.sin6_port,
                                     niquery->flags, srvbuf, sizeof(srvbuf));
        }
      niquery->callback(niquery->arg, ARES_SUCCESS, niquery->timeouts, ipbuf, service);
      return;
    }
  niquery->callback(niquery->arg, status, niquery->timeouts, NULL, NULL);
  free(niquery);
}
Пример #13
0
resource_service_fn_t *rs_remote_server_create(void *arg, tbx_inip_file_t *fd, char *section)
{
    service_manager_t *ess = (service_manager_t *)arg;
    resource_service_fn_t *rs;
    rs_remote_server_priv_t *rsrs;
    rs_create_t *rs_create;
    mq_command_table_t *ctable;
    char *stype, *ctype;

    if (section == NULL) section = "rs_remote_server";

    tbx_type_malloc_clear(rs, resource_service_fn_t, 1);
    tbx_type_malloc_clear(rsrs, rs_remote_server_priv_t, 1);
    rs->priv = (void *)rsrs;

    //** Make the locks and cond variables
    assert_result(apr_pool_create(&(rsrs->mpool), NULL), APR_SUCCESS);
    apr_thread_mutex_create(&(rsrs->lock), APR_THREAD_MUTEX_DEFAULT, rsrs->mpool);
    apr_thread_cond_create(&(rsrs->cond), rsrs->mpool);

    rsrs->pending = tbx_stack_new();
    memset(&(rsrs->my_map_version), 0, sizeof(rsrs->my_map_version));
    memset(&(rsrs->notify_map_version), 0, sizeof(rsrs->notify_map_version));
    rsrs->notify_map_version.lock = rsrs->lock;
    rsrs->notify_map_version.cond = rsrs->cond;

    //** Get the host name we bind to
    rsrs->hostname= tbx_inip_get_string(fd, section, "address", NULL);

    //** Start the child RS.   The update above should have dumped a RID config for it to load
    stype = tbx_inip_get_string(fd, section, "rs_local", NULL);
    if (stype == NULL) {  //** Oops missing child RS
        log_printf(0, "ERROR: Mising child RS  section=%s key=rs_local!\n", section);
        tbx_log_flush();
        free(stype);
        abort();
    }

    //** and load it
    ctype = tbx_inip_get_string(fd, stype, "type", RS_TYPE_SIMPLE);
    rs_create = lookup_service(ess, RS_SM_AVAILABLE, ctype);
    rsrs->rs_child = (*rs_create)(ess, fd, stype);
    if (rsrs->rs_child == NULL) {
        log_printf(1, "ERROR loading child RS!  type=%s section=%s\n", ctype, stype);
        tbx_log_flush();
        abort();
    }
    free(ctype);
    free(stype);

    //** Get the MQC
    rsrs->mqc = lookup_service(ess, ESS_RUNNING, ESS_MQ); assert(rsrs->mqc != NULL);

    //** Make the server portal
    rsrs->server_portal = mq_portal_create(rsrs->mqc, rsrs->hostname, MQ_CMODE_SERVER);
    ctable = mq_portal_command_table(rsrs->server_portal);
    mq_command_set(ctable, RSR_GET_RID_CONFIG_KEY, RSR_GET_RID_CONFIG_SIZE, rs, rsrs_rid_config_cb);
    mq_command_set(ctable, RSR_GET_UPDATE_CONFIG_KEY, RSR_GET_UPDATE_CONFIG_SIZE, rs, rsrs_rid_config_cb);
    mq_command_set(ctable, RSR_ABORT_KEY, RSR_ABORT_SIZE, rs, rsrs_abort_cb);
    mq_portal_install(rsrs->mqc, rsrs->server_portal);

    //** Launch the config changes thread
    tbx_thread_create_assert(&(rsrs->monitor_thread), NULL, rsrs_monitor_thread, (void *)rs, rsrs->mpool);

    //** Set up the fn ptrs.  This is just for syncing the rid configuration and state
    //** so very little is implemented
    rs->destroy_service = rs_remote_server_destroy;

    rs->type = RS_TYPE_REMOTE_SERVER;

    return(rs);
}
Пример #14
0
int main(void)
{
    int sockfd, client_fd;  // listen on sock_fd, new connection on client_fd
    struct addrinfo hints, *servinfo, *p;
    struct sockaddr_storage their_addr; // connector's address information
    socklen_t sin_size;
    struct sigaction sa;
    int yes=1;
    char s[INET6_ADDRSTRLEN];
    int rv;
    int pid=0;
	int numbytes=0, bleft=0;//recv and sepected bytes in packets
	int request_type;
	char buff[_MAX_PACKET_LEN_];//used to receive the packet from client part, 
	//regarless of whether it is a server or client(in view of mapper)
	char workbuff[_MAX_WORK_LEN_];//used to deal with packet command
	char *tp=NULL;//used for set the pointer of msg buffer
	memset((char*)buff,0,_MAX_PACKET_LEN_);
	memset((char*)workbuff,0,_MAX_WORK_LEN_);
	/*-----------------------Shared memory init---------------------------*/
	int shm_bitmap_id = 0, shm_server_id =0, shm_mapper_id=0;
	if((shm_bitmap_id=shmget(_SHM_BITMAP_ID_,_SHM_BITMAP_NODE_,IPC_CREAT | 0666 ))<0){
		perror("shmget");
		exit(1);
	}
	if((shm_server_id=shmget(_SHM_SERVER_ID_,_SHM_SERVER_NODE_,IPC_CREAT | 0666 ))<0){
		perror("shmget");
		exit(1);
	}
	if((shm_mapper_id=shmget(_SHM_MAPPER_ID_,_SHM_MAPPER_NODE_,IPC_CREAT | 0666 ))<0){
		perror("shmget");
		exit(1);
	}
	if ((shm = shmat(shm_bitmap_id, NULL, 0)) == (char *) -1) {
        perror("shmat");
        exit(1);
    }
    page_bitmap=(unsigned long long*)shm;
    if ((shm = shmat(shm_server_id, NULL, 0)) == (char *) -1) {
        perror("shmat");
        exit(1);
    }
  	seg_heap=(Server*)shm;
 	if ((shm = shmat(shm_mapper_id, NULL, 0)) == (char *) -1) {
        perror("shmat");
        exit(1);
    }
    Mapper=(Mapper_item*)shm;
	initial_mapper();

    /*------------------------Internet Settings Init-------------------------*/
    struct sockaddr_in local;
    int len=sizeof(local);
    if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
        perror("socket error at mapper");
        exit(-1);
    }
    local.sin_family=AF_INET;
    local.sin_addr.s_addr=INADDR_ANY;
    local.sin_port=0;
    bind(sockfd,(struct sockaddr *)&local,sizeof(local));
    /*Find out and publish socket name */
    getsockname(sockfd,(struct sockaddr *)&local,&len);
    printf("Socket has port %d\n",local.sin_port);
    system("./ip_writer > localip");
    usleep(500);
    sprintf((char*)buff,"echo \"%d\" >> localip ",local.sin_port);
    system(buff);
    memset((char*)buff,0,_MAX_PACKET_LEN_);
    /*---------------------Main Loop: listen and fork process to handle-----------------*/
    if (listen(sockfd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
	}
    sa.sa_handler = sigchld_handler; // reap all dead processes
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
        perror("sigaction");
		exit(1); 
	}
    printf("server: waiting for connections...\n");
    for(;;) {  // main accept() loop
        sin_size = sizeof their_addr;
        client_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
        if (client_fd == -1) {
            perror("accept");
			continue; 
		}
        inet_ntop(their_addr.ss_family,
            get_in_addr((struct sockaddr *)&their_addr),
            s, sizeof s);
        printf("mapper: got connection from %s\n", s);
        //fork another process to deal with all the messages
        if ( (pid = fork())==0 ) { // this is the child process
            close(sockfd); //close listening process
            //receive first message from ourside 
            if((numbytes = recv(client_fd,buff,_MAX_PACKET_LEN_-1 ,0))==-1){
            	//limit the recv number: _MAX_PACKET_LEN_-1: cause the max return value will be _MAX_WORK_LEN_-1, 
            	//then if we use the statment ment as follow will not cause core dump 
            	perror("recv");
            	fprintf(stderr,"recv:=%d\n, message:=%s\n",numbytes,buff);
            	exit(1);
            }
            if(!numbytes){
            	fprintf(stdout,"client has closed the connect\n");
            	exit(2);
            }
            tp=(char*)workbuff;
            memcpy((char*)tp,(char*)buff,numbytes*sizeof(char));
            tp+=numbytes;
            memset((char*)buff,0,_MAX_PACKET_LEN_);
            //read lenth message
            //attention: there is a $ here
            if(!sscanf(workbuff,"$%d#%d",&bleft,&request_type)){
            	fprintf(stdout,"buff is empty");
            	exit(2);
            }
           printf("\t+expected lenth next:=%d\n",bleft);
           bleft-=numbytes;
           int buffer_left=_MAX_WORK_LEN_-numbytes-1;//left space for '\0'
            //keep reading if there is not comming to the end
            while( bleft > 0 && buffer_left>0){
            	if((numbytes = recv(client_fd,buff,_MAX_PACKET_LEN_,0))==-1){
            		perror("recv");
            		fprintf(stderr,"recv:=%d\n, message:=%s\n",numbytes,buff);
            		exit(1);
            	}
            	if(!numbytes){
            		fprintf(stdout,"client has closed the connect\n");
            		exit(2);
            	}
            	memcpy(tp,buff,MIN(buffer_left,numbytes)*sizeof(char));//copy all the data received
            	memset(buff,0,_MAX_PACKET_LEN_*sizeof(char));
            	tp+=MIN(buffer_left,numbytes);
       			buffer_left-=MIN(buffer_left,numbytes);
            	bleft-=numbytes;
            }
            if(buffer_left>0){//means bleft=0
            	*tp='\0';
            }
            else{//means buffer_left<0
            	fprintf(stderr,"ivalied client parameter\n");
            	exit(1);
            }
            //the buff has already been filled up, get the whole message
            char procname[PROC_NAME_LENGTH],*procn=NULL,*ttp=NULL;
            int version,port;
            int flag=0;
            char ipname[INET6_ADDRSTRLEN];
    		memset((char*)procname,0,PROC_NAME_LENGTH);
            get_peername(client_fd, ipname, INET6_ADDRSTRLEN, &port);
    		Server* tserver=NULL;
            switch(request_type){
            	case 1://regitster
            		//unpack_stom_reg_msg((char *)workbuff, (char *)procname, &version);
             		ttp=(char*)workbuff+7;
             		printf("\t+type1: add server#\n");
                    //procn=(char*)ipname;
                    //while((*ttp)!='#') *procn++=*ttp++; *procn='\0';
                    sscanf(ttp,"#%d",&port);
                    for(++ttp;*ttp!='#';++ttp); 
					while((*ttp)!='$'){
					 	ttp++;
					 	procn=(char*)procname;
					 	while((*ttp)!='#')	*procn++ = *ttp++;
					 	*procn='\0';
					 	if(!sscanf(ttp,"#%d",&version)){
             				fprintf(stdout,"ttp is empty");
             				exit(2);
             			}
             			if(add_service((char*)procname,version,ipname,port)){
					 		perror("addserver");
					 		sprintf((char*)buff, "$0000#2#0#%s#%d#%s#%d$",(char*)procname,version,ipname,port);
					 		set_pack_len(buff,strlen(buff));
					 		flag=1;
					 		break;
             			}
					 	memset((char*)procname,0,PROC_NAME_LENGTH);
             			++ttp;
             			while((*ttp)!='#' && (*ttp)!='$')	++ttp;
					}
					if(!flag)
					{
						sprintf((char*)buff, "$0000#2#1$");
						set_pack_len(buff,strlen(buff));
						print_mapper();
					}
            		bleft=strlen(buff);
            		while(bleft>0){
	            		if ((numbytes = send(client_fd, buff, strlen(buff)+1,0))==-1)
    						{
        	 					perror("Sent");
         						exit(1);
    						}
    					bleft-=numbytes;
    				}
					break;
            	case 3://lookup
            		//unpack_ctom_qry_msg((char *)workbuff, (char *)procname, &version);
             		ttp=(char*)workbuff+8;
             		printf("\t+type2: lookup a server#\n");
             		printf("type: %s\n",ttp);
					procn=(char*)procname;
					while((*ttp)!='#' && (*ttp)!='$' )	*procn++ = *ttp++; *procn='\0';
					if(!sscanf(ttp,"#%d",&version)){
             			fprintf(stdout,"ttp is empty");
             			exit(2);
             		}
            		printf("\t+lookup for %s %d\n",procname,version);
            		tserver = lookup_service((char*)procname, version);
            		if(!tserver){//find nothing: there is no avail server could help
            			//pack_mtoc_qry_msg((char*)buff, 0, NULL, 0);
            			sprintf((char*)buff, "$0000#0$");
            		}
            		else{//we find one server could help
            			sprintf((char*)buff, "$0000#1#%s#%d$",(char*)(tserver->addstr),tserver->port);
            			//pack_mtoc_qry_msg((char*)buff,1,(char*)(tserver->addstr), tserver->port);
            		}
            		set_pack_len(buff,strlen(buff));
            		bleft=strlen(buff);
            		while(bleft>0){
	            		if ((numbytes = send(client_fd, buff, strlen(buff)+1,0))==-1)
    						{
        	 					perror("Sent");
         						exit(1);
    						}
    					bleft-=numbytes;
    				}
            		break;
            	default://error: 
            		fprintf(stderr,"ivaled type");
            		printf("\tivalued type\n");
            		exit(1);
            }
           	printf("\tworkbuff:=%s\n",workbuff);
            close(client_fd);
			exit(0); 
		}
        close(client_fd);  // parent doesn't need this 
    }
	return 0; 
}
Пример #15
0
int main(int argc, char **argv)
{
    int i, start_option;
    int n_rid;
    char *query_text;
    rs_query_t *rq;
    ex_off_t block_size, total_size;
    exnode_t *ex;
    segment_create_t *screate;
    char *fname_out = NULL;
    exnode_exchange_t *exp;
    segment_t *seg = NULL;
    op_generic_t *gop;

    if (argc < 5) {
        printf("\n");
        printf("mk_linear LIO_COMMON_OPTIONS -q rs_query_string n_rid block_size total_size file.ex3\n");
        lio_print_options(stdout);
        printf("\n");
        return(1);
    }

    lio_init(&argc, &argv);

    //*** Parse the args
    i=1;
    do {
        start_option = i;

        if (strcmp(argv[i], "-q") == 0) { //** Load the query
            i++;
            query_text = argv[i];
            i++;
        }

    } while (start_option < i);

    //** Load the fixed options
    n_rid = atoi(argv[i]);
    i++;
    block_size = atoi(argv[i]);
    i++;
    total_size = atoi(argv[i]);
    i++;
    fname_out = argv[i];
    i++;

    //** Do some simple sanity checks
    //** Make sure we loaded a simple res service
    if (fname_out == NULL) {
        printf("Missing output filename!\n");
        return(2);
    }

    //** Create an empty linear segment
    screate = lookup_service(lio_gc->ess, SEG_SM_CREATE, SEGMENT_TYPE_LINEAR);
    seg = (*screate)(lio_gc->ess);

    //** Parse the query
    rq = rs_query_parse(lio_gc->rs, query_text);
//  rs_query_add(rs, &rq, RSQ_BASE_OP_AND, "lun", RSQ_BASE_KV_EXACT, "", RSQ_BASE_KV_ANY);
    if (rq == NULL) {
        printf("Error parsing RS query: %s\n", query_text);
        printf("Exiting!\n");
        exit(1);
    }

    //** Make the actual segment
    gop = segment_linear_make(seg, NULL, rq, n_rid, block_size, total_size, lio_gc->timeout);
    i = gop_waitall(gop);
    if (i != 0) {
        printf("ERROR making segment! nerr=%d\n", i);
        return(-1);
    }
    gop_free(gop, OP_DESTROY);

    //** Make an empty exnode
    ex = exnode_create();

    //** and insert it
    view_insert(ex, seg);


    //** Print it
    exp = exnode_exchange_create(EX_TEXT);
    exnode_serialize(ex, exp);
    printf("%s", exp->text.text);

    //** and Save if back to disk
    FILE *fd = fopen(fname_out, "w");
    fprintf(fd, "%s", exp->text.text);
    fclose(fd);
    exnode_exchange_destroy(exp);


    //** Clean up
    exnode_destroy(ex);

    rs_query_destroy(lio_gc->rs, rq);

    lio_shutdown();

    return(0);
}
int client_main(void)
{
    int fd, r, n, m, wait = 0, retries,pid;
    void *binder, *cookie;
    bcmd_txn_t *txn;
    bwr_t bwr;
    inst_buf_t *inst, *inst_reply;
    inst_entry_t *entry, copy;
    unsigned char rbuf[RBUF_SIZE], *ibuf, *p;
    struct timeval ref, delta;
    char labels[INST_MAX_ENTRIES][8];
    unsigned long long total_usecs[INST_MAX_ENTRIES];
    unsigned long long min[INST_MAX_ENTRIES],max[INST_MAX_ENTRIES],record[INST_MAX_ENTRIES];
    FILE *fp;

    if (!share_cpus) {
        cpu_set_t cpuset;

        CPU_ZERO(&cpuset);
        CPU_SET(id + 1, &cpuset);
        r = sched_setaffinity(0, sizeof(cpuset), &cpuset);
        if (!r)
            printf("client %d is bound to CPU %d\n", id, id + 1);
        else
            fprintf(stderr, "client %d failed to be bound to CPU %d\n", id, id + 1);
    }

    fd = open("/dev/binder", O_RDWR);
    if (fd < 0) {
        fprintf(stderr, "client %d failed to open binder device\n", id);
        return -1;
    }

#if (!defined(INLINE_TRANSACTION_DATA))
    if (mmap(NULL, 128 * 1024, PROT_READ, MAP_PRIVATE, fd, 0) == MAP_FAILED) {
        fprintf(stderr, "server failed to mmap shared buffer\n");
        return -1;
    }
#endif

    while (1) {
        r = lookup_service(fd, service, sizeof(service) / 2, &binder, &cookie);
        if (r < 0) {
            fprintf(stderr, "client %d failed to find the instrumentation service\n", id);
            return -1;
        } else if (r > 0)
            break;

        if (wait++ > 1)
            fprintf(stderr, "client %d still waiting on instrumentation service to be ready\n", id);
        sleep(1);
    }
    printf("client %d found instrumentation service\n", id);

    txn = create_transaction(0, binder, cookie, 0, NULL, sizeof(inst_buf_t) + data_SZ, NULL, 0);
    if (!txn) {
        fprintf(stderr, "client %d failed to prepare transaction buffer\n", id);
        return -1;
    }

    bwr.write_buffer = (unsigned long)txn;
    bwr.read_buffer = (unsigned long)rbuf;

    inst = (inst_buf_t *)txn->tdata.data.ptr.buffer;
    INST_INIT(inst);

    ibuf = malloc((iterations + 1) * sizeof(inst_entry_t) * INST_MAX_ENTRIES);
    if (!ibuf)
        fprintf(stderr, "client %d failed to allocate instrumentation buffer\n", id);

    p = ibuf;
    n = iterations + 1;
    while (n-- > 0) {
        INST_BEGIN(inst);

        retries = 2;

        bwr.write_size = sizeof(*txn);
        bwr.write_consumed = 0;
        bwr.read_size = sizeof(rbuf);
        bwr.read_consumed = 0;

        INST_ENTRY(inst, "C_SEND");

        ioctl_write++;
wait_reply:
        ioctl_read++;
        r = ioctl(fd, BINDER_WRITE_READ, &bwr);
        if (r < 0) {
            fprintf(stderr, "client %d failed ioctl\n", id);
            return r;
        }
        INST_RECORD(&copy);

        r = client_parse_command(id, rbuf, bwr.read_consumed, &inst_reply);
        if (r < 0)
            return r;

        if (!inst_reply) {
            //hexdump(rbuf, bwr.read_consumed);
            if (retries-- > 0) {
                bwr.write_size = 0;
                bwr.read_consumed = 0;
                goto wait_reply;
            } else {
                fprintf(stderr, "client %d failed to receive reply\n", id);
                return -1;
            }
        }

        memcpy(inst, inst_reply, sizeof(*inst)+data_SZ);
        //acsiidump(inst_reply,sizeof(*inst)+data_SZ);
        INST_ENTRY_COPY(inst, "C_RECV", &copy);
        INST_END(inst, &p);

#if (defined(SIMULATE_FREE_BUFFER) || !defined(INLINE_TRANSACTION_DATA))
        if (FREE_BUFFER(fd, inst_reply) < 0) {
            fprintf(stderr, "client %d: failed to free shared buffer\n", id);
            return -1;
        }
#endif
    }

    if (output_file) {
        if (clients > 1) {
            char *p = malloc(strlen(output_file) + 16);

            if (!p) {
                fprintf(stderr, "client %d failed to alloc memory for filename\n", id);
                return -1;
            }
            sprintf(p, "%s-%d", output_file, id);
            output_file = p;
        }

        fp = fopen(output_file, "w");
        if (!fp) {
            fprintf(stderr, "client %d failed to open dump file\n", id);
            return -1;
        }
    } else
        fp = stdout;

    memset(total_usecs, 0, sizeof(total_usecs));
    memset(max,0,sizeof(max));
    memset(min,255,sizeof(min));
    entry = (inst_entry_t *)ibuf;

    int i;
    //acsiidump(ibuf,80);
    for (n = 0; n < inst->seq; n++) {
        for (m = 0; m < inst->next_entry; m++) {
            if (n > 0) {
                if (m == 0) {
                    if (time_ref == 0)	// absolute time
                        ref.tv_sec = ref.tv_usec = 0;
                    else
                        ref = entry->tv;
                }

                delta.tv_sec = entry->tv.tv_sec - ref.tv_sec;
                delta.tv_usec = entry->tv.tv_usec - ref.tv_usec;
                if (delta.tv_usec < 0) {
                    delta.tv_sec--;
                    delta.tv_usec += 1000000;
                }
                record[m] = delta.tv_sec * 1000000 + delta.tv_usec;

                //fprintf(fp, "%ld.%06ld\t", delta.tv_sec, delta.tv_usec);

                if (time_ref > 0) {
                    total_usecs[m] += delta.tv_sec * 1000000 + delta.tv_usec;
                    if( m == inst->next_entry -1) {
                        if (min[m] > record[m] ) {
                            for( i = 0; i < inst->next_entry; i++ ) {
                                min[i] = record[i];
                            }
                        }
                        if (max[m] < record[m] ) {
                            for( i = 0; i < inst->next_entry; i++ ) {
                                max[i] = record[i];
                            }
                        }
                    }
                }
                if (time_ref > 1)	// relative to the previous entry
                    ref = entry->tv;
            } else {
                //fprintf(fp, "%8s\t", entry->label);
                if (time_ref > 0)
                    strcpy(labels[m], entry->label);
            }

            entry++;
        }
        //fprintf(fp, "\n");
    }

    if (fp != stdout)
        fclose(fp);
    free(txn);

    pid =getpid();
    printf("client(%d) %d: ioctl read: %u\n",pid,id, ioctl_read);
    printf("client(%d) %d: ioctl write: %u\n",pid,id, ioctl_write);
    printf("client(%d) %d: ioctl buffer: %u\n",pid,id, ioctl_buffer);

    if (time_ref > 0 && iterations > 0) {
        int pos = 0,minpos=0,maxpos=0;
        char *buf = malloc(64 * m);
        char *minbuf = malloc(64 * m);
        char *maxbuf = malloc(64 * m);

        if (!buf||!minbuf||!maxbuf)
            return 1;
        for (n = 0; n < m; n++) {
            pos += sprintf(buf + pos, "\t%s: %lld.%02lldus\n", labels[n],
                           (total_usecs[n] / iterations),
                           (total_usecs[n] % iterations) * 100 / iterations);

            minpos += sprintf(minbuf + minpos, "\t%s: %lldus\n", labels[n],
                              min[n]);
            maxpos += sprintf(maxbuf + maxpos, "\t%s: %lldus\n", labels[n],
                              max[n]);
        }
        printf("client %d: average results:\n%s\n", id, buf);
        printf("client %d: min results:\n%s\n", id, minbuf);
        printf("client %d: max results:\n%s\n", id, maxbuf);
        free(buf);
        free(minbuf);
        free(maxbuf);
    }
    return 0;
}