'Return an available connection ready to be reused
:param req: Request we want to send using the connection.
:param conn_factory: Factory function for connection creation. Receives
req as parameter.'

def get_available_connection(self, req, conn_factory):

    with self._lock:
        retry_count = self.GET_AVAILABLE_CONNECTION_RETRY_NUM
        host = req.get_host()
        while (retry_count > 0):
            if (not req.new_connection):
                for conn in self._hostmap.setdefault(host, []):
                    try:
                        self._free_conns.remove(conn)
                    except ValueError:
                        continue
                    else:
                        self._used_cons.append(conn)
                        msg = 'Reusing    free    %s    to    use    in    new    request'
                        debug((msg % conn))
                        return conn
            else:
                debug('Forcing    the    use    of    a    new    HTTPConnection')
            conn_total = self.get_connections_total(host)
            if (conn_total < self._host_pool_size):
                conn = conn_factory(req)
                self._used_cons.append(conn)
                hostmap = self._hostmap.setdefault(host, [])
                hostmap.append(conn)
                msg = 'Added    %s    to    pool,    current    %s    pool    size:    %s'
                debug((msg % (conn, host, (conn_total + 1))))
                return conn
            else:
                args = (conn_total, self._host_pool_size)
                msg = 'No    free    connections    in    pool    with    size    %s/%s.    Wait...'
                debug((msg % args))
                retry_count -= 1
                time.sleep(self.GET_AVAILABLE_CONNECTION_RETRY_SECS)
        msg = 'HTTP    connection    pool    (keepalive)    waited    too    long    (%s    sec)    for    a    free    connection,    giving    up.    This    usually    occurs    when    w3af    is    scanning    using    a    slow    connection,    the    remote    server    is    slow    (or    applying    QoS    to    IP    addresses    flagged    as    attackers).'
        seconds = (self.GET_AVAILABLE_CONNECTION_RETRY_NUM * self.GET_AVAILABLE_CONNECTION_RETRY_SECS)
        raise ConnectionPoolException((msg % seconds))
