0
# Virtual Host Objects
1
2
Object models for representing nginx virtual hosts and network addresses. These classes provide structured access to nginx configuration elements with comprehensive attribute management and manipulation methods.
3
4
## Capabilities
5
6
### Virtual Host Representation
7
8
The VirtualHost class represents an nginx server block with all its configuration details.
9
10
```python { .api }
11
class VirtualHost:
12
"""Represents an nginx virtual host (server block).
13
14
Args:
15
filep: File path of virtual host
16
addrs: Virtual host addresses
17
ssl: SSLEngine enabled status
18
enabled: Virtual host enabled status
19
names: Server names/aliases
20
raw: Raw parsed server block
21
path: Indices into parsed file for server block access
22
23
Attributes:
24
filep: str - File path of VH
25
addrs: Sequence[Addr] - Virtual host addresses
26
names: set[str] - Server names/aliases of vhost
27
ssl: bool - SSL enabled in vhost
28
enabled: bool - Virtual host is enabled
29
raw: list[Any] - Raw form of parsed server block
30
path: list[int] - Indices for accessing server block
31
"""
32
33
def __init__(self, filep: str, addrs: Sequence[Addr], ssl: bool,
34
enabled: bool, names: set[str], raw: list[Any],
35
path: list[int]) -> None:
36
"""Initialize a virtual host."""
37
```
38
39
### Virtual Host Network Configuration
40
41
Methods for checking IPv4/IPv6 support and network configuration.
42
43
```python { .api }
44
def ipv4_enabled(self) -> bool:
45
"""Check if IPv4 is enabled for this virtual host.
46
47
Returns:
48
True if any address supports IPv4
49
"""
50
51
def ipv6_enabled(self) -> bool:
52
"""Check if IPv6 is enabled for this virtual host.
53
54
Returns:
55
True if any address supports IPv6
56
"""
57
```
58
59
### Virtual Host Content Analysis
60
61
Analyze virtual host configuration content and structure.
62
63
```python { .api }
64
def contains_list(self, test_list: list[Any]) -> bool:
65
"""Check if server block contains specified directive list.
66
67
Args:
68
test_list: List structure to search for
69
70
Returns:
71
True if directive list is found in server block
72
"""
73
74
def has_header(self, header_substring: str) -> bool:
75
"""Check if server has specific header directive.
76
77
Args:
78
header_substring: Header name to search for
79
80
Returns:
81
True if header directive is present
82
"""
83
```
84
85
### Virtual Host Display
86
87
Methods for displaying virtual host information.
88
89
```python { .api }
90
def display_repr(self) -> str:
91
"""Get display representation of virtual host.
92
93
Returns:
94
Human-readable string representation
95
"""
96
97
def __str__(self) -> str:
98
"""String representation of virtual host.
99
100
Returns:
101
Formatted string with file, addresses, names, SSL status
102
"""
103
```
104
105
### Address Representation
106
107
The Addr class represents nginx listen directive addresses with full attribute support.
108
109
```python { .api }
110
class Addr:
111
"""Represents nginx listen directive address.
112
113
Args:
114
host: Address part (hostname, IPv4, IPv6, "", or "*")
115
port: Port number or "*" or ""
116
ssl: Whether directive includes 'ssl'
117
default: Whether directive includes 'default_server'
118
ipv6: Whether this is IPv6 address
119
ipv6only: Whether directive includes 'ipv6only=on'
120
121
Attributes:
122
ssl: bool - SSL enabled on address
123
default: bool - Default server designation
124
ipv6: bool - IPv6 address flag
125
ipv6only: bool - IPv6-only flag
126
unspecified_address: bool - Address is unspecified
127
"""
128
129
UNSPECIFIED_IPV4_ADDRESSES: tuple[str, ...] = ('', '*', '0.0.0.0')
130
CANONICAL_UNSPECIFIED_ADDRESS: str = ''
131
132
def __init__(self, host: str, port: str, ssl: bool, default: bool,
133
ipv6: bool, ipv6only: bool) -> None:
134
"""Initialize address with parameters."""
135
```
136
137
### Address Construction and Parsing
138
139
Create Addr objects from string representations and convert back to strings.
140
141
```python { .api }
142
@classmethod
143
def fromstring(cls, str_addr: str) -> "Addr":
144
"""Initialize Addr from string representation.
145
146
Args:
147
str_addr: Nginx address string (e.g., "80", "127.0.0.1:443 ssl")
148
149
Returns:
150
Parsed nginx address object
151
152
Raises:
153
SocketAddrError: If UNIX-domain socket address is given
154
"""
155
156
def to_string(self, include_default: bool = True) -> str:
157
"""Convert address to string representation.
158
159
Args:
160
include_default: Include default_server in output
161
162
Returns:
163
String representation of address
164
"""
165
166
def __str__(self) -> str:
167
"""String representation of address."""
168
```
169
170
### Address Information Access
171
172
Access individual components of the address.
173
174
```python { .api }
175
def get_addr(self) -> str:
176
"""Get address part of listen directive.
177
178
Returns:
179
Address component (host/IP)
180
"""
181
182
def get_port(self) -> str:
183
"""Get port part of listen directive.
184
185
Returns:
186
Port component
187
"""
188
189
def get_ipv6_exploded(self) -> str:
190
"""Get exploded IPv6 address representation.
191
192
Returns:
193
Exploded IPv6 address string
194
"""
195
196
def normalized_tuple(self) -> tuple[str, str]:
197
"""Get normalized (address, port) tuple.
198
199
Returns:
200
Normalized address and port tuple
201
"""
202
```
203
204
### Address Comparison
205
206
Compare addresses with IPv6 support and unspecified address handling.
207
208
```python { .api }
209
def super_eq(self, other: "Addr") -> bool:
210
"""Check IP/port equality with IPv6 support.
211
212
Args:
213
other: Address to compare with
214
215
Returns:
216
True if addresses are equivalent
217
"""
218
219
def __eq__(self, other: Any) -> bool:
220
"""Full equality comparison including SSL and default status.
221
222
Args:
223
other: Object to compare with
224
225
Returns:
226
True if addresses are fully equal
227
"""
228
```
229
230
## Exception Classes
231
232
```python { .api }
233
class SocketAddrError(Exception):
234
"""Raised when UNIX-domain socket address is encountered.
235
236
UNIX-domain sockets are not supported by the nginx plugin.
237
"""
238
```
239
240
## Usage Examples
241
242
### Working with Virtual Hosts
243
244
```python
245
from certbot_nginx._internal.parser import NginxParser
246
247
# Get virtual hosts from parser
248
parser = NginxParser('/etc/nginx')
249
vhosts = parser.get_vhosts()
250
251
# Examine virtual host properties
252
for vhost in vhosts:
253
print(f"File: {vhost.filep}")
254
print(f"Server names: {vhost.names}")
255
print(f"SSL enabled: {vhost.ssl}")
256
print(f"IPv4 enabled: {vhost.ipv4_enabled()}")
257
print(f"IPv6 enabled: {vhost.ipv6_enabled()}")
258
259
# Check for specific headers
260
has_hsts = vhost.has_header('Strict-Transport-Security')
261
print(f"Has HSTS header: {has_hsts}")
262
263
# Display representation
264
print(f"Display: {vhost.display_repr()}")
265
```
266
267
### Working with Addresses
268
269
```python
270
from certbot_nginx._internal.obj import Addr
271
272
# Parse address from string
273
addr1 = Addr.fromstring('80')
274
addr2 = Addr.fromstring('443 ssl default_server')
275
addr3 = Addr.fromstring('[::]:443 ssl ipv6only=on')
276
277
# Examine address properties
278
print(f"Address 1: {addr1.get_addr()}:{addr1.get_port()}, SSL: {addr1.ssl}")
279
print(f"Address 2: {addr2.get_addr()}:{addr2.get_port()}, SSL: {addr2.ssl}, Default: {addr2.default}")
280
print(f"Address 3: IPv6: {addr3.ipv6}, IPv6-only: {addr3.ipv6only}")
281
282
# Convert back to string
283
print(f"String representation: {addr2.to_string()}")
284
285
# Compare addresses
286
print(f"Addresses equal: {addr1 == addr2}")
287
print(f"IP/port equal: {addr1.super_eq(addr2)}")
288
```
289
290
### Address Construction Examples
291
292
```python
293
# Different address string formats
294
addresses = [
295
'80', # Port only
296
'127.0.0.1:8080', # Host and port
297
'443 ssl', # Port with SSL
298
'192.168.1.1:443 ssl default_server', # Full specification
299
'[::]:80', # IPv6 address
300
'[2001:db8::1]:443 ssl ipv6only=on' # IPv6 with options
301
]
302
303
for addr_str in addresses:
304
try:
305
addr = Addr.fromstring(addr_str)
306
print(f"'{addr_str}' -> {addr}")
307
print(f" Host: '{addr.get_addr()}', Port: '{addr.get_port()}'")
308
print(f" SSL: {addr.ssl}, Default: {addr.default}, IPv6: {addr.ipv6}")
309
except Exception as e:
310
print(f"Error parsing '{addr_str}': {e}")
311
```
312
313
### Virtual Host Analysis
314
315
```python
316
# Find virtual hosts with specific characteristics
317
ssl_vhosts = [vhost for vhost in vhosts if vhost.ssl]
318
ipv6_vhosts = [vhost for vhost in vhosts if vhost.ipv6_enabled()]
319
default_vhosts = [vhost for vhost in vhosts
320
if any(addr.default for addr in vhost.addrs)]
321
322
print(f"SSL virtual hosts: {len(ssl_vhosts)}")
323
print(f"IPv6 virtual hosts: {len(ipv6_vhosts)}")
324
print(f"Default virtual hosts: {len(default_vhosts)}")
325
326
# Check for security headers
327
security_headers = ['Strict-Transport-Security', 'X-Frame-Options', 'X-Content-Type-Options']
328
for vhost in vhosts:
329
headers_present = [header for header in security_headers
330
if vhost.has_header(header)]
331
if headers_present:
332
print(f"VHost {vhost.filep} has headers: {headers_present}")
333
```