1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! PFD Contents IE.
//!
//! According to 3GPP TS 29.244, the PFD Contents IE contains the description of a PFD
//! with flags indicating which fields are present (FD, URL, DN, CP, DNP, AFD, AURL, ADNP).
//!
//! **Flow Description Encoding**: The Flow Description field, when present, shall be encoded
//! as an OctetString as specified in clause 6.4.3.7 of 3GPP TS 29.251, which references
//! the IP filter rule syntax from 3GPP TS 29.212 clause 5.4.2. Flow descriptions should follow
//! the format: `action dir proto from src to dst \[options\]`
//!
//! Example flow descriptions:
//! - `"permit out tcp from any to any port 80"`
//! - `"deny in udp from 192.168.1.0/24 to any"`
//! - `"permit out ip from any to 10.0.0.0/8"`
use crate::error::PfcpError;
use crate::ie::{Ie, IeType};
/// Represents PFD Contents Information Element.
///
/// According to 3GPP TS 29.244 Figure 8.2.39-1, PFD Contents IE contains packet flow
/// description information with the following optional fields:
///
/// - **Flow Description (FD)**: IP filter rule as OctetString per 3GPP TS 29.251 clause 6.4.3.7
/// - **URL**: Application URL pattern
/// - **Domain Name (DN)**: Domain name pattern
/// - **Custom PFD Content (CP)**: Vendor-specific detection content
/// - **Domain Name Protocol (DNP)**: Protocol associated with domain name
/// - **Additional Flow Description (AFD)**: Additional IP filter rules
/// - **Additional URL (AURL)**: Additional URL patterns
/// - **Additional Domain Name and Protocol (ADNP)**: Additional domain/protocol pairs
///
/// The flags field indicates which optional fields are present using bit positions 0-7.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PfdContents {
pub flags: u8,
/// Flow Description as IP filter rule (3GPP TS 29.251 clause 6.4.3.7).
/// Format: "action dir proto from src to dst \[options\]"
/// Example: "permit out tcp from any to any port 80"
pub flow_description: Option<String>,
pub url: Option<String>,
pub domain_name: Option<String>,
pub custom_pfd_content: Option<String>,
pub domain_name_protocol: Option<String>,
/// Additional Flow Descriptions as IP filter rules (3GPP TS 29.251 clause 6.4.3.7).
/// Each entry follows the same format as flow_description.
pub additional_flow_description: Vec<String>,
pub additional_url: Vec<String>,
pub additional_domain_name_and_protocol: Vec<String>,
}
/// Builder for PfdContents Information Element.
///
/// According to 3GPP TS 29.244, PFD Contents IE contains the description of a PFD
/// with flags indicating which fields are present (FD, URL, DN, CP, DNP, AFD, AURL, ADNP).
#[derive(Debug, Default)]
pub struct PfdContentsBuilder {
flow_description: Option<String>,
url: Option<String>,
domain_name: Option<String>,
custom_pfd_content: Option<String>,
domain_name_protocol: Option<String>,
additional_flow_description: Vec<String>,
additional_url: Vec<String>,
additional_domain_name_and_protocol: Vec<String>,
}
impl PfdContentsBuilder {
/// Creates a new PfdContents builder.
pub fn new() -> Self {
Self::default()
}
/// Sets the flow description (FD flag bit 0).
///
/// The flow description shall be an IP filter rule as specified in 3GPP TS 29.251 clause 6.4.3.7.
/// Format: "action dir proto from src to dst \[options\]"
///
/// # Examples
/// ```rust
/// # use rs_pfcp::ie::pfd_contents::PfdContentsBuilder;
/// let pfd = PfdContentsBuilder::new()
/// .flow_description("permit out tcp from any to any port 80")
/// .build()
/// .unwrap();
/// ```
pub fn flow_description<S: Into<String>>(mut self, flow_description: S) -> Self {
self.flow_description = Some(flow_description.into());
self
}
/// Sets the URL (URL flag bit 1).
pub fn url<S: Into<String>>(mut self, url: S) -> Self {
self.url = Some(url.into());
self
}
/// Sets the domain name (DN flag bit 2).
pub fn domain_name<S: Into<String>>(mut self, domain_name: S) -> Self {
self.domain_name = Some(domain_name.into());
self
}
/// Sets the custom PFD content (CP flag bit 3).
pub fn custom_pfd_content<S: Into<String>>(mut self, custom_pfd_content: S) -> Self {
self.custom_pfd_content = Some(custom_pfd_content.into());
self
}
/// Sets the domain name protocol (DNP flag bit 4).
pub fn domain_name_protocol<S: Into<String>>(mut self, domain_name_protocol: S) -> Self {
self.domain_name_protocol = Some(domain_name_protocol.into());
self
}
/// Adds an additional flow description (AFD flag bit 5).
///
/// Each additional flow description shall be an IP filter rule as specified in 3GPP TS 29.251 clause 6.4.3.7.
/// Multiple additional flow descriptions can be added using multiple calls to this method.
pub fn add_additional_flow_description<S: Into<String>>(mut self, flow_description: S) -> Self {
self.additional_flow_description
.push(flow_description.into());
self
}
/// Sets multiple additional flow descriptions (AFD flag bit 5).
///
/// Each flow description shall be an IP filter rule as specified in 3GPP TS 29.251 clause 6.4.3.7.
pub fn additional_flow_descriptions<I, S>(mut self, flow_descriptions: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.additional_flow_description =
flow_descriptions.into_iter().map(|s| s.into()).collect();
self
}
/// Adds an additional URL (AURL flag bit 6).
pub fn add_additional_url<S: Into<String>>(mut self, url: S) -> Self {
self.additional_url.push(url.into());
self
}
/// Sets multiple additional URLs (AURL flag bit 6).
pub fn additional_urls<I, S>(mut self, urls: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.additional_url = urls.into_iter().map(|s| s.into()).collect();
self
}
/// Adds an additional domain name and protocol (ADNP flag bit 7).
pub fn add_additional_domain_name_and_protocol<S: Into<String>>(
mut self,
domain_name_and_protocol: S,
) -> Self {
self.additional_domain_name_and_protocol
.push(domain_name_and_protocol.into());
self
}
/// Sets multiple additional domain names and protocols (ADNP flag bit 7).
pub fn additional_domain_names_and_protocols<I, S>(
mut self,
domain_names_and_protocols: I,
) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.additional_domain_name_and_protocol = domain_names_and_protocols
.into_iter()
.map(|s| s.into())
.collect();
self
}
/// Builds the PfdContents Information Element.
///
/// # Errors
/// Returns an error if no fields are set (PFD Contents must have at least one field).
pub fn build(self) -> Result<PfdContents, PfcpError> {
// Validate that at least one field is set
if self.flow_description.is_none()
&& self.url.is_none()
&& self.domain_name.is_none()
&& self.custom_pfd_content.is_none()
&& self.domain_name_protocol.is_none()
&& self.additional_flow_description.is_empty()
&& self.additional_url.is_empty()
&& self.additional_domain_name_and_protocol.is_empty()
{
return Err(PfcpError::validation_error(
"PfdContentsBuilder",
"fields",
"PfdContents must have at least one field set",
));
}
// Calculate flags based on which fields are set (3GPP TS 29.244 Figure 8.2.39-1)
let mut flags = 0;
if self.flow_description.is_some() {
flags |= 0x01; // FD - Flow Description
}
if self.url.is_some() {
flags |= 0x02; // URL - URL
}
if self.domain_name.is_some() {
flags |= 0x04; // DN - Domain Name
}
if self.custom_pfd_content.is_some() {
flags |= 0x08; // CP - Custom PFD Content
}
if self.domain_name_protocol.is_some() {
flags |= 0x10; // DNP - Domain Name Protocol
}
if !self.additional_flow_description.is_empty() {
flags |= 0x20; // AFD - Additional Flow Description
}
if !self.additional_url.is_empty() {
flags |= 0x40; // AURL - Additional URL
}
if !self.additional_domain_name_and_protocol.is_empty() {
flags |= 0x80; // ADNP - Additional Domain Name and Protocol
}
Ok(PfdContents {
flags,
flow_description: self.flow_description,
url: self.url,
domain_name: self.domain_name,
custom_pfd_content: self.custom_pfd_content,
domain_name_protocol: self.domain_name_protocol,
additional_flow_description: self.additional_flow_description,
additional_url: self.additional_url,
additional_domain_name_and_protocol: self.additional_domain_name_and_protocol,
})
}
}
impl PfdContents {
/// Creates a new PfdContents builder.
pub fn builder() -> PfdContentsBuilder {
PfdContentsBuilder::new()
}
/// Creates a PfdContents with just a flow description.
///
/// The flow description shall be an IP filter rule as specified in 3GPP TS 29.251 clause 6.4.3.7.
/// Format: "action dir proto from src to dst \[options\]"
pub fn flow_description<S: Into<String>>(flow_description: S) -> Result<Self, PfcpError> {
PfdContentsBuilder::new()
.flow_description(flow_description)
.build()
}
/// Creates a PfdContents with just a URL.
pub fn url<S: Into<String>>(url: S) -> Result<Self, PfcpError> {
PfdContentsBuilder::new().url(url).build()
}
/// Creates a PfdContents with just a domain name.
pub fn domain_name<S: Into<String>>(domain_name: S) -> Result<Self, PfcpError> {
PfdContentsBuilder::new().domain_name(domain_name).build()
}
/// Creates a PfdContents with flow description and URL (common pattern).
///
/// The flow description shall be an IP filter rule as specified in 3GPP TS 29.251 clause 6.4.3.7.
pub fn flow_and_url<S1: Into<String>, S2: Into<String>>(
flow_description: S1,
url: S2,
) -> Result<Self, PfcpError> {
PfdContentsBuilder::new()
.flow_description(flow_description)
.url(url)
.build()
}
/// Creates a PfdContents with domain name and protocol (common pattern).
pub fn domain_and_protocol<S1: Into<String>, S2: Into<String>>(
domain_name: S1,
protocol: S2,
) -> Result<Self, PfcpError> {
PfdContentsBuilder::new()
.domain_name(domain_name)
.domain_name_protocol(protocol)
.build()
}
/// Marshals the PFD Contents into a byte vector, which is the payload of the IE.
///
/// Encoding follows 3GPP TS 29.244 Figure 8.2.39-1. Flow descriptions are encoded
/// as OctetString per 3GPP TS 29.251 clause 6.4.3.7 (length-prefixed UTF-8 strings).
pub fn marshal(&self) -> Vec<u8> {
let mut data = vec![self.flags, 0]; // Flags and spare
fn write_field(data: &mut Vec<u8>, field: &Option<String>) {
if let Some(ref val) = field {
data.extend_from_slice(&(val.len() as u16).to_be_bytes());
data.extend_from_slice(val.as_bytes());
}
}
fn write_vec_field(data: &mut Vec<u8>, vec_field: &Vec<String>) {
for val in vec_field {
data.extend_from_slice(&(val.len() as u16).to_be_bytes());
data.extend_from_slice(val.as_bytes());
}
}
write_field(&mut data, &self.flow_description);
write_field(&mut data, &self.url);
write_field(&mut data, &self.domain_name);
write_field(&mut data, &self.custom_pfd_content);
write_field(&mut data, &self.domain_name_protocol);
write_vec_field(&mut data, &self.additional_flow_description);
write_vec_field(&mut data, &self.additional_url);
write_vec_field(&mut data, &self.additional_domain_name_and_protocol);
data
}
/// Unmarshals a byte slice into PFD Contents.
pub fn unmarshal(payload: &[u8]) -> Result<Self, PfcpError> {
if payload.len() < 2 {
return Err(PfcpError::invalid_length(
"PFD Contents",
IeType::PfdContents,
2,
payload.len(),
));
}
let flags = payload[0];
let mut offset = 2;
let read_field = |offset: &mut usize| -> Result<Option<String>, PfcpError> {
if payload.len() < *offset + 2 {
return Ok(None);
}
let len = u16::from_be_bytes([payload[*offset], payload[*offset + 1]]) as usize;
*offset += 2;
if payload.len() < *offset + len {
return Err(PfcpError::invalid_length(
"PFD Contents field",
IeType::PfdContents,
*offset + len,
payload.len(),
));
}
let val = String::from_utf8(payload[*offset..*offset + len].to_vec()).map_err(|e| {
PfcpError::invalid_value("PFD Contents", "field", format!("invalid UTF-8: {}", e))
})?;
*offset += len;
Ok(Some(val))
};
let flow_description = if flags & 0x01 != 0 {
read_field(&mut offset)?
} else {
None
};
let url = if flags & 0x02 != 0 {
read_field(&mut offset)?
} else {
None
};
let domain_name = if flags & 0x04 != 0 {
read_field(&mut offset)?
} else {
None
};
let custom_pfd_content = if flags & 0x08 != 0 {
read_field(&mut offset)?
} else {
None
};
let domain_name_protocol = if flags & 0x10 != 0 {
read_field(&mut offset)?
} else {
None
};
// For additional fields, we need to know how many entries there are
// The spec doesn't specify this clearly, so we'll read until we hit different flag types
// or end of data. This is a limitation of the current spec format.
let mut additional_flow_description = Vec::new();
let mut additional_url = Vec::new();
let mut additional_domain_name_and_protocol = Vec::new();
// Read additional fields in the order they appear
if flags & 0x20 != 0 {
// AFD - Additional Flow Description
// Read all consecutive additional flow descriptions
while offset < payload.len() {
if let Some(val) = read_field(&mut offset)? {
additional_flow_description.push(val);
} else {
break;
}
// Check if we should continue reading AFD or move to next field type
// This is a heuristic since spec doesn't clearly define boundaries
if flags & 0x40 != 0 || flags & 0x80 != 0 {
// We have more field types coming, so limit AFD entries
// In practice, implementations typically use just one entry per type
break;
}
}
}
if flags & 0x40 != 0 {
// AURL - Additional URL
while offset < payload.len() {
if let Some(val) = read_field(&mut offset)? {
additional_url.push(val);
} else {
break;
}
// Check if we should continue reading AURL or move to next field type
if flags & 0x80 != 0 {
// We have ADNP coming, so limit AURL entries
break;
}
}
}
if flags & 0x80 != 0 {
// ADNP - Additional Domain Name and Protocol
while offset < payload.len() {
if let Some(val) = read_field(&mut offset)? {
additional_domain_name_and_protocol.push(val);
} else {
break;
}
}
}
Ok(PfdContents {
flags,
flow_description,
url,
domain_name,
custom_pfd_content,
domain_name_protocol,
additional_flow_description,
additional_url,
additional_domain_name_and_protocol,
})
}
/// Wraps the PFD Contents in a PFDContents IE.
pub fn to_ie(&self) -> Ie {
Ie::new(IeType::PfdContents, self.marshal())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pfd_contents_builder_basic() {
let pfd_contents = PfdContentsBuilder::new()
.flow_description("flow desc")
.url("http://example.com")
.domain_name("example.com")
.build()
.unwrap();
assert_eq!(pfd_contents.flags, 0x07); // FD | URL | DN
assert_eq!(pfd_contents.flow_description, Some("flow desc".to_string()));
assert_eq!(pfd_contents.url, Some("http://example.com".to_string()));
assert_eq!(pfd_contents.domain_name, Some("example.com".to_string()));
}
#[test]
fn test_pfd_contents_builder_all_fields() {
let pfd_contents = PfdContentsBuilder::new()
.flow_description("flow desc")
.url("http://example.com")
.domain_name("example.com")
.custom_pfd_content("custom content")
.domain_name_protocol("https")
.add_additional_flow_description("additional flow 1")
.add_additional_flow_description("additional flow 2")
.add_additional_url("http://additional1.com")
.add_additional_url("http://additional2.com")
.add_additional_domain_name_and_protocol("additional domain protocol")
.build()
.unwrap();
assert_eq!(pfd_contents.flags, 0xFF); // All flags set
assert_eq!(pfd_contents.additional_flow_description.len(), 2);
assert_eq!(pfd_contents.additional_url.len(), 2);
assert_eq!(pfd_contents.additional_domain_name_and_protocol.len(), 1);
}
#[test]
fn test_pfd_contents_builder_with_iterators() {
let flow_descriptions = vec!["flow1", "flow2", "flow3"];
let urls = vec!["http://url1.com", "http://url2.com"];
let domain_protocols = vec!["protocol1", "protocol2"];
let pfd_contents = PfdContentsBuilder::new()
.flow_description("main flow")
.additional_flow_descriptions(flow_descriptions)
.additional_urls(urls)
.additional_domain_names_and_protocols(domain_protocols)
.build()
.unwrap();
assert_eq!(pfd_contents.flags, 0xE1); // FD | AFD | AURL | ADNP
assert_eq!(pfd_contents.additional_flow_description.len(), 3);
assert_eq!(pfd_contents.additional_url.len(), 2);
assert_eq!(pfd_contents.additional_domain_name_and_protocol.len(), 2);
}
#[test]
fn test_pfd_contents_builder_empty_error() {
let result = PfdContentsBuilder::new().build();
assert!(result.is_err());
match result.unwrap_err() {
PfcpError::ValidationError {
builder,
field,
reason,
} => {
assert_eq!(builder, "PfdContentsBuilder");
assert_eq!(field, "fields");
assert!(reason.contains("PfdContents must have at least one field set"));
}
_ => panic!("Expected ValidationError"),
}
}
#[test]
fn test_pfd_contents_convenience_methods() {
// Test flow_description convenience method
let flow_only = PfdContents::flow_description("test flow").unwrap();
assert_eq!(flow_only.flags, 0x01);
assert_eq!(flow_only.flow_description, Some("test flow".to_string()));
// Test url convenience method
let url_only = PfdContents::url("http://test.com").unwrap();
assert_eq!(url_only.flags, 0x02);
assert_eq!(url_only.url, Some("http://test.com".to_string()));
// Test domain_name convenience method
let domain_only = PfdContents::domain_name("test.domain").unwrap();
assert_eq!(domain_only.flags, 0x04);
assert_eq!(domain_only.domain_name, Some("test.domain".to_string()));
// Test flow_and_url convenience method
let flow_and_url = PfdContents::flow_and_url("flow", "http://url.com").unwrap();
assert_eq!(flow_and_url.flags, 0x03); // FD | URL
assert_eq!(flow_and_url.flow_description, Some("flow".to_string()));
assert_eq!(flow_and_url.url, Some("http://url.com".to_string()));
// Test domain_and_protocol convenience method
let domain_and_protocol = PfdContents::domain_and_protocol("domain.com", "https").unwrap();
assert_eq!(domain_and_protocol.flags, 0x14); // DN | DNP
assert_eq!(
domain_and_protocol.domain_name,
Some("domain.com".to_string())
);
assert_eq!(
domain_and_protocol.domain_name_protocol,
Some("https".to_string())
);
}
#[test]
fn test_pfd_contents_marshal_unmarshal() {
let pfd_contents = PfdContentsBuilder::new()
.flow_description("flow desc")
.url("http://example.com")
.domain_name("example.com")
.custom_pfd_content("custom")
.add_additional_flow_description("additional flow")
.build()
.unwrap();
let marshaled = pfd_contents.marshal();
let unmarshaled = PfdContents::unmarshal(&marshaled).unwrap();
assert_eq!(pfd_contents, unmarshaled);
}
#[test]
fn test_pfd_contents_to_ie() {
let pfd_contents = PfdContents::flow_description("test").unwrap();
let ie = pfd_contents.to_ie();
assert_eq!(ie.ie_type, IeType::PfdContents);
assert!(!ie.payload.is_empty());
}
}