xref: /curl/tests/http/test_12_reuse.py (revision 358eae42)
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3#***************************************************************************
4#                                  _   _ ____  _
5#  Project                     ___| | | |  _ \| |
6#                             / __| | | | |_) | |
7#                            | (__| |_| |  _ <| |___
8#                             \___|\___/|_| \_\_____|
9#
10# Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
11#
12# This software is licensed as described in the file COPYING, which
13# you should have received as part of this distribution. The terms
14# are also available at https://curl.se/docs/copyright.html.
15#
16# You may opt to use, copy, modify, merge, publish, distribute and/or sell
17# copies of the Software, and permit persons to whom the Software is
18# furnished to do so, under the terms of the COPYING file.
19#
20# This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
21# KIND, either express or implied.
22#
23# SPDX-License-Identifier: curl
24#
25###########################################################################
26#
27import logging
28import os
29from datetime import datetime, timedelta
30import pytest
31
32from testenv import Env, CurlClient
33
34
35log = logging.getLogger(__name__)
36
37
38@pytest.mark.skipif(condition=not Env.have_ssl_curl(), reason="curl without SSL")
39class TestReuse:
40
41    # check if HTTP/1.1 handles 'Connection: close' correctly
42    @pytest.mark.parametrize("proto", ['http/1.1'])
43    def test_12_01_h1_conn_close(self, env: Env,
44                                 httpd, nghttpx, repeat, proto):
45        httpd.clear_extra_configs()
46        httpd.set_extra_config('base', [
47            'MaxKeepAliveRequests 1',
48        ])
49        httpd.reload()
50        count = 100
51        curl = CurlClient(env=env)
52        urln = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{count-1}]'
53        r = curl.http_download(urls=[urln], alpn_proto=proto)
54        r.check_response(count=count, http_status=200)
55        # Server sends `Connection: close` on every 2nd request, requiring
56        # a new connection
57        delta = 5
58        assert (count/2 - delta) < r.total_connects < (count/2 + delta)
59
60    @pytest.mark.skipif(condition=Env.httpd_is_at_least('2.5.0'),
61                        reason="httpd 2.5+ handles KeepAlives different")
62    @pytest.mark.parametrize("proto", ['http/1.1'])
63    def test_12_02_h1_conn_timeout(self, env: Env,
64                                   httpd, nghttpx, repeat, proto):
65        httpd.clear_extra_configs()
66        httpd.set_extra_config('base', [
67            'KeepAliveTimeout 1',
68        ])
69        httpd.reload()
70        count = 5
71        curl = CurlClient(env=env)
72        urln = f'https://{env.authority_for(env.domain1, proto)}/data.json?[0-{count-1}]'
73        r = curl.http_download(urls=[urln], alpn_proto=proto, extra_args=[
74            '--rate', '30/m',
75        ])
76        r.check_response(count=count, http_status=200)
77        # Connections time out on server before we send another request,
78        assert r.total_connects == count
79
80    @pytest.mark.skipif(condition=not Env.have_h3(), reason="h3 not supported")
81    def test_12_03_alt_svc_h2h3(self, env: Env, httpd, nghttpx):
82        httpd.clear_extra_configs()
83        httpd.reload()
84        count = 2
85        # write a alt-svc file the advises h3 instead of h2
86        asfile = os.path.join(env.gen_dir, 'alt-svc-12_03.txt')
87        ts = datetime.now() + timedelta(hours=24)
88        expires = f'{ts.year:04}{ts.month:02}{ts.day:02} {ts.hour:02}:{ts.minute:02}:{ts.second:02}'
89        with open(asfile, 'w') as fd:
90            fd.write(f'h2 {env.domain1} {env.https_port} h3 {env.domain1} {env.https_port} "{expires}" 0 0')
91        log.info(f'altscv: {open(asfile).readlines()}')
92        curl = CurlClient(env=env)
93        urln = f'https://{env.authority_for(env.domain1, "h2")}/data.json?[0-{count-1}]'
94        r = curl.http_download(urls=[urln], with_stats=True, extra_args=[
95            '--alt-svc', f'{asfile}',
96        ])
97        r.check_response(count=count, http_status=200)
98        # We expect the connection to be reused
99        assert r.total_connects == 1
100        for s in r.stats:
101            assert s['http_version'] == '3', f'{s}'
102
103    def test_12_04_alt_svc_h3h2(self, env: Env, httpd, nghttpx):
104        httpd.clear_extra_configs()
105        httpd.reload()
106        count = 2
107        # write a alt-svc file the advises h2 instead of h3
108        asfile = os.path.join(env.gen_dir, 'alt-svc-12_04.txt')
109        ts = datetime.now() + timedelta(hours=24)
110        expires = f'{ts.year:04}{ts.month:02}{ts.day:02} {ts.hour:02}:{ts.minute:02}:{ts.second:02}'
111        with open(asfile, 'w') as fd:
112            fd.write(f'h3 {env.domain1} {env.https_port} h2 {env.domain1} {env.https_port} "{expires}" 0 0')
113        log.info(f'altscv: {open(asfile).readlines()}')
114        curl = CurlClient(env=env)
115        urln = f'https://{env.authority_for(env.domain1, "h2")}/data.json?[0-{count-1}]'
116        r = curl.http_download(urls=[urln], with_stats=True, extra_args=[
117            '--alt-svc', f'{asfile}',
118        ])
119        r.check_response(count=count, http_status=200)
120        # We expect the connection to be reused
121        assert r.total_connects == 1
122        for s in r.stats:
123            assert s['http_version'] == '2', f'{s}'
124
125    def test_12_05_alt_svc_h3h1(self, env: Env, httpd, nghttpx):
126        httpd.clear_extra_configs()
127        httpd.reload()
128        count = 2
129        # write a alt-svc file the advises h1 instead of h3
130        asfile = os.path.join(env.gen_dir, 'alt-svc-12_05.txt')
131        ts = datetime.now() + timedelta(hours=24)
132        expires = f'{ts.year:04}{ts.month:02}{ts.day:02} {ts.hour:02}:{ts.minute:02}:{ts.second:02}'
133        with open(asfile, 'w') as fd:
134            fd.write(f'h3 {env.domain1} {env.https_port} http/1.1 {env.domain1} {env.https_port} "{expires}" 0 0')
135        log.info(f'altscv: {open(asfile).readlines()}')
136        curl = CurlClient(env=env)
137        urln = f'https://{env.authority_for(env.domain1, "h2")}/data.json?[0-{count-1}]'
138        r = curl.http_download(urls=[urln], with_stats=True, extra_args=[
139            '--alt-svc', f'{asfile}',
140        ])
141        r.check_response(count=count, http_status=200)
142        # We expect the connection to be reused
143        assert r.total_connects == 1
144        # When using http/1.1 from alt-svc, we ALPN-negotiate 'h2,http/1.1' anyway
145        # which means our server gives us h2
146        for s in r.stats:
147            assert s['http_version'] == '2', f'{s}'
148