示例#1
0
static GSocket *
open_snapd_socket (GCancellable *cancellable, GError **error)
{
    GSocket *socket;
    g_autoptr(GSocketAddress) address = NULL;
    g_autoptr(GError) error_local = NULL;

    socket = g_socket_new (G_SOCKET_FAMILY_UNIX,
                           G_SOCKET_TYPE_STREAM,
                           G_SOCKET_PROTOCOL_DEFAULT,
                           &error_local);
    if (!socket) {
        g_set_error (error,
                     GS_PLUGIN_ERROR,
                     GS_PLUGIN_ERROR_NOT_SUPPORTED,
                     "Unable to open snapd socket: %s",
                     error_local->message);
        return NULL;
    }
    address = g_unix_socket_address_new (SNAPD_SOCKET);
    if (!g_socket_connect (socket, address, cancellable, &error_local)) {
        g_set_error (error,
                     GS_PLUGIN_ERROR,
                     GS_PLUGIN_ERROR_NOT_SUPPORTED,
                     "Unable to connect snapd socket: %s",
                     error_local->message);
        g_object_unref (socket);
        return NULL;
    }

    return socket;
}
示例#2
0
static void
set_up_mock_xdg_runtime_dir (void)
{
  GError *error = NULL;
  GSocketAddress *addr;

  mock_bus = g_socket_new (G_SOCKET_FAMILY_UNIX, G_SOCKET_TYPE_STREAM, 0,
      &error);
  g_assert_no_error (error);
  g_assert_true (G_IS_SOCKET (mock_bus));

  /* alters tmpdir in-place */
  if (g_mkdtemp_full (tmpdir, 0700) == NULL)
    {
      int errsv = errno;
      g_error ("g_mkdtemp_full: %s", g_strerror (errsv));
    }

  mock_bus_path = g_strconcat (tmpdir, "/bus", NULL);
  addr = g_unix_socket_address_new (mock_bus_path);
  g_socket_bind (mock_bus, addr, FALSE, &error);
  g_assert_no_error (error);
  g_object_unref (addr);

  g_setenv ("XDG_RUNTIME_DIR", tmpdir, TRUE);
}
示例#3
0
static int remote_connect(const char* host, unsigned port,
		void** connectiondata) {
	g_message("connecting to remote: %s on port %u", host, port);

	GSocket* sock = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM,
			G_SOCKET_PROTOCOL_TCP, NULL);

	GSocketConnectable* addr = g_network_address_new(host, port);
	GSocketAddressEnumerator* enumerator = g_socket_connectable_enumerate(addr);

	int ret = EMCUETITI_PORT_REMOTE_TRYAGAIN;

	GSocketAddress* sockaddr;
	while ((sockaddr = g_socket_address_enumerator_next(enumerator, NULL, NULL))) {
		g_message("connecting...");
		GError* error = NULL;
		if (g_socket_connect(sock, sockaddr, NULL, &error)) {
			g_message("connected");
			g_socket_set_blocking(sock, FALSE);
			remote_wireupsocketcallback(sock);
			*connectiondata = sock;
			ret = EMCUETITI_PORT_REMOTE_OK;
			break;
		} else {
			g_message("failed to connect %d:%s", error->code, error->message);
		}
	}

	if (ret != EMCUETITI_PORT_REMOTE_OK)
		g_object_unref(sock);

	g_object_unref(addr);
	g_object_unref(enumerator);
	return ret;
}
示例#4
0
/* TODO: could use dbus, but for portability maybe not..... */
static void
do_connect(SpiceVDAgent *agent)
{
    GError *error = NULL;
    GSocketAddressEnumerator *enumerator;
    GSocketAddress *address;

#ifdef G_OS_UNIX
    agent->socket = g_socket_new(G_SOCKET_FAMILY_UNIX, G_SOCKET_TYPE_STREAM, 0, &error);
    agent->connectable = G_SOCKET_CONNECTABLE(g_unix_socket_address_new(vdagentd_socket));
#endif

    enumerator = g_socket_connectable_enumerate (agent->connectable);
    while (TRUE) {
        address = g_socket_address_enumerator_next (enumerator, agent->cancellable, NULL);
        if (!address) {
            g_error("can't connect to socket");
            exit(1);
        }

        if (g_socket_connect(agent->socket, address, agent->cancellable, &error))
            break;

        g_debug("Connection failed, trying next");
        g_clear_error (&error);
        g_object_unref (address);
    }
    g_object_unref(enumerator);

    agent->connection =
        G_IO_STREAM(g_socket_connection_factory_create_connection(agent->socket));
    g_debug("Connected to %s %p", vdagentd_socket, agent->connection);

    send_xorg_config(agent);
}
示例#5
0
gboolean
xdmcp_client_start (XDMCPClient *client)
{
    if (client->priv->socket)
        return TRUE;

    g_autoptr(GError) error = NULL;
    client->priv->socket = g_socket_new (G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_DATAGRAM, G_SOCKET_PROTOCOL_UDP, &error);
    if (error)
        g_warning ("Error creating XDMCP socket: %s", error->message);
    if (!client->priv->socket)
        return FALSE;

    GSocketConnectable *address = g_network_address_new (client->priv->host, client->priv->port);
    GSocketAddressEnumerator *enumerator = g_socket_connectable_enumerate (address);
    while (TRUE)
    {
        g_autoptr(GError) e = NULL;
        g_autoptr(GSocketAddress) socket_address = g_socket_address_enumerator_next (enumerator, NULL, &e);
        if (e)
            g_warning ("Failed to get socket address: %s", e->message);
        if (!socket_address)
            return FALSE;

        if (!g_socket_connect (client->priv->socket, socket_address, NULL, &e))
        {
            g_warning ("Unable to connect XDMCP socket: %s", error->message);
            continue;
        }

        g_io_add_watch (g_io_channel_unix_new (g_socket_get_fd (client->priv->socket)), G_IO_IN, xdmcp_data_cb, client);

        return TRUE;
    }
}
示例#6
0
ArvDevice *
arv_gv_device_new (GInetAddress *interface_address, GInetAddress *device_address)
{
	ArvGvDevice *gv_device;
	ArvGvDeviceIOData *io_data;
	ArvGvDeviceHeartbeatData *heartbeat_data;
	char *address_string;

	g_return_val_if_fail (G_IS_INET_ADDRESS (interface_address), NULL);
	g_return_val_if_fail (G_IS_INET_ADDRESS (device_address), NULL);

	address_string = g_inet_address_to_string (interface_address);
	arv_debug_device ("[GvDevice::new] Interface address = %s", address_string);
	g_free (address_string);
	address_string = g_inet_address_to_string (device_address);
	arv_debug_device ("[GvDevice::new] Device address = %s", address_string);
	g_free (address_string);

	gv_device = g_object_new (ARV_TYPE_GV_DEVICE, NULL);

	io_data = g_new0 (ArvGvDeviceIOData, 1);

	io_data->mutex = g_mutex_new ();
	io_data->packet_id = 65300; /* Start near the end of the circular counter */

	io_data->interface_address = g_inet_socket_address_new (interface_address, 0);
	io_data->device_address = g_inet_socket_address_new (device_address, ARV_GVCP_PORT);
	io_data->socket = g_socket_new (G_SOCKET_FAMILY_IPV4,
					G_SOCKET_TYPE_DATAGRAM,
					G_SOCKET_PROTOCOL_UDP, NULL);
	g_socket_bind (io_data->socket, io_data->interface_address, TRUE, NULL);

	io_data->buffer = g_malloc (ARV_GV_DEVICE_BUFFER_SIZE);
	io_data->gvcp_n_retries = ARV_GV_DEVICE_GVCP_N_RETRIES_DEFAULT;
	io_data->gvcp_timeout_ms = ARV_GV_DEVICE_GVCP_TIMEOUT_MS_DEFAULT;
	io_data->poll_in_event.fd = g_socket_get_fd (io_data->socket);
	io_data->poll_in_event.events =  G_IO_IN;
	io_data->poll_in_event.revents = 0;

	gv_device->priv->io_data = io_data;

	arv_gv_device_load_genicam (gv_device);

	arv_gv_device_take_control (gv_device);

	heartbeat_data = g_new (ArvGvDeviceHeartbeatData, 1);
	heartbeat_data->gv_device = gv_device;
	heartbeat_data->io_data = io_data;
	heartbeat_data->period_us = ARV_GV_DEVICE_HEARTBEAT_PERIOD_US;
	heartbeat_data->cancel = FALSE;

	gv_device->priv->heartbeat_data = heartbeat_data;

	gv_device->priv->heartbeat_thread = g_thread_create (arv_gv_device_heartbeat_thread,
							     gv_device->priv->heartbeat_data,
							     TRUE, NULL);

	return ARV_DEVICE (gv_device);
}
示例#7
0
gint
main (void)
{
	gboolean ret;
	GSocket *socket = NULL;
	GSocketAddress *address = NULL;
	GError *error = NULL;
	gsize wrote;
	const gchar *buffer = "ping\n";
	const gchar *socket_filename = "/tmp/pk-self-test.socket";
	GSource *source;
	GMainLoop *loop;

	g_type_init ();
	loop = g_main_loop_new (NULL, FALSE);

	/* create socket */
	socket = g_socket_new (G_SOCKET_FAMILY_UNIX, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_DEFAULT, &error);
	if (socket == NULL) {
		g_warning ("failed to create socket: %s", error->message);
		g_error_free (error);
		goto out;
	}
	g_socket_set_blocking (socket, FALSE);
	g_socket_set_keepalive (socket, TRUE);

	/* connect to it */
	address = g_unix_socket_address_new (socket_filename);
	ret = g_socket_connect (socket, address, NULL, &error);
	if (!ret) {
		g_warning ("failed to connect to socket: %s", error->message);
		g_error_free (error);
		goto out;
	}

	/* socket has data */
	source = g_socket_create_source (socket, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL, NULL);
	g_source_set_callback (source, (GSourceFunc) pk_socket_example_accept_connection_cb, loop, NULL);
	g_source_attach (source, NULL);

	/* send some data */
	wrote = g_socket_send (socket, buffer, 5, NULL, &error);
	if (wrote != 5) {
		g_warning ("failed to write 5 bytes");
		goto out;
	}

	/* run main loop */
	g_debug ("running main loop");
	g_main_loop_run (loop);
out:
	if (loop != NULL)
		g_main_loop_unref (loop);
	if (socket != NULL)
		g_object_unref (socket);
	if (address != NULL)
		g_object_unref (address);
	return 0;
}
示例#8
0
/**
 * g_socket_listener_add_address:
 * @listener: a #GSocketListener
 * @address: a #GSocketAddress
 * @type: a #GSocketType
 * @protocol: a #GSocketProtocol
 * @source_object: (allow-none): Optional #GObject identifying this source
 * @effective_address: (out) (allow-none): location to store the address that was bound to, or %NULL.
 * @error: #GError for error reporting, or %NULL to ignore.
 *
 * Creates a socket of type @type and protocol @protocol, binds
 * it to @address and adds it to the set of sockets we're accepting
 * sockets from.
 *
 * Note that adding an IPv6 address, depending on the platform,
 * may or may not result in a listener that also accepts IPv4
 * connections.  For more deterministic behavior, see
 * g_socket_listener_add_inet_port().
 *
 * @source_object will be passed out in the various calls
 * to accept to identify this particular source, which is
 * useful if you're listening on multiple addresses and do
 * different things depending on what address is connected to.
 *
 * If successful and @effective_address is non-%NULL then it will
 * be set to the address that the binding actually occurred at.  This
 * is helpful for determining the port number that was used for when
 * requesting a binding to port 0 (ie: "any port").  This address, if
 * requested, belongs to the caller and must be freed.
 *
 * Returns: %TRUE on success, %FALSE on error.
 *
 * Since: 2.22
 */
gboolean
g_socket_listener_add_address (GSocketListener  *listener,
			       GSocketAddress   *address,
			       GSocketType       type,
			       GSocketProtocol   protocol,
			       GObject          *source_object,
                               GSocketAddress  **effective_address,
			       GError          **error)
{
  GSocketAddress *local_address;
  GSocketFamily family;
  GSocket *socket;

  if (!check_listener (listener, error))
    return FALSE;

  family = g_socket_address_get_family (address);
  socket = g_socket_new (family, type, protocol, error);
  if (socket == NULL)
    return FALSE;

  g_socket_set_listen_backlog (socket, listener->priv->listen_backlog);

  if (!g_socket_bind (socket, address, TRUE, error) ||
      !g_socket_listen (socket, error))
    {
      g_object_unref (socket);
      return FALSE;
    }

  local_address = NULL;
  if (effective_address)
    {
      local_address = g_socket_get_local_address (socket, error);
      if (local_address == NULL)
	{
	  g_object_unref (socket);
	  return FALSE;
	}
    }

  if (!g_socket_listener_add_socket (listener, socket,
				     source_object,
				     error))
    {
      if (local_address)
	g_object_unref (local_address);
      g_object_unref (socket);
      return FALSE;
    }

  if (effective_address)
    *effective_address = local_address;

  g_object_unref (socket); /* add_socket refs this */

  return TRUE;
}
示例#9
0
/*!
 * Create a new \ref clr_oci_vm_conn and connect to hypervisor to
 * perform initial welcome negotiation.
 *
 * \param socket_path Full path to named socket.
 * \param pid Process ID of running hypervisor.
 *
 * \return \ref clr_oci_vm_conn on success, else \c NULL.
 */
static struct clr_oci_vm_conn *
clr_oci_vm_conn_new (const gchar *socket_path, GPid pid)
{
	struct clr_oci_vm_conn  *conn = NULL;
	GError                  *error = NULL;
	gboolean                 ret = false;

	g_assert (socket_path);
	g_assert (pid);

	conn = g_new0 (struct clr_oci_vm_conn, 1);
	if (! conn) {
		return NULL;
	}

	g_strlcpy (conn->socket_path, socket_path,
			sizeof (conn->socket_path));

	conn->socket_addr = g_unix_socket_address_new (socket_path);
	if (! conn->socket_addr) {
		g_critical ("socket path does not exist: %s", socket_path);
		goto err;
	}

	conn->socket = g_socket_new (G_SOCKET_FAMILY_UNIX,
			G_SOCKET_TYPE_STREAM,
			G_SOCKET_PROTOCOL_DEFAULT, &error);

	if (! conn->socket) {
		g_critical ("failed to create socket: %s",
				error->message);
		g_error_free (error);
		goto err;
	}

	ret = g_socket_connect (conn->socket, conn->socket_addr,
			NULL, &error);
	if (! ret) {
		g_critical ("failed to connect to socket: %s",
				error->message);
		g_error_free (error);
		goto err;
	}

	g_debug ("connected to socket path %s", socket_path);

	ret = clr_oci_qmp_check_welcome (conn->socket);
	if (! ret) {
		goto err;
	}

	return conn;

err:
	clr_oci_vm_conn_free (conn);

	return NULL;
}
示例#10
0
static void
on_address_next (GObject *object,
                 GAsyncResult *result,
                 gpointer user_data)
{
  CockpitStream *self = user_data;
  GSocketConnection *connection;
  GSocketAddress *address;
  GError *error = NULL;
  GSocket *sock;

  address = g_socket_address_enumerator_next_finish (G_SOCKET_ADDRESS_ENUMERATOR (object),
                                                     result, &error);

  if (error)
    {
      set_problem_from_error (self, "couldn't resolve", error);
      g_error_free (error);
      close_immediately (self, NULL);
    }
  else if (address)
    {
      sock = g_socket_new (g_socket_address_get_family (address), G_SOCKET_TYPE_STREAM, 0, &error);
      if (sock)
        {
          g_socket_set_blocking (sock, FALSE);

          connection = g_socket_connection_factory_create_connection (sock);
          g_object_unref (sock);

          g_socket_connection_connect_async (connection, address, NULL,
                                             on_socket_connect, g_object_ref (self));
        }

      if (error)
        {
          g_debug ("%s: couldn't open socket: %s", self->priv->name, error->message);
          g_clear_error (&self->priv->connect_error);
          self->priv->connect_error = error;
        }
      g_object_unref (address);
    }
  else
    {
      if (self->priv->connect_error)
        {
          set_problem_from_error (self, "couldn't connect", self->priv->connect_error);
          close_immediately (self, NULL);
        }
      else
        {
          g_message ("%s: no addresses found", self->priv->name);
          close_immediately (self, "not-found");
        }
    }

  g_object_unref (self);
}
示例#11
0
static ArvGvDiscoverSocketList *
arv_gv_discover_socket_list_new (void)
{
	ArvGvDiscoverSocketList *socket_list;
	GSList *iter;
	struct ifaddrs *ifap  = NULL;
	struct ifaddrs *ifap_iter;
	int i;

	socket_list = g_new0 (ArvGvDiscoverSocketList, 1);

	if (getifaddrs (&ifap) < 0)
		return socket_list;

	for (ifap_iter = ifap; ifap_iter != NULL; ifap_iter = ifap_iter->ifa_next) {
		if ((ifap_iter->ifa_flags & IFF_UP) != 0 &&
		    (ifap_iter->ifa_flags & IFF_POINTOPOINT) == 0 &&
		    (ifap_iter->ifa_addr != NULL) &&
		    (ifap_iter->ifa_addr->sa_family == AF_INET)) {
			ArvGvDiscoverSocket *discover_socket = g_new0 (ArvGvDiscoverSocket, 1);
			GSocketAddress *socket_address;
			GInetAddress *inet_address;
			char *inet_address_string;
			GError *error = NULL;

			socket_address = g_socket_address_new_from_native (ifap_iter->ifa_addr,
									   sizeof (struct sockaddr));
			inet_address = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (socket_address));
			inet_address_string = g_inet_address_to_string (inet_address);
			arv_debug_interface ("[GvDiscoverSocket::new] Add interface %s", inet_address_string);
			g_free (inet_address_string);
			discover_socket->interface_address = g_inet_socket_address_new (inet_address, 0);
			g_object_unref (socket_address);

			discover_socket->socket = g_socket_new (G_SOCKET_FAMILY_IPV4,
								G_SOCKET_TYPE_DATAGRAM,
								G_SOCKET_PROTOCOL_UDP, NULL);
			g_socket_bind (discover_socket->socket, discover_socket->interface_address, TRUE, &error);

			socket_list->sockets = g_slist_prepend (socket_list->sockets, discover_socket);
			socket_list->n_sockets++;
		}
	}

	freeifaddrs (ifap);

	socket_list->poll_fds = g_new (GPollFD, socket_list->n_sockets);
	for (i = 0, iter = socket_list->sockets; iter != NULL; i++, iter = iter->next) {
		ArvGvDiscoverSocket *discover_socket = iter->data;

		socket_list->poll_fds[i].fd = g_socket_get_fd (discover_socket->socket);
		socket_list->poll_fds[i].events =  G_IO_IN;
		socket_list->poll_fds[i].revents = 0;
	}

	return socket_list;
}
示例#12
0
static void
arv_gv_interface_build_discover_infos_list (ArvGvInterface *gv_interface)
{
	struct ifaddrs *ifap  = NULL;
	struct ifaddrs *ifap_iter;
	int return_value;

	arv_gv_interface_free_discover_infos_list (gv_interface);

	return_value  = getifaddrs (&ifap);
	if (return_value < 0)
		return;

	for (ifap_iter = ifap; ifap_iter != NULL; ifap_iter = ifap_iter->ifa_next) {
		if ((ifap_iter->ifa_flags & IFF_UP) != 0 &&
		    (ifap_iter->ifa_flags & IFF_POINTOPOINT) == 0 &&
		    (ifap_iter->ifa_addr->sa_family == AF_INET)) {
			ArvGvInterfaceDiscoverInfos *infos = g_new (ArvGvInterfaceDiscoverInfos, 1);
			GSocketAddress *socket_address;
			GInetAddress *inet_address;
			char *inet_address_string;
			GError *error = NULL;

			socket_address = g_socket_address_new_from_native (ifap_iter->ifa_addr,
									   sizeof (struct sockaddr));
			inet_address = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (socket_address));
			inet_address_string = g_inet_address_to_string (inet_address);
			arv_debug_interface ("[GvInterface::build_discover_infos_list] Add interface %s",
					     inet_address_string);
			g_free (inet_address_string);
			infos->interface_address = g_inet_socket_address_new (inet_address, 0);
			g_object_unref (socket_address);

			socket_address = g_socket_address_new_from_native (ifap_iter->ifa_broadaddr,
									   sizeof (struct sockaddr));
			inet_address = g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (socket_address));
			infos->broadcast_address = g_inet_socket_address_new (inet_address, ARV_GVCP_PORT);
			inet_address_string = g_inet_address_to_string (inet_address);
			arv_debug_interface ("[GvInterface::build_discover_infos_list] Broadcast address is %s",
					     inet_address_string);
			g_free (inet_address_string);
			g_object_unref (socket_address);

			infos->socket = g_socket_new (G_SOCKET_FAMILY_IPV4,
						      G_SOCKET_TYPE_DATAGRAM,
						      G_SOCKET_PROTOCOL_UDP, NULL);
			g_socket_bind (infos->socket, infos->interface_address, TRUE, &error);

			gv_interface->priv->discover_infos_list =
				g_slist_prepend (gv_interface->priv->discover_infos_list,
						 infos);
			gv_interface->priv->n_discover_infos++;
		}
	}

	freeifaddrs (ifap);
}
示例#13
0
GSocket *
xg_socket_new (GSocketFamily family,
               GSocketType type,
               GSocketProtocol protocol)
{
    GSocket *s;
    GError *error;
    s = g_socket_new (family, type, protocol, &error);
    if (s == NULL)
        g_critical ("g_socket_new() returns NULL: %s", error->message);
    return s;
}
示例#14
0
//Bfoadcast ivy msgs to clients
void broadcast_to_clients () {

  int i;

  if (uTCP) {
    //broadcast using tcp connection
    GError *error = NULL;

    for (i = 0; i < MAXCLIENT; i++) {
      if (ConnectedClients[i].used > 0) {
        GOutputStream * ostream = g_io_stream_get_output_stream (ConnectedClients[i].ClientTcpData);
        g_output_stream_write(ostream, ivybuffer, strlen(ivybuffer), NULL, &error);
      }

    }
    return;
  }

  i=0;
  for (i = 0; i < MAXCLIENT; i++) {
    if (ConnectedClients[i].used > 0) {

      //Send data
      GInetAddress *udpAddress;
      GSocketAddress *udpSocketAddress;
      GSocket *udpSocket;

      udpAddress = g_inet_address_new_from_string(ConnectedClients[i].client_ip);

      udpSocketAddress = g_inet_socket_address_new(udpAddress, udp_port);

      udpSocket = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_DATAGRAM, 17, NULL);

      if (g_socket_connect(udpSocket, udpSocketAddress, NULL, NULL) == FALSE) {
        printf("App Server: stg wrong with socket connect\n");
        fflush(stdout);
      }
      if (g_socket_send(udpSocket, ivybuffer, strlen(ivybuffer) , NULL, NULL) < 0) {
        printf("App Server: stg wrong with send func\n");
        fflush(stdout);
      }
      if (g_socket_close(udpSocket, NULL) == FALSE) {
        printf("App Server: stg wrong with socket close\n");
        fflush(stdout);
      }
      //Unref objects
      g_object_unref(udpAddress);
      g_object_unref(udpSocketAddress);
      g_object_unref(udpSocket);
    }
  }

}
示例#15
0
static gboolean
kms_sctp_connection_create_socket (KmsSCTPConnection * conn, gchar * host,
    gint port, GCancellable * cancellable, GError ** err)
{
  GInetAddress *addr;

  /* look up name if we need to */
  addr = g_inet_address_new_from_string (host);
  if (addr == NULL) {
    GResolver *resolver;
    GList *results;

    resolver = g_resolver_get_default ();
    results = g_resolver_lookup_by_name (resolver, host, cancellable, err);

    if (results == NULL) {
      g_object_unref (resolver);
      return FALSE;
    }

    addr = G_INET_ADDRESS (g_object_ref (results->data));

    g_resolver_free_addresses (results);
    g_object_unref (resolver);
  }

  if (G_UNLIKELY (GST_LEVEL_DEBUG <= _gst_debug_min)) {
    gchar *ip = g_inet_address_to_string (addr);

    GST_DEBUG ("IP address for host %s is %s", host, ip);
    g_free (ip);
  }

  conn->saddr = g_inet_socket_address_new (addr, port);
  g_object_unref (addr);

  conn->socket = g_socket_new (g_socket_address_get_family (conn->saddr),
      G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_SCTP, err);

  if (conn->socket == NULL) {
    g_clear_object (&conn->saddr);
    return FALSE;
  }

  /* create socket */
  GST_DEBUG ("created SCTP socket for %s", host);

  return TRUE;
}
示例#16
0
int setRTPConnectionToServer(GstRTSPsink *sink)
{

	GError *error;

//	gchar *host = sink->host; // "www.ynet.co.il";// "192.168.2.108"; 
//	gint port = sink->server_rtp_port;
//

	if (!sink->socket)  {
		sink->socket = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_DATAGRAM, G_SOCKET_PROTOCOL_UDP, NULL);

		gchar *s;
		GInetAddress *ia;
		ia = g_inet_address_new_from_string(sink->host);


		// Try to get hostby name 
		if (!ia) {
			GResolver *resolver;
			resolver = g_resolver_get_default();
			GList *results;
			results = g_resolver_lookup_by_name(resolver, sink->host, FALSE, &error);
			if (results){
				ia = G_INET_ADDRESS(g_object_ref(results->data));
			}

			gchar *ip = g_inet_address_to_string(ia);

			g_print("IP address for host %s is %s", sink->host, ip);
			g_free(ip);

			g_resolver_free_addresses(results);
			g_object_unref(resolver);
		}


		s = g_inet_address_to_string(ia);
		sink->sa = g_inet_socket_address_new(ia, sink->server_rtp_port);
	}


	if (sink->socket != NULL && sink->sa != NULL)
		return GST_RTSP_OK;

	return GST_RTSP_ERROR;

}
示例#17
0
文件: main.c 项目: dram/configs
GSocket *create_socket(void)
{
	GSocket *sock;
	GSocketAddress *addr;

	sock = g_socket_new(
		G_SOCKET_FAMILY_UNIX, G_SOCKET_TYPE_STREAM, 0, NULL);

	addr = g_unix_socket_address_new(EMACS_FCITX_SOCKET);

	unlink(EMACS_FCITX_SOCKET);

	g_socket_bind(sock, addr, FALSE, NULL);

	g_socket_listen(sock, NULL);

	return sock;
}
示例#18
0
int main(int argc, char *argv[])
{
    GError *err = NULL;
    GSocket *serv_gsock;
    GSocketAddress *gaddr;
    struct sockaddr_in addr;

    /* Create socket */
    serv_gsock = g_socket_new(G_SOCKET_FAMILY_IPV4,
                          G_SOCKET_TYPE_STREAM,
                          0,
                          &err);
    if (!serv_gsock) {
        printf("GSocket creation failure: %s\n", err->message);
        g_clear_error(&err);
    }

    /* Bind to 127.0.0.1 */
    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(10086);
    inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
    gaddr = g_socket_address_new_from_native(&addr, sizeof(addr));
    if (!g_socket_bind(serv_gsock, gaddr, TRUE, &err)) {
        printf("GSocket bind failure: %s\n", err->message);
        g_clear_error(&err);
    }

    /* Listen */
    if (!g_socket_listen(serv_gsock, &err)) {
        printf("GSocket listen failure: %s\n", err->message);
        g_clear_error(&err);
    }

    /* Accept */
    gchar buffer[256];
    gsize bytes_read;
    GSocket *clnt_gsock;
    clnt_gsock = g_socket_accept(serv_gsock, NULL, &err);
    bytes_read = g_socket_receive(clnt_gsock, buffer, 256, NULL, &err);
    printf("%u read: <%s>\n", (unsigned int)bytes_read, buffer);
    return 0;
}
示例#19
0
GSocket *multicast_createSocket(gchar *interface, gchar *groupaddress, guint port,
                                 GSocketAddress **sa)
{
    GError *err = NULL;
    GInetAddress *addr =
        g_inet_address_new_from_string(groupaddress);
    *sa = g_inet_socket_address_new(addr,port);

    GSocket *socket = g_socket_new(G_SOCKET_FAMILY_IPV6,
                        G_SOCKET_TYPE_DATAGRAM,
                        G_SOCKET_PROTOCOL_UDP,
                        NULL);
    ub_assert(socket != NULL);
    
    int on = 1;
    setsockopt(g_socket_get_fd(socket), SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    if( g_socket_bind(socket, *sa, TRUE, &err) == FALSE ){
        syslog(LOG_ERR, "net_createSockets: Error while binding udp socket: %s\n", err->message);
        g_error_free(err);
        g_object_unref(*sa);
        g_object_unref(socket);
        return NULL;
    }

    struct addrinfo *resmulti;
    struct ipv6_mreq mreq;
    mreq.ipv6mr_interface = if_nametoindex(interface);
    gchar *tmp = g_inet_address_to_string(addr);
    syslog(LOG_DEBUG,"using address: %s\n",tmp);
    int ret = getaddrinfo(tmp, NULL, NULL, &resmulti);
    g_free(tmp);
    if( ret ){
        syslog(LOG_ERR,"net_multicast.c: %s",  gai_strerror(ret));
        g_object_unref(*sa);
        g_object_unref(socket);
        return NULL;
    }
    mreq.ipv6mr_multiaddr = ((struct sockaddr_in6 *)resmulti->ai_addr)->sin6_addr;
    setsockopt(g_socket_get_fd(socket), IPPROTO_IPV6,
        IPV6_ADD_MEMBERSHIP, (char *)&mreq, sizeof(mreq));
    return socket;
}
示例#20
0
文件: interface.c 项目: muccc/ubd
gint interface_createAddress(struct node *n) //GInetAddress *addr)
{
    GError * e = NULL;
    
    GInetAddress *lo = g_inet_address_new_loopback(
                            G_SOCKET_FAMILY_IPV6);
    GSocketAddress *sa = g_inet_socket_address_new(
                            lo,
                            42);
    
    GSocket *s = n->ubnetd;
    if( s != NULL ){
        g_socket_close(s,NULL);
        g_object_unref(s);
    }

    s = g_socket_new(G_SOCKET_FAMILY_IPV6,
                            G_SOCKET_TYPE_STREAM,
                            G_SOCKET_PROTOCOL_TCP,
                            &e);
    if( e != NULL ){
        syslog(LOG_ERR,"interface_pushAddress: Error while creating socket: %s\n", e->message);
        g_error_free(e);
        return -1;
    }

    g_socket_connect(s, sa, NULL, &e);
    if( e != NULL ){
        syslog(LOG_ERR,"interface_pushAddress: Error while connecting: %s\n", e->message);
        g_error_free(e);
        return -1;
    }
    
    g_socket_send(s,"A",1,NULL,NULL);
    gchar *bytes = (gchar*)g_inet_address_to_bytes(n->netadr);
    g_socket_send(s,bytes,16,NULL,NULL);
    n->ubnetd = s;
    //gchar buf[1];
    //g_socket_receive(s,buf,1,NULL,NULL);
    return 0;
}
示例#21
0
static GSocket *
create_socket (GSocketClient  *client,
	       GSocketAddress *dest_address,
	       GError        **error)
{
  GSocketFamily family;
  GSocket *socket;

  family = client->priv->family;
  if (family == G_SOCKET_FAMILY_INVALID &&
      client->priv->local_address != NULL)
    family = g_socket_address_get_family (client->priv->local_address);
  if (family == G_SOCKET_FAMILY_INVALID)
    family = g_socket_address_get_family (dest_address);

  socket = g_socket_new (family,
			 client->priv->type,
			 client->priv->protocol,
			 error);
  if (socket == NULL)
    return NULL;

  if (client->priv->local_address)
    {
      if (!g_socket_bind (socket,
			  client->priv->local_address,
			  FALSE,
			  error))
	{
	  g_object_unref (socket);
	  return NULL;
	}
    }

  if (client->priv->timeout)
    g_socket_set_timeout (socket, client->priv->timeout);

  return socket;
}
GSocket *
_client_create_local_socket (GError **error)
{
  GSocket *socket = NULL;
  GInetAddress * inet_address = NULL;
  GSocketAddress *socket_address = NULL;

  /* Create the IPv4 socket, and listen for connection on it */
  socket = g_socket_new (G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM,
      G_SOCKET_PROTOCOL_DEFAULT, error);
  if (socket != NULL)
    {
      inet_address = g_inet_address_new_loopback (G_SOCKET_FAMILY_IPV4);
      socket_address = g_inet_socket_address_new (inet_address, 0);
      g_socket_bind (socket, socket_address, FALSE, error);
    }

  tp_clear_object (&inet_address);
  tp_clear_object (&socket_address);

  return socket;
}
示例#23
0
/**
 * g_vfs_ftp_connection_listen_data_connection:
 * @conn: a connection
 * @error: %NULL or location to take potential errors
 *
 * Initiates a listening socket that the FTP server can connect to. To accept 
 * connections and initialize data transfers, use 
 * g_vfs_ftp_connection_accept_data_connection().
 * This function supports what is known as "active FTP", while
 * g_vfs_ftp_connection_open_data_connection() is to be used for "passive FTP".
 *
 * Returns: the actual address the socket is listening on or %NULL on error
 **/
GSocketAddress *
g_vfs_ftp_connection_listen_data_connection (GVfsFtpConnection *conn,
                                             GError **          error)
{
  GSocketAddress *local, *addr;

  g_return_val_if_fail (conn != NULL, NULL);
  g_return_val_if_fail (conn->data == NULL, NULL);

  g_vfs_ftp_connection_stop_listening (conn);

  local = g_socket_connection_get_local_address (conn->connection, error);
  if (local == NULL)
    return NULL;

  conn->listen_socket = g_socket_new (g_socket_address_get_family (local),
                                      G_SOCKET_TYPE_STREAM,
                                      G_SOCKET_PROTOCOL_TCP,
                                      error);
  if (conn->listen_socket == NULL)
    return NULL;

  g_assert (G_IS_INET_SOCKET_ADDRESS (local));
  addr = g_inet_socket_address_new (g_inet_socket_address_get_address (G_INET_SOCKET_ADDRESS (local)), 0);
  g_object_unref (local);

  if (!g_socket_bind (conn->listen_socket, addr, TRUE, error) ||
      !g_socket_listen (conn->listen_socket, error) ||
      !(local = g_socket_get_local_address (conn->listen_socket, error)))
    {
      g_object_unref (addr);
      g_vfs_ftp_connection_stop_listening (conn);
      return NULL;
    }

  g_object_unref (addr);
  return local;
}
示例#24
0
文件: net.c 项目: schneider42/uberbus
static gboolean net_createUDPSocket(struct node *n, guint classid)
{
    GError * err = NULL;
    GInetAddress *addr = n->netadr;
    guint port = 2300+n->classes[classid];

    syslog(LOG_DEBUG,"net_createSockets: Creating udp socket on port %u\n", port);

    GSocketAddress * sa = g_inet_socket_address_new(addr,port);

    n->udpsockets[classid].n = n;
    GSocket *socket = g_socket_new(G_SOCKET_FAMILY_IPV6,
                        G_SOCKET_TYPE_DATAGRAM,
                        G_SOCKET_PROTOCOL_UDP,
                        NULL);

    ub_assert(socket != NULL);

    if( g_socket_bind(socket, sa, TRUE, &err) == FALSE ){
        syslog(LOG_WARNING, "net_createSockets: Error while binding udp socket: %s\n", err->message);
        g_error_free(err);
        return FALSE;
    }

    GSource *source = g_socket_create_source(socket, G_IO_IN, NULL);
    ub_assert(source != NULL);
    g_source_set_callback(source, (GSourceFunc)udp_read,
            &(n->udpsockets[classid]) , NULL);
    g_source_attach(source, g_main_context_default());
    n->udpsockets[classid].socket = socket;
    n->udpsockets[classid].source = source;
    n->udpsockets[classid].socketaddress = sa;
    n->udpsockets[classid].classid = classid;

    //broadcast_addService(n->classes[classid]);
    return TRUE;
}
示例#25
0
//Bfoadcast ivy msgs to clients
void broadcast_to_clients () {

  int i;
  for (i = 0; i < MAXCLIENT; i++) {
    if (ConnectedClients[i].used > 0) {

      //Send data
      GInetAddress *udpAddress;
      GSocketAddress *udpSocketAddress;
      GSocket *udpSocket;

      udpAddress = g_inet_address_new_from_string(ConnectedClients[i].client_ip);

      udpSocketAddress = g_inet_socket_address_new(udpAddress, udp_port);

      udpSocket = g_socket_new(G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_DATAGRAM, 17, NULL);

      if (g_socket_connect(udpSocket, udpSocketAddress, NULL, NULL) == FALSE) {
        printf("App Server: stg wrong with socket connect\n");
        fflush(stdout);
      }
      if (g_socket_send(udpSocket, ivybuffer, strlen(ivybuffer) , NULL, NULL) < 0) {
        printf("App Server: stg wrong with send func\n");
        fflush(stdout);
      }
      if (g_socket_close(udpSocket, NULL) == FALSE) {
        printf("App Server: stg wrong with socket close\n");
        fflush(stdout);
      }
      //Unref objects
      g_object_unref(udpAddress);
      g_object_unref(udpSocketAddress);
      g_object_unref(udpSocket);
    }
  }
}
/* create a socket for sending to remote machine */
static void
gst_sctp_base_sink_create_socket (GstSCTPBaseSink * self)
{
  GSocketAddress *saddr;
  GResolver *resolver;
  GInetAddress *addr;
  GError *err = NULL;

  if (GST_OBJECT_FLAG_IS_SET (self, GST_SCTP_BASE_SINK_OPEN))
    return;

  /* look up name if we need to */
  addr = g_inet_address_new_from_string (self->priv->host);
  if (addr == NULL) {
    GList *results;

    resolver = g_resolver_get_default ();
    results = g_resolver_lookup_by_name (resolver, self->priv->host,
        self->priv->cancellable, &err);

    if (results == NULL)
      goto name_resolve;

    addr = G_INET_ADDRESS (g_object_ref (results->data));

    g_resolver_free_addresses (results);
    g_object_unref (resolver);
  }

  if (G_UNLIKELY (GST_LEVEL_DEBUG <= _gst_debug_min)) {
    gchar *ip = g_inet_address_to_string (addr);

    GST_DEBUG_OBJECT (self, "IP address for host %s is %s", self->priv->host,
        ip);
    g_free (ip);
  }

  saddr = g_inet_socket_address_new (addr, self->priv->port);
  g_object_unref (addr);

  /* create sending client socket */
  GST_DEBUG_OBJECT (self, "opening sending client socket to %s:%d",
      self->priv->host, self->priv->port);

  self->priv->socket = g_socket_new (g_socket_address_get_family (saddr),
      G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_SCTP, &err);
  if (self->priv->socket == NULL)
    goto no_socket;

#if defined (SCTP_INITMSG)
  {
    struct sctp_initmsg initmsg;

    memset (&initmsg, 0, sizeof (initmsg));
    initmsg.sinit_num_ostreams = self->priv->num_ostreams;
    initmsg.sinit_max_instreams = self->priv->max_istreams;

    if (setsockopt (g_socket_get_fd (self->priv->socket), IPPROTO_SCTP,
            SCTP_INITMSG, &initmsg, sizeof (initmsg)) < 0)
      GST_ELEMENT_WARNING (self, RESOURCE, SETTINGS, (NULL),
          ("Could not configure SCTP socket: %s (%d)", g_strerror (errno),
              errno));
  }
#else
  GST_WARNING_OBJECT (self, "don't know how to configure the SCTP initiation "
      "parameters on this OS.");
#endif

  GST_DEBUG_OBJECT (self, "opened sending client socket");

  /* connect to server */
  if (!g_socket_connect (self->priv->socket, saddr, self->priv->cancellable,
          &err))
    goto connect_failed;

  g_object_unref (saddr);

  GST_OBJECT_FLAG_SET (self, GST_SCTP_BASE_SINK_OPEN);
  GST_DEBUG ("Created sctp socket");

  return;

no_socket:
  {
    GST_ELEMENT_ERROR (self, RESOURCE, OPEN_READ, (NULL),
        ("Failed to create socket: %s", err->message));
    g_clear_error (&err);
    g_object_unref (saddr);
    return;
  }
name_resolve:
  {
    if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
      GST_DEBUG_OBJECT (self, "Cancelled name resolval");
    } else {
      GST_ELEMENT_ERROR (self, RESOURCE, OPEN_READ, (NULL),
          ("Failed to resolve host '%s': %s", self->priv->host, err->message));
    }
    g_clear_error (&err);
    g_object_unref (resolver);
    return;
  }
connect_failed:
  {
    if (g_error_matches (err, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
      GST_DEBUG_OBJECT (self, "Cancelled connecting");
    } else {
      GST_ELEMENT_ERROR (self, RESOURCE, OPEN_READ, (NULL),
          ("Failed to connect to host '%s:%d': %s", self->priv->host,
              self->priv->port, err->message));
    }
    g_clear_error (&err);
    g_object_unref (saddr);
    /* pretend we opened ok for proper cleanup to happen */
    GST_OBJECT_FLAG_SET (self, GST_SCTP_BASE_SINK_OPEN);
    gst_sctp_base_sink_destroy_socket (self);
    return;
  }
}
示例#27
0
int
main (int argc,
      char *argv[])
{
  GSocket *socket, *new_socket, *recv_socket;
  GSocketAddress *src_address;
  GSocketAddress *address;
  GSocketType socket_type;
  GSocketFamily socket_family;
  GError *error = NULL;
  GOptionContext *context;
  GCancellable *cancellable;
  char *display_addr;
  GTlsCertificate *tlscert = NULL;
  GIOStream *connection;
  GInputStream *istream;
  GOutputStream *ostream;

  g_type_init ();

  context = g_option_context_new (" - Test GSocket server stuff");
  g_option_context_add_main_entries (context, cmd_entries, NULL);
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("%s: %s\n", argv[0], error->message);
      return 1;
    }

  if (unix_socket && argc != 2)
    {
      g_printerr ("%s: %s\n", argv[0], "Need to specify unix socket name");
      return 1;
    }

  if (cancel_timeout)
    {
      GThread *thread;
      cancellable = g_cancellable_new ();
      thread = g_thread_new ("cancel", cancel_thread, cancellable);
      g_thread_unref (thread);
    }
  else
    {
      cancellable = NULL;
    }

  if (tls_cert_file)
    {
      if (use_udp)
	{
	  g_printerr ("DTLS (TLS over UDP) is not supported");
	  return 1;
	}

      tlscert = g_tls_certificate_new_from_file (tls_cert_file, &error);
      if (!tlscert)
	{
	  g_printerr ("Could not read server certificate '%s': %s\n",
		      tls_cert_file, error->message);
	  return 1;
	}
    }

  loop = g_main_loop_new (NULL, FALSE);

  if (use_udp)
    socket_type = G_SOCKET_TYPE_DATAGRAM;
  else
    socket_type = G_SOCKET_TYPE_STREAM;

  if (unix_socket)
    socket_family = G_SOCKET_FAMILY_UNIX;
  else
    socket_family = G_SOCKET_FAMILY_IPV4;

  socket = g_socket_new (socket_family, socket_type, 0, &error);

  if (socket == NULL)
    {
      g_printerr ("%s: %s\n", argv[0], error->message);
      return 1;
    }

  if (non_blocking)
    g_socket_set_blocking (socket, FALSE);

  if (unix_socket)
    {
      src_address = socket_address_from_string (argv[1]);
      if (src_address == NULL)
	{
	  g_printerr ("%s: Could not parse '%s' as unix socket name\n", argv[0], argv[1]);
	  return 1;
	}
    }
  else
    {
      src_address = g_inet_socket_address_new (g_inet_address_new_any (G_SOCKET_FAMILY_IPV4), port);
    }

  if (!g_socket_bind (socket, src_address, !dont_reuse_address, &error))
    {
      g_printerr ("Can't bind socket: %s\n", error->message);
      return 1;
    }
  g_object_unref (src_address);

  if (!use_udp)
    {
      if (!g_socket_listen (socket, &error))
	{
	  g_printerr ("Can't listen on socket: %s\n", error->message);
	  return 1;
	}

      address = g_socket_get_local_address (socket, &error);
      if (!address)
	{
	  g_printerr ("Error getting local address: %s\n",
		      error->message);
	  return 1;
	}
      display_addr = socket_address_to_string (address);
      g_print ("listening on %s...\n", display_addr);
      g_free (display_addr);

      ensure_socket_condition (socket, G_IO_IN, cancellable);
      new_socket = g_socket_accept (socket, cancellable, &error);
      if (!new_socket)
	{
	  g_printerr ("Error accepting socket: %s\n",
		      error->message);
	  return 1;
	}

      if (non_blocking)
	g_socket_set_blocking (new_socket, FALSE);
      if (read_timeout)
	g_socket_set_timeout (new_socket, read_timeout);

      address = g_socket_get_remote_address (new_socket, &error);
      if (!address)
	{
	  g_printerr ("Error getting remote address: %s\n",
		      error->message);
	  return 1;
	}

      display_addr = socket_address_to_string (address);
      g_print ("got a new connection from %s\n", display_addr);
      g_free(display_addr);
      g_object_unref (address);

      recv_socket = new_socket;

      connection = G_IO_STREAM (g_socket_connection_factory_create_connection (recv_socket));
      g_object_unref (new_socket);
    }
  else
    {
      recv_socket = socket;
      connection = NULL;
    }

  if (tlscert)
    {
      GIOStream *tls_conn;

      tls_conn = g_tls_server_connection_new (connection, tlscert, &error);
      if (!tls_conn)
	{
	  g_printerr ("Could not create TLS connection: %s\n",
		      error->message);
	  return 1;
	}

      if (!g_tls_connection_handshake (G_TLS_CONNECTION (tls_conn),
				       cancellable, &error))
	{
	  g_printerr ("Error during TLS handshake: %s\n",
		      error->message);
	  return 1;
       }

      g_object_unref (connection);
      connection = tls_conn;
    }

  if (connection)
    {
      istream = g_io_stream_get_input_stream (connection);
      ostream = g_io_stream_get_output_stream (connection);
    }
  else
    {
      g_assert (use_udp);
      istream = NULL;
      ostream = NULL;
    }

  while (TRUE)
    {
      gchar buffer[4096];
      gssize size;
      gsize to_send;

      if (use_udp)
	{
	  ensure_socket_condition (recv_socket, G_IO_IN, cancellable);
	  size = g_socket_receive_from (recv_socket, &address,
					buffer, sizeof buffer,
					cancellable, &error);
	}
      else
	{
	  ensure_connection_condition (connection, G_IO_IN, cancellable);
	  size = g_input_stream_read (istream,
				      buffer, sizeof buffer,
				      cancellable, &error);
	}

      if (size < 0)
	{
	  g_printerr ("Error receiving from socket: %s\n",
		      error->message);
	  return 1;
	}

      if (size == 0)
	break;

      g_print ("received %" G_GSSIZE_FORMAT " bytes of data", size);
      if (use_udp)
	g_print (" from %s", socket_address_to_string (address));
      g_print ("\n");

      if (verbose)
	g_print ("-------------------------\n"
		 "%.*s\n"
		 "-------------------------\n",
		 (int)size, buffer);

      to_send = size;

#ifdef __QNXNTO__
      if (delay_)
#else
      if (delay)
#endif
	{
#ifdef __QNXNTO__
	  if (verbose)
	    g_print ("delaying %d seconds before response\n", delay_);
	  g_usleep (1000 * 1000 * delay_);
#else
	  if (verbose)
	    g_print ("delaying %d seconds before response\n", delay);
	  g_usleep (1000 * 1000 * delay);
#endif
	}

      while (to_send > 0)
	{
	  if (use_udp)
	    {
	      ensure_socket_condition (recv_socket, G_IO_OUT, cancellable);
	      size = g_socket_send_to (recv_socket, address,
				       buffer, to_send, cancellable, &error);
	    }
	  else
	    {
	      ensure_connection_condition (connection, G_IO_OUT, cancellable);
	      size = g_output_stream_write (ostream,
					    buffer, to_send,
					    cancellable, &error);
	    }

	  if (size < 0)
	    {
	      if (g_error_matches (error,
				   G_IO_ERROR,
				   G_IO_ERROR_WOULD_BLOCK))
		{
		  g_print ("socket send would block, handling\n");
		  g_error_free (error);
		  error = NULL;
		  continue;
		}
	      else
		{
		  g_printerr ("Error sending to socket: %s\n",
			      error->message);
		  return 1;
		}
	    }

	  g_print ("sent %" G_GSSIZE_FORMAT " bytes of data\n", size);

	  if (size == 0)
	    {
	      g_printerr ("Unexpected short write\n");
	      return 1;
	    }

	  to_send -= size;
	}
    }

  g_print ("connection closed\n");

  if (connection)
    {
      if (!g_io_stream_close (connection, NULL, &error))
	{
	  g_printerr ("Error closing connection stream: %s\n",
		      error->message);
	  return 1;
	}
      g_object_unref (connection);
    }

  if (!g_socket_close (socket, &error))
    {
      g_printerr ("Error closing master socket: %s\n",
		  error->message);
      return 1;
    }
  g_object_unref (socket);

  return 0;
}
GST_END_TEST

GST_START_TEST (test_functioning)
{
  GstDvbCssWcServer *wc;
  GstDvbCssWcPacket *packet;
  GstClock *clock;
  guint32 local_secs, local_nanos;
  GSocketAddress *server_addr;
  GInetAddress *addr;
  GSocket *socket;
  gint port = -1;
  GstClockTime prev_receive_timevalue, prev_transmit_timevalue;

  clock = gst_system_clock_obtain ();
  fail_unless (clock != NULL, "failed to get system clock");
  wc = gst_dvb_css_wc_server_new (clock, "127.0.0.1", 37034, TRUE, 500);
  fail_unless (wc != NULL, "failed to create dvb css wc server");

  g_object_get (wc, "port", &port, NULL);
  fail_unless (port > 0);

  socket = g_socket_new (G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_DATAGRAM,
      G_SOCKET_PROTOCOL_UDP, NULL);
  fail_unless (socket != NULL, "could not create socket");

  addr = g_inet_address_new_from_string ("127.0.0.1");
  server_addr = g_inet_socket_address_new (addr, port);
  g_object_unref (addr);

  packet = gst_dvb_css_wc_packet_new (NULL);
  fail_unless (packet != NULL, "failed to create packet");

  packet->message_type = GST_DVB_CSS_WC_MSG_REQUEST;  
  packet->originate_timevalue_secs = local_secs = 123;  
  packet->originate_timevalue_nanos = local_nanos = 456;  

  fail_unless (gst_dvb_css_wc_packet_send (packet, socket, server_addr, NULL));

  g_free (packet);
  
  packet = gst_dvb_css_wc_packet_receive (socket, NULL, NULL);
  fail_unless (packet != NULL, "failed to receive packet");
  fail_unless (packet->message_type == GST_DVB_CSS_WC_MSG_RESPONSE_WITH_FOLLOWUP, "wrong msg type");
  fail_unless (packet->originate_timevalue_secs == local_secs, "originate_timevalue_secs is not the same");
  fail_unless (packet->originate_timevalue_nanos == local_nanos, "originate_timevalue_nanos is not the same");
  fail_unless (packet->receive_timevalue < packet->transmit_timevalue, "remote time not after local time");
  fail_unless (packet->transmit_timevalue < gst_clock_get_time (clock), "remote time in the future");

  prev_receive_timevalue = packet->receive_timevalue;
  prev_transmit_timevalue = packet->transmit_timevalue;
  
  g_free (packet);

  packet = gst_dvb_css_wc_packet_receive (socket, NULL, NULL);  
  fail_unless (packet != NULL, "failed to receive packet");
  fail_unless (packet->message_type == GST_DVB_CSS_WC_MSG_FOLLOWUP, "wrong msg type");
  fail_unless (packet->originate_timevalue_secs == local_secs, "originate_timevalue_secs is not the same");
  fail_unless (packet->originate_timevalue_nanos == local_nanos, "originate_timevalue_nanos is not the same");
  fail_unless (packet->receive_timevalue < packet->transmit_timevalue, "remote time not after local time");
  fail_unless (packet->transmit_timevalue < gst_clock_get_time (clock), "remote time in the future");
  
  fail_unless (prev_receive_timevalue == packet->receive_timevalue, "remote time not after local time");
  fail_unless (prev_transmit_timevalue < packet->transmit_timevalue, "remote time not after local time");
   
  g_free (packet);
    
  
  
  packet = gst_dvb_css_wc_packet_new (NULL);
  fail_unless (packet != NULL, "failed to create packet");
  packet->message_type = GST_DVB_CSS_WC_MSG_REQUEST;  
  fail_unless (gst_dvb_css_wc_packet_send (packet, socket, server_addr, NULL));
  g_free (packet);
  
  packet = gst_dvb_css_wc_packet_new (NULL);
  fail_unless (packet != NULL, "failed to create packet");
  packet->message_type = GST_DVB_CSS_WC_MSG_RESPONSE;    //wrong msg ignored by server
  fail_unless (gst_dvb_css_wc_packet_send (packet, socket, server_addr, NULL));
  g_free (packet);
  
  packet = gst_dvb_css_wc_packet_receive (socket, NULL, NULL);  
  fail_unless (packet != NULL, "failed to receive packet");
  fail_unless (packet->message_type == GST_DVB_CSS_WC_MSG_RESPONSE_WITH_FOLLOWUP, "wrong msg type");
  g_free (packet);
  
  g_object_unref (socket);
  g_object_unref (server_addr);

  gst_object_unref (wc);
  gst_object_unref (clock);
}
示例#29
0
static GSocket *
gst_switch_server_listen (GstSwitchServer *srv, gint port,
    gint *bound_port)
{
  GError *err = NULL;
  GInetAddress *addr;
  GSocket *socket = NULL;
  GSocketAddress *saddr;
  GResolver *resolver;
  gchar *ip;

  *bound_port = 0;

  /* look up name if we need to */
  addr = g_inet_address_new_from_string (srv->host);
  if (!addr) {
    GList *results;

    resolver = g_resolver_get_default ();
    results = g_resolver_lookup_by_name (resolver, srv->host,
        srv->cancellable, &err);
    if (!results)
      goto resolve_no_name;

    addr = G_INET_ADDRESS (g_object_ref (results->data));

    g_resolver_free_addresses (results);
    g_object_unref (resolver);
  }

  ip = g_inet_address_to_string (addr);
  saddr = g_inet_socket_address_new (addr, port);
  g_object_unref (addr);

  /* create the server listener socket */
  socket = g_socket_new (g_socket_address_get_family (saddr),
      G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP, &err);
  if (!socket)
    goto socket_new_failed;
  
  /* bind it */
  if (!g_socket_bind (socket, saddr, TRUE, &err))
    goto socket_bind_failed;

  g_object_unref (saddr);

  /* listen on the socket */
  g_socket_set_listen_backlog (socket, GST_SWITCH_SERVER_LISTEN_BACKLOG);
  if (!g_socket_listen (socket, &err))
    goto socket_listen_failed;

  if (port == 0) {
    saddr = g_socket_get_local_address (socket, NULL);
    *bound_port = g_inet_socket_address_get_port ((GInetSocketAddress *) saddr);
    g_object_unref (saddr);
  } else {
    *bound_port = port;
  }

  INFO ("Listening on %s (%s:%d)", srv->host, ip, *bound_port);

  g_free (ip);

  //g_atomic_int_set (&srv->bound_port, bound_port);
  //g_object_notify (G_OBJECT (src), "bound-port");
  return socket;

  /* Errors Handling */

 resolve_no_name:
  {
    ERROR ("resolve: %s", err->message);
    g_object_unref (resolver);
    g_object_unref (addr);
    return NULL;
  }

 socket_new_failed:
  {
    ERROR ("new socket: %s", err->message);
    g_clear_error (&err);
    g_object_unref (saddr);
    g_free (ip);
    return NULL;
  }

 socket_bind_failed:
  {
    ERROR ("bind socket: %s", err->message);
    g_clear_error (&err);
    g_object_unref (saddr);
    g_free (ip);
    return NULL;
  }

 socket_listen_failed:
  {
    ERROR ("listen socket: %s", err->message);
    g_clear_error (&err);
    g_object_unref (saddr);
    g_free (ip);
    return NULL;
  }
}
示例#30
0
NiceSocket *
nice_tcp_bsd_socket_new (GMainContext *ctx, NiceAddress *addr)
{
  union {
    struct sockaddr_storage storage;
    struct sockaddr addr;
  } name;
  NiceSocket *sock;
  TcpPriv *priv;
  GSocket *gsock = NULL;
  GError *gerr = NULL;
  gboolean gret = FALSE;
  GSocketAddress *gaddr;

  if (addr == NULL) {
    /* We can't connect a tcp socket with no destination address */
    return NULL;
  }

  sock = g_slice_new0 (NiceSocket);

  nice_address_copy_to_sockaddr (addr, &name.addr);

  if (name.storage.ss_family == AF_UNSPEC || name.storage.ss_family == AF_INET) {
    gsock = g_socket_new (G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM,
        G_SOCKET_PROTOCOL_TCP, NULL);

    name.storage.ss_family = AF_INET;
#ifdef HAVE_SA_LEN
    name.storage.ss_len = sizeof (struct sockaddr_in);
#endif
  } else if (name.storage.ss_family == AF_INET6) {
    gsock = g_socket_new (G_SOCKET_FAMILY_IPV6, G_SOCKET_TYPE_STREAM,
        G_SOCKET_PROTOCOL_TCP, NULL);
    name.storage.ss_family = AF_INET6;
#ifdef HAVE_SA_LEN
    name.storage.ss_len = sizeof (struct sockaddr_in6);
#endif
  }

  if (gsock == NULL) {
    g_slice_free (NiceSocket, sock);
    return NULL;
  }

  gaddr = g_socket_address_new_from_native (&name.addr, sizeof (name));
  if (gaddr == NULL) {
    g_object_unref (gsock);
    g_slice_free (NiceSocket, sock);
    return NULL;
  }

  /* GSocket: All socket file descriptors are set to be close-on-exec. */
  g_socket_set_blocking (gsock, false);

  gret = g_socket_connect (gsock, gaddr, NULL, &gerr);
  g_object_unref (gaddr);

  if (gret == FALSE) {
    if (g_error_matches (gerr, G_IO_ERROR, G_IO_ERROR_PENDING) == FALSE) {
      g_error_free (gerr);
      g_socket_close (gsock, NULL);
      g_object_unref (gsock);
      g_slice_free (NiceSocket, sock);
      return NULL;
    }
    g_error_free (gerr);
  }

  gaddr = g_socket_get_local_address (gsock, NULL);
  if (gaddr == NULL ||
      !g_socket_address_to_native (gaddr, &name.addr, sizeof (name), NULL)) {
    g_slice_free (NiceSocket, sock);
    g_socket_close (gsock, NULL);
    g_object_unref (gsock);
    return NULL;
  }
  g_object_unref (gaddr);

  nice_address_set_from_sockaddr (&sock->addr, &name.addr);

  sock->priv = priv = g_slice_new0 (TcpPriv);

  if (ctx == NULL)
    ctx = g_main_context_default ();
  priv->context = g_main_context_ref (ctx);
  priv->server_addr = *addr;
  priv->error = FALSE;

  sock->fileno = gsock;
  sock->send_messages = socket_send_messages;
  sock->recv_messages = socket_recv_messages;
  sock->is_reliable = socket_is_reliable;
  sock->close = socket_close;

  return sock;
}