+/**
+ * Parse and validate URL string.
+ *
+ * The URL syntax is loosely based on RFC 3986, supporting one of
+ * - "["host"]"[:port] for native IPv6 addresses and
+ * - host[:port] for IPv4 hostnames and DNS names.
+ *
+ * Native IPv6 addresses must be enclosed in square brackets, since
+ * otherwise there is an ambiguity with the port separator `:'.
+ * The 'port' part is always considered to be a number; if absent,
+ * it is set to -1, to indicate that a default port is to be used.
+ *
+ * The following are valid examples:
+ * - 10.10.1.1
+ * - 10.10.1.2:8000
+ * - localhost
+ * - localhost:8001
+ * - [::1]:8000
+ * - [badc0de::1]
+ *
+ * \param url The URL string to take apart.
+ * \param host To return the copied host part of \a url.
+ * \param hostlen The maximum length of \a host.
+ * \param port To return the port number (if any) of \a url.
+ *
+ * \return Pointer to \a host, or NULL if failed.
+ * If NULL is returned, \a host and \a portnum are undefined. If no
+ * port number was present in \a url, \a portnum is set to -1.
+ *
+ * \sa RFC 3986, 3.2.2/3.2.3
+ */
+char *parse_url(const char *url,
+ char *host, ssize_t hostlen,
+ int32_t *port)
+{
+ const char *o = url;
+ char *c = host, *end = c + (hostlen - 1);
+
+ *port = -1;
+
+ if (o == NULL || hostlen < 1)
+ goto failed;
+
+ if (*o == '[') {
+ for (++o; (*c = *o == ']' ? '\0' : *o); c++, o++)
+ if (c == end)
+ goto failed;
+
+ if (*o++ != ']' || (*o != '\0' && *o != ':'))
+ goto failed;
+ } else {
+ for (; (*c = *o == ':'? '\0' : *o); c++, o++)
+ if (c == end)
+ goto failed;
+ }
+
+ if (*o == ':')
+ if (para_atoi32(++o, port) < 0 ||
+ *port < 0 || *port > 0xffff)
+ goto failed;
+
+ if (host_string_ok(host))
+ return host;
+failed:
+ *host = '\0';
+ return NULL;
+}
+
+/**
+ * Stringify port number, resolve into service name where defined.
+ * \param port 2-byte port number, in host-byte-order.
+ * \param transport Transport protocol name (e.g. "udp", "tcp"), or NULL.
+ * \return Pointer to static result buffer.
+ *
+ * \sa getservent(3), services(5), nsswitch.conf(5)
+ */
+const char *stringify_port(int port, const char *transport)
+{
+ static char service[NI_MAXSERV];
+
+ if (port < 0 || port > 0xFFFF) {
+ snprintf(service, sizeof(service), "undefined (%d)", port);
+ } else {
+ struct servent *se = getservbyport(htons(port), transport);
+
+ if (se == NULL)
+ snprintf(service, sizeof(service), "%u", port);
+ else
+ snprintf(service, sizeof(service), "%s", se->s_name);
+ }
+ return service;
+}
+
+/**
+ * Determine the socket type for a given layer-4 protocol.
+ *
+ * \param l4type The symbolic name of the transport-layer protocol.
+ *
+ * \sa ip(7), socket(2)
+ */
+static inline int sock_type(const unsigned l4type)
+{
+ switch (l4type) {
+ case IPPROTO_UDP: return SOCK_DGRAM;
+ case IPPROTO_TCP: return SOCK_STREAM;
+ case IPPROTO_DCCP: return SOCK_DCCP;
+ }
+ return -1; /* not supported here */
+}
+
+/**
+ * Pretty-print transport-layer name.
+ */
+static const char *layer4_name(const unsigned l4type)
+{
+ switch (l4type) {
+ case IPPROTO_UDP: return "UDP";
+ case IPPROTO_TCP: return "TCP";
+ case IPPROTO_DCCP: return "DCCP";
+ }
+ return "UNKNOWN PROTOCOL";
+}
+
+/**
+ * Flowopts: Transport-layer independent encapsulation of socket options.
+ *
+ * These collect individual socket options into a queue, which is disposed of
+ * directly after makesock(). The 'pre_conn_opt' structure is for internal use
+ * only and should not be visible elsewhere.
+ *
+ * \sa setsockopt(2), makesock()
+ */
+struct pre_conn_opt {
+ int sock_level; /**< Second argument to setsockopt() */
+ int sock_option; /**< Third argument to setsockopt() */
+ char *opt_name; /**< Stringified \a sock_option */
+ void *opt_val; /**< Fourth argument to setsockopt() */
+ socklen_t opt_len; /**< Fifth argument to setsockopt() */
+
+ struct list_head node; /**< FIFO, as sockopt order matters. */
+};
+
+/** FIFO list of pre-connection socket options to be set */
+struct flowopts {
+ struct list_head sockopts;
+};
+
+struct flowopts *flowopt_new(void)
+{
+ struct flowopts *new = para_malloc(sizeof(*new));
+
+ INIT_LIST_HEAD(&new->sockopts);
+ return new;
+}
+
+/**
+ * Append new socket option to flowopt queue.
+ *
+ * \param fo The flowopt queue to append to.
+ * \param lev Level at which \a opt resides.
+ * \param opt New option to add.
+ * \param name Stringified name of \a opt.
+ * \param val The value to set \a opt to.
+ * \param len Length of \a val.
+ *
+ * \sa setsockopt(2)
+ */
+void flowopt_add(struct flowopts *fo, int lev, int opt,
+ const char *name, const void *val, int len)
+{
+ struct pre_conn_opt *new = para_malloc(sizeof(*new));
+
+ new->sock_option = opt;
+ new->sock_level = lev;
+ new->opt_name = para_strdup(name);
+
+ if (val == NULL) {
+ new->opt_val = NULL;
+ new->opt_len = 0;
+ } else {
+ new->opt_val = para_malloc(len);
+ new->opt_len = len;
+ memcpy(new->opt_val, val, len);
+ }
+
+ list_add_tail(&new->node, &fo->sockopts);
+}
+
+void flowopt_add_bool(struct flowopts *fo, int lev, int opt,
+ const char *optname, bool on_or_off)
+{
+ int on = on_or_off; /* kernel takes 'int' */
+
+ flowopt_add(fo, lev, opt, optname, &on, sizeof(on));
+}
+
+/** Set the entire bunch of pre-connection options at once. */
+static void flowopt_setopts(int sockfd, struct flowopts *fo)
+{
+ struct pre_conn_opt *pc;
+
+ if (fo == NULL)
+ return;
+
+ list_for_each_entry(pc, &fo->sockopts, node)
+ if (setsockopt(sockfd, pc->sock_level, pc->sock_option,
+ pc->opt_val, pc->opt_len) < 0) {
+ PARA_EMERG_LOG("Can not set %s socket option: %s",
+ pc->opt_name, strerror(errno));
+ exit(EXIT_FAILURE);
+ }
+}
+
+static void flowopt_cleanup(struct flowopts *fo)
+{
+ struct pre_conn_opt *cur, *next;
+
+ if (fo == NULL)
+ return;
+
+ list_for_each_entry_safe(cur, next, &fo->sockopts, node) {
+ free(cur->opt_name);
+ free(cur->opt_val);
+ free(cur);
+ }
+ free(fo);
+}
+
+/**
+ * Resolve IPv4/IPv6 address and create a ready-to-use active or passive socket.
+ *
+ * \param l4type The layer-4 type (\p IPPROTO_xxx).
+ * \param passive Whether this is a passive (1) or active (0) socket.
+ * \param host Remote or local hostname or IPv/6 address string.
+ * \param port_number Decimal port number.
+ * \param fo Socket options to be set before making the connection.
+ *
+ * This creates a ready-made IPv4/v6 socket structure after looking up the
+ * necessary parameters. The interpretation of \a host depends on the value of
+ * \a passive:
+ * - on a passive socket host is interpreted as an interface IPv4/6 address
+ * (can be left NULL);
+ * - on an active socket, \a host is the peer DNS name or IPv4/6 address
+ * to connect to;
+ * - \a port_number is in either case the numeric port number (not service
+ * string).
+ *
+ * Furthermore, bind(2) is called on passive sockets, and connect(2) on active
+ * sockets. The algorithm tries all possible address combinations until it
+ * succeeds. If \a fo is supplied, options are set and cleanup is performed.
+ *
+ * \return This function returns 1 on success and \a -E_ADDRESS_LOOKUP when no
+ * matching connection could be set up (with details in the error log).
+ *
+ * \sa ipv6(7), getaddrinfo(3), bind(2), connect(2).
+ */
+int makesock(unsigned l4type, bool passive,
+ const char *host, uint16_t port_number,
+ struct flowopts *fo)
+{
+ struct addrinfo *local = NULL, *src = NULL, *remote = NULL,
+ *dst = NULL, hints;
+ unsigned int l3type = AF_UNSPEC;
+ int rc, on = 1, sockfd = -1,
+ socktype = sock_type(l4type);
+ char port[6]; /* port number has at most 5 digits */
+
+ sprintf(port, "%u", port_number);
+ /* Set up address hint structure */
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = l3type;
+ hints.ai_socktype = socktype;
+ /*
+ * getaddrinfo does not support SOCK_DCCP, so for the sake of lookup
+ * (and only then) pretend to be UDP.
+ */
+ if (l4type == IPPROTO_DCCP)
+ hints.ai_socktype = SOCK_DGRAM;
+
+ /* only use addresses available on the host */
+ hints.ai_flags = AI_ADDRCONFIG;
+ if (l3type == AF_INET6)
+ /* use v4-mapped-v6 if no v6 addresses found */
+ hints.ai_flags |= AI_V4MAPPED | AI_ALL;
+
+ if (passive && host == NULL)
+ hints.ai_flags |= AI_PASSIVE;
+
+ /* Obtain local/remote address information */
+ if ((rc = getaddrinfo(host, port, &hints, passive ? &local : &remote))) {
+ PARA_ERROR_LOG("can not resolve %s address %s#%s: %s.\n",
+ layer4_name(l4type),
+ host? host : (passive? "[loopback]" : "[localhost]"),
+ port, gai_strerror(rc));
+ rc = -E_ADDRESS_LOOKUP;
+ goto out;
+ }
+
+ /* Iterate over all src/dst combination, exhausting dst first */
+ for (src = local, dst = remote; src != NULL || dst != NULL; /* no op */ ) {
+ if (src && dst && src->ai_family == AF_INET
+ && dst->ai_family == AF_INET6)
+ goto get_next_dst; /* v4 -> v6 is not possible */
+
+ sockfd = socket(src ? src->ai_family : dst->ai_family,
+ socktype, l4type);
+ if (sockfd < 0)
+ goto get_next_dst;
+
+ /*
+ * Reuse the address on passive sockets to avoid failure on
+ * restart (protocols using listen()) and when creating
+ * multiple listener instances (UDP multicast).
+ */
+ if (passive && setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
+ &on, sizeof(on)) == -1) {
+ rc = errno;
+ close(sockfd);
+ PARA_ERROR_LOG("can not set SO_REUSEADDR: %s\n",
+ strerror(rc));
+ rc = -ERRNO_TO_PARA_ERROR(rc);