-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy pathcliargs.rs
More file actions
318 lines (286 loc) · 10.4 KB
/
cliargs.rs
File metadata and controls
318 lines (286 loc) · 10.4 KB
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
/*
* Copyright (C) 2023 Fastly, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use crate::core::config::get_config_file;
use crate::core::version;
use clap::{arg, Parser};
use std::env;
use std::ffi::CString;
use std::path::PathBuf;
// Struct to hold the command line arguments
#[derive(Parser, Debug)]
#[command(
name= "Pushpin Proxy",
version = version(),
about = "Pushpin proxy component."
)]
pub struct CliArgs {
/// Set path to the configuration file
#[arg(short, long = "config", value_name = "file")]
pub config_file: Option<String>,
/// Set path to the log file
#[arg(short = 'l', long = "logfile", value_name = "file")]
pub log_file: Option<String>,
/// Set log level (0=error, 1=warn, 2=info, 3=debug, 4=trace)
#[arg(short = 'L', long = "loglevel", value_name = "x", default_value_t = 2, value_parser = clap::value_parser!(u32).range(1..=4))]
pub log_level: u32,
/// Override ipc_prefix config option, which is used to add a prefix to all ZeroMQ IPC filenames
#[arg(long, value_name = "prefix")]
pub ipc_prefix: Option<String>,
/// Add route (overrides routes file)
#[arg(long, value_name = "route")]
pub route: Option<Vec<String>>,
}
impl CliArgs {
/// Verifies the command line arguments.
pub fn verify(mut self) -> Self {
let work_dir = env::current_dir().unwrap_or_default();
let config_path: Option<PathBuf> = self.config_file.as_ref().map(PathBuf::from);
// Resolve the config file path using get_config_file
self.config_file = match get_config_file(&work_dir, config_path) {
Ok(path) => Some(path.to_string_lossy().to_string()),
Err(e) => {
eprintln!("error: failed to find configuration file: {}", e);
std::process::exit(1);
}
};
self
}
pub fn to_ffi(&self) -> ffi::ProxyCliArgs {
let config_file = self
.config_file
.as_ref()
.map_or_else(
|| {
let work_dir = std::env::current_dir().unwrap_or_default();
let default_config = get_config_file(&work_dir, None)
.unwrap_or_else(|_| "examples/config/pushpin.conf".into());
CString::new(default_config.to_string_lossy().to_string()).unwrap()
},
|s| CString::new(s.as_str()).unwrap(),
)
.into_raw();
let log_file = self
.log_file
.as_ref()
.map_or_else(
|| CString::new("").unwrap(),
|s| CString::new(s.as_str()).unwrap(),
)
.into_raw();
let ipc_prefix = self
.ipc_prefix
.as_ref()
.map_or_else(
|| CString::new("").unwrap(),
|s| CString::new(s.as_str()).unwrap(),
)
.into_raw();
let (routes, routes_count) = match &self.route {
Some(routes_vec) if !routes_vec.is_empty() => {
// Allocate array of string pointers
let routes_array = unsafe {
libc::malloc(routes_vec.len() * std::mem::size_of::<*mut libc::c_char>())
as *mut *mut libc::c_char
};
// Convert each route to CString and store pointer in array
for (i, item) in routes_vec.iter().enumerate() {
let c_string = CString::new(item.to_string()).unwrap().into_raw();
unsafe {
*routes_array.add(i) = c_string;
}
}
(routes_array, routes_vec.len() as libc::c_uint)
}
_ => {
let routes_array = unsafe { libc::malloc(0) as *mut *mut libc::c_char };
(routes_array, 0)
}
};
ffi::ProxyCliArgs {
config_file,
log_file,
log_level: self.log_level,
ipc_prefix,
routes,
routes_count,
}
}
}
pub mod ffi {
#[repr(C)]
pub struct ProxyCliArgs {
pub config_file: *mut libc::c_char,
pub log_file: *mut libc::c_char,
pub log_level: libc::c_uint,
pub ipc_prefix: *mut libc::c_char,
pub routes: *mut *mut libc::c_char,
pub routes_count: libc::c_uint,
}
}
/// Frees the memory allocated by proxy_cli_args_to_ffi
/// MUST be called by C++ code when done with the ProxyCliArgs struct
///
/// # Safety
///
/// This function is unsafe because it takes ownership of raw pointers and frees their memory.
/// The caller must ensure that:
/// - The `ffi_args` struct was created by `proxy_cli_args_to_ffi`
/// - Each pointer field in `ffi_args` is either null or points to valid memory allocated by `CString::into_raw()` or `libc::malloc()`
/// - The `routes` array and its individual string elements were allocated properly
/// - No pointer in `ffi_args` is used after this function is called (double-free protection)
/// - This function is called exactly once per `ProxyCliArgs` instance
#[no_mangle]
pub unsafe extern "C" fn destroy_proxy_cli_args(ffi_args: ffi::ProxyCliArgs) {
if !ffi_args.config_file.is_null() {
let _ = CString::from_raw(ffi_args.config_file);
}
if !ffi_args.log_file.is_null() {
let _ = CString::from_raw(ffi_args.log_file);
}
if !ffi_args.ipc_prefix.is_null() {
let _ = CString::from_raw(ffi_args.ipc_prefix);
}
if !ffi_args.routes.is_null() {
// Free each individual route string
for i in 0..ffi_args.routes_count {
let route_ptr = *ffi_args.routes.add(i as usize);
if !route_ptr.is_null() {
let _ = CString::from_raw(route_ptr);
}
}
libc::free(ffi_args.routes as *mut libc::c_void);
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::NamedTempFile;
#[test]
fn test_ccli_args() {
// Create mock values
let file = NamedTempFile::new().unwrap();
let config_test_file = file.path().to_str().unwrap().to_string();
let args = CliArgs {
config_file: Some(config_test_file.clone()),
log_file: Some("pushpin.log".to_string()),
log_level: 3,
ipc_prefix: Some("ipc".to_string()),
route: Some(vec!["route1".to_string(), "route2".to_string()]),
};
let args_ffi = args.to_ffi();
// Test verify() method
let verified_args = args.verify();
assert_eq!(verified_args.config_file, Some(config_test_file.clone()));
assert_eq!(verified_args.log_file, Some("pushpin.log".to_string()));
assert_eq!(verified_args.log_level, 3);
assert_eq!(verified_args.ipc_prefix, Some("ipc".to_string()));
assert_eq!(
verified_args.route,
Some(vec!["route1".to_string(), "route2".to_string()])
);
// Test conversion to C++-compatible struct
unsafe {
assert_eq!(
std::ffi::CStr::from_ptr(args_ffi.config_file)
.to_str()
.unwrap(),
config_test_file
);
assert_eq!(
std::ffi::CStr::from_ptr(args_ffi.log_file)
.to_str()
.unwrap(),
"pushpin.log"
);
assert_eq!(
std::ffi::CStr::from_ptr(args_ffi.ipc_prefix)
.to_str()
.unwrap(),
"ipc"
);
// Test routes array
assert_eq!(args_ffi.routes_count, 2);
let routes_array = args_ffi.routes;
assert_eq!(
std::ffi::CStr::from_ptr(*routes_array.add(0))
.to_str()
.unwrap(),
"route1"
);
assert_eq!(
std::ffi::CStr::from_ptr(*routes_array.add(1))
.to_str()
.unwrap(),
"route2"
);
}
assert_eq!(args_ffi.log_level, 3);
// Test cleanup - this should not crash
unsafe {
destroy_proxy_cli_args(args_ffi);
}
// Test with empty/default values
let empty_args = CliArgs {
config_file: None,
log_file: None,
log_level: 2,
ipc_prefix: None,
route: None,
};
let empty_args_ffi = empty_args.to_ffi();
// Test verify() with empty args
let verified_empty_args = empty_args.verify();
let default_config_file = get_config_file(&env::current_dir().unwrap(), None)
.unwrap()
.to_string_lossy()
.to_string();
assert_eq!(
verified_empty_args.config_file,
Some(default_config_file.clone())
);
assert_eq!(verified_empty_args.log_file, None);
assert_eq!(verified_empty_args.log_level, 2);
assert_eq!(verified_empty_args.ipc_prefix, None);
assert_eq!(verified_empty_args.route, None);
// Test conversion to C++-compatible struct
unsafe {
assert_eq!(
std::ffi::CStr::from_ptr(empty_args_ffi.config_file)
.to_str()
.unwrap(),
default_config_file
);
assert_eq!(
std::ffi::CStr::from_ptr(empty_args_ffi.log_file)
.to_str()
.unwrap(),
""
);
assert_eq!(
std::ffi::CStr::from_ptr(empty_args_ffi.ipc_prefix)
.to_str()
.unwrap(),
""
);
assert_eq!(empty_args_ffi.routes_count, 0);
assert_eq!(empty_args_ffi.log_level, 2);
}
// Test cleanup for empty args - this should not crash
unsafe {
destroy_proxy_cli_args(empty_args_ffi);
}
}
}