+static int first_free_port(uint32_t *portbits)
+{
+ int port;
+
+ port = HTTP_PORT_MIN;
+ while (port <= HTTP_PORT_MAX && !~portbits[HTTP_PORT_AIDX(port)])
+ port += 32;
+ while (port <= HTTP_PORT_MAX && HTTP_PORT_TEST(portbits, port))
+ port++;
+ if (port > HTTP_PORT_MAX) {
+ ERROR("Can't compute a valid port");
+ errno = EADDRNOTAVAIL;
+ port = -1;
+ }
+ return port;
+}
+
+static int get_port()
+{
+ int port;
+
+ /* ensure existing port bitmap */
+ if (port_bits == NULL) {
+ port_bits = malloc(HTTP_PORT_ACNT * sizeof(uint32_t));
+ if (port_bits == NULL || update_portbits(port_bits) < 0)
+ return -1;
+ }
+
+ /* allocates the port */
+ port = first_free_port(port_bits);
+ if (port >= 0)
+ HTTP_PORT_SET(port_bits, port);
+
+ return port;
+}
+