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
//! Network streams and enhanced subprocess I/O.
//!
//! Implements:
//! - TCP client connections (open-network-stream)
//! - Process filters (async output handlers)
//! - Process sentinels (state change handlers)
//! - URL fetching (basic HTTP)
//! - Pipe-based IPC
//! - Process output buffer management
use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;
#[cfg(test)]
use super::error::{Flow, signal};
#[cfg(test)]
use super::value::{Value, ValueKind};
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/// Network connection types.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ConnectionType {
Plain,
// Tls, // future: TLS support
}
/// Status of a network connection.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NetworkStatus {
Open,
Closed,
Failed(String),
Connecting,
}
/// A TCP network stream.
pub struct NetworkStream {
pub id: u64,
pub name: String,
pub host: String,
pub port: u16,
pub stream: Option<TcpStream>,
pub buffer_name: Option<String>,
pub filter: Option<String>,
pub sentinel: Option<String>,
pub status: NetworkStatus,
pub output_buffer: Vec<u8>,
pub coding_system: String,
pub conn_type: ConnectionType,
}
/// Handles async output from a subprocess or network stream.
pub struct ProcessFilter {
pub name: String,
pub output_buffer: String,
}
/// Handles state changes for a process or network stream.
pub struct ProcessSentinel {
pub name: String,
}
// ---------------------------------------------------------------------------
// NetworkManager
// ---------------------------------------------------------------------------
/// Central registry for network connections, process filters, and sentinels.
pub struct NetworkManager {
connections: HashMap<u64, NetworkStream>,
next_id: u64,
process_filters: HashMap<u64, ProcessFilter>,
process_sentinels: HashMap<u64, ProcessSentinel>,
}
impl Default for NetworkManager {
fn default() -> Self {
Self::new()
}
}
impl NetworkManager {
pub fn new() -> Self {
Self {
connections: HashMap::new(),
next_id: 1,
process_filters: HashMap::new(),
process_sentinels: HashMap::new(),
}
}
// -- Network streams ----------------------------------------------------
/// Open a TCP connection to `host:port`. Returns the connection id on
/// success, or an error string on failure.
pub fn open_connection(
&mut self,
name: &str,
host: &str,
port: u16,
buffer: Option<&str>,
) -> Result<u64, String> {
let addr_str = format!("{}:{}", host, port);
let addrs: Vec<_> = addr_str
.to_socket_addrs()
.map_err(|e| format!("DNS resolution failed for {}: {}", addr_str, e))?
.collect();
if addrs.is_empty() {
return Err(format!("No addresses found for {}", addr_str));
}
let stream = TcpStream::connect_timeout(&addrs[0], Duration::from_secs(30))
.map_err(|e| format!("Connection to {} failed: {}", addr_str, e))?;
// Set a default read timeout so receive_data doesn't block forever.
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let id = self.next_id;
self.next_id += 1;
let conn = NetworkStream {
id,
name: name.to_string(),
host: host.to_string(),
port,
stream: Some(stream),
buffer_name: buffer.map(|s| s.to_string()),
filter: None,
sentinel: None,
status: NetworkStatus::Open,
output_buffer: Vec::new(),
coding_system: "utf-8".to_string(),
conn_type: ConnectionType::Plain,
};
self.connections.insert(id, conn);
Ok(id)
}
/// Close a network connection. Returns true if the connection existed.
pub fn close_connection(&mut self, id: u64) -> bool {
if let Some(conn) = self.connections.get_mut(&id) {
// Drop the TcpStream, which closes the socket.
conn.stream = None;
conn.status = NetworkStatus::Closed;
true
} else {
false
}
}
/// Send raw bytes over a connection. Returns the number of bytes
/// written.
pub fn send_data(&mut self, id: u64, data: &[u8]) -> Result<usize, String> {
let conn = self
.connections
.get_mut(&id)
.ok_or_else(|| format!("No connection with id {}", id))?;
match conn.status {
NetworkStatus::Open => {}
ref status => {
return Err(format!(
"Connection {} is not open (status: {:?})",
id, status
));
}
}
let stream = conn
.stream
.as_mut()
.ok_or_else(|| format!("Connection {} has no underlying stream", id))?;
let n = stream
.write(data)
.map_err(|e| format!("Write error on connection {}: {}", id, e))?;
stream
.flush()
.map_err(|e| format!("Flush error on connection {}: {}", id, e))?;
Ok(n)
}
/// Receive data from a connection. An optional timeout overrides the
/// socket's default read timeout. Returns the bytes read (may be empty
/// if the timeout expires with no data).
pub fn receive_data(&mut self, id: u64, timeout: Option<Duration>) -> Result<Vec<u8>, String> {
let conn = self
.connections
.get_mut(&id)
.ok_or_else(|| format!("No connection with id {}", id))?;
match conn.status {
NetworkStatus::Open => {}
ref status => {
return Err(format!(
"Connection {} is not open (status: {:?})",
id, status
));
}
}
let stream = conn
.stream
.as_mut()
.ok_or_else(|| format!("Connection {} has no underlying stream", id))?;
if let Some(dur) = timeout {
let _ = stream.set_read_timeout(Some(dur));
}
let mut buf = vec![0u8; 4096];
match stream.read(&mut buf) {
Ok(0) => {
// EOF — remote closed connection.
conn.status = NetworkStatus::Closed;
Ok(Vec::new())
}
Ok(n) => {
buf.truncate(n);
// Also append to the connection's output_buffer for later
// consumption by accept-process-output.
conn.output_buffer.extend_from_slice(&buf);
Ok(buf)
}
Err(ref e)
if e.kind() == std::io::ErrorKind::WouldBlock
|| e.kind() == std::io::ErrorKind::TimedOut =>
{
// Timeout expired, no data available.
Ok(Vec::new())
}
Err(e) => {
conn.status = NetworkStatus::Failed(e.to_string());
Err(format!("Read error on connection {}: {}", id, e))
}
}
}
/// Query the status of a connection.
pub fn connection_status(&self, id: u64) -> Option<&NetworkStatus> {
self.connections.get(&id).map(|c| &c.status)
}
/// Get a reference to a connection by id.
pub fn get_connection(&self, id: u64) -> Option<&NetworkStream> {
self.connections.get(&id)
}
/// List all connections: (id, name, host, port).
pub fn list_connections(&self) -> Vec<(u64, &str, &str, u16)> {
self.connections
.values()
.map(|c| (c.id, c.name.as_str(), c.host.as_str(), c.port))
.collect()
}
/// Delete a connection entirely (close + remove from registry).
pub fn delete_connection(&mut self, id: u64) -> bool {
if let Some(mut conn) = self.connections.remove(&id) {
conn.stream = None;
// Also remove associated filter/sentinel.
self.process_filters.remove(&id);
self.process_sentinels.remove(&id);
true
} else {
false
}
}
// -- Process filters and sentinels --------------------------------------
/// Set the filter function for a process/connection id.
pub fn set_process_filter(&mut self, process_id: u64, filter_name: &str) {
self.process_filters.insert(
process_id,
ProcessFilter {
name: filter_name.to_string(),
output_buffer: String::new(),
},
);
}
/// Set the sentinel function for a process/connection id.
pub fn set_process_sentinel(&mut self, process_id: u64, sentinel_name: &str) {
self.process_sentinels.insert(
process_id,
ProcessSentinel {
name: sentinel_name.to_string(),
},
);
}
/// Get the filter function name for a process/connection.
pub fn get_process_filter(&self, process_id: u64) -> Option<&str> {
self.process_filters
.get(&process_id)
.map(|f| f.name.as_str())
}
/// Get the sentinel function name for a process/connection.
pub fn get_process_sentinel(&self, process_id: u64) -> Option<&str> {
self.process_sentinels
.get(&process_id)
.map(|s| s.name.as_str())
}
/// Remove the filter for a process/connection.
pub fn remove_process_filter(&mut self, process_id: u64) {
self.process_filters.remove(&process_id);
}
/// Remove the sentinel for a process/connection.
pub fn remove_process_sentinel(&mut self, process_id: u64) {
self.process_sentinels.remove(&process_id);
}
// -- Output handling ----------------------------------------------------
/// Drain and return accumulated output for a connection, decoding as
/// UTF-8 (lossy). An optional timeout triggers a receive attempt first.
pub fn accept_process_output(
&mut self,
id: u64,
timeout: Option<Duration>,
) -> Result<String, String> {
// If a timeout is given, try to read fresh data first.
if timeout.is_some() {
let _ = self.receive_data(id, timeout);
}
let conn = self
.connections
.get_mut(&id)
.ok_or_else(|| format!("No connection with id {}", id))?;
let data = std::mem::take(&mut conn.output_buffer);
Ok(String::from_utf8_lossy(&data).into_owned())
}
/// Whether there is un-consumed output buffered for a connection.
pub fn process_output_pending(&self, id: u64) -> bool {
self.connections
.get(&id)
.map(|c| !c.output_buffer.is_empty())
.unwrap_or(false)
}
// -- URL fetching -------------------------------------------------------
/// Perform a basic synchronous HTTP GET. Connects to the host on port
/// 80 (or 443 not yet supported), sends a minimal HTTP/1.0 request, and
/// returns the entire response body.
pub fn url_retrieve_synchronously(&mut self, url: &str) -> Result<String, String> {
// Parse scheme, host, port, path from the URL.
let (host, port, path) = parse_http_url(url)?;
let addr_str = format!("{}:{}", host, port);
let addrs: Vec<_> = addr_str
.to_socket_addrs()
.map_err(|e| format!("DNS resolution failed for {}: {}", host, e))?
.collect();
if addrs.is_empty() {
return Err(format!("No addresses found for {}", host));
}
let mut stream = TcpStream::connect_timeout(&addrs[0], Duration::from_secs(30))
.map_err(|e| format!("Connection to {}:{} failed: {}", host, port, e))?;
let _ = stream.set_read_timeout(Some(Duration::from_secs(30)));
let request = format!(
"GET {} HTTP/1.0\r\nHost: {}\r\nConnection: close\r\n\r\n",
path, host,
);
stream
.write_all(request.as_bytes())
.map_err(|e| format!("Write error: {}", e))?;
let mut response = Vec::new();
stream
.read_to_end(&mut response)
.map_err(|e| format!("Read error: {}", e))?;
let response_str = String::from_utf8_lossy(&response).into_owned();
// Split headers from body at the first \r\n\r\n.
if let Some(pos) = response_str.find("\r\n\r\n") {
Ok(response_str[pos + 4..].to_string())
} else {
// No header/body separator found; return everything.
Ok(response_str)
}
}
}
// ---------------------------------------------------------------------------
// URL parsing helper
// ---------------------------------------------------------------------------
/// Very basic HTTP URL parser. Returns (host, port, path).
fn parse_http_url(url: &str) -> Result<(String, u16, String), String> {
let rest = if let Some(stripped) = url.strip_prefix("http://") {
stripped
} else if let Some(stripped) = url.strip_prefix("https://") {
// We note the scheme but don't actually do TLS.
stripped
} else {
return Err(format!("Unsupported URL scheme in: {}", url));
};
let default_port: u16 = if url.starts_with("https://") { 443 } else { 80 };
// Split host(+port) from path.
let (hostport, path) = match rest.find('/') {
Some(idx) => (&rest[..idx], &rest[idx..]),
None => (rest, "/"),
};
// Split host from port.
let (host, port) = if let Some(colon_idx) = hostport.rfind(':') {
let port_str = &hostport[colon_idx + 1..];
let port: u16 = port_str
.parse()
.map_err(|_| format!("Invalid port in URL: {}", port_str))?;
(&hostport[..colon_idx], port)
} else {
(hostport, default_port)
};
if host.is_empty() {
return Err("Empty host in URL".to_string());
}
Ok((host.to_string(), port, path.to_string()))
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
#[cfg(test)]
fn expect_args(name: &str, args: &[Value], n: usize) -> Result<(), Flow> {
if args.len() != n {
Err(signal(
"wrong-number-of-arguments",
vec![Value::symbol(name), Value::fixnum(args.len() as i64)],
))
} else {
Ok(())
}
}
#[cfg(test)]
fn expect_min_args(name: &str, args: &[Value], min: usize) -> Result<(), Flow> {
if args.len() < min {
Err(signal(
"wrong-number-of-arguments",
vec![Value::symbol(name), Value::fixnum(args.len() as i64)],
))
} else {
Ok(())
}
}
#[cfg(test)]
fn expect_string(value: &Value) -> Result<String, Flow> {
match value.kind() {
ValueKind::String => Ok(value.as_str().unwrap().to_owned()),
ValueKind::Symbol(id) => Ok(crate::emacs_core::intern::resolve_sym(id).to_owned()),
ValueKind::Nil => Ok("nil".to_string()),
ValueKind::T => Ok("t".to_string()),
other => Err(signal(
"wrong-type-argument",
vec![Value::symbol("stringp"), *value],
)),
}
}
#[cfg(test)]
fn expect_int(value: &Value) -> Result<i64, Flow> {
match value.kind() {
ValueKind::Fixnum(n) => Ok(n),
other => Err(signal(
"wrong-type-argument",
vec![Value::symbol("integerp"), *value],
)),
}
}
// ---------------------------------------------------------------------------
// Builtins (eval-dependent — need access to NetworkManager on the Context)
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
#[path = "network_test.rs"]
mod tests;