aria2-rpc 0.3.2

Remote control server for aria2-rust: aria2-compatible JSON-RPC 2.0, XML-RPC, and WebSocket download management
Documentation
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! RPC HTTP server: `RpcServer` struct, axum routes and the HTTP request handlers.

use std::sync::Arc;

use super::auth::AuthConfig;
use super::config::ServerConfig;
use super::cors::CorsConfig;
use super::tls::{TlsConfig, TlsError};
use super::ws_session::handle_ws_socket;
use crate::engine::{RpcEngine, dispatch_wire_entries};

/// RPC HTTP server supporting both HTTP and HTTPS.
///
/// Provides a tokio-based async server that handles JSON-RPC requests
/// over HTTP or HTTPS (TLS) depending on configuration.
pub struct RpcServer {
    /// Server configuration (host, port, auth, CORS, TLS)
    config: ServerConfig,
    /// TLS acceptor (None for HTTP, Some for HTTPS)
    tls_acceptor: Option<tokio_rustls::TlsAcceptor>,
    /// Shared RPC engine that persists across all requests.
    /// Holds download task state, group manager, and command channel.
    engine: Arc<RpcEngine>,
}

impl RpcServer {
    /// Create a new RPC server with the given configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if TLS configuration is provided but fails to load.
    pub fn new(config: ServerConfig) -> Result<Self, TlsError> {
        let tls_acceptor = if let Some(ref tls_config) = config.tls {
            let server_config = tls_config.load_server_config()?;
            Some(tokio_rustls::TlsAcceptor::from(server_config))
        } else {
            None
        };

        let engine = if let Some(token) = config.auth.token.as_deref() {
            Arc::new(
                RpcEngine::new().with_auth_middleware(super::auth::RpcAuthMiddleware::new(token)),
            )
        } else {
            Arc::new(RpcEngine::new())
        };

        Ok(Self {
            config,
            tls_acceptor,
            engine,
        })
    }

    /// Create a new RPC server with a pre-configured shared engine.
    /// Use this when the caller has already set up `group_man` and `cmd_tx`
    /// on the engine (e.g., when wiring to a running DownloadEngine).
    pub fn new_with_engine(config: ServerConfig, engine: Arc<RpcEngine>) -> Result<Self, TlsError> {
        let tls_acceptor = if let Some(ref tls_config) = config.tls {
            let server_config = tls_config.load_server_config()?;
            Some(tokio_rustls::TlsAcceptor::from(server_config))
        } else {
            None
        };

        Ok(Self {
            config,
            tls_acceptor,
            engine,
        })
    }

    /// Create a new HTTP RPC server (no TLS).
    pub fn new_http(host: impl Into<String>, port: u16) -> Self {
        Self {
            config: ServerConfig::default().with_host(host).with_port(port),
            tls_acceptor: None,
            engine: Arc::new(RpcEngine::new()),
        }
    }

    /// Create a new HTTPS RPC server with TLS.
    ///
    /// # Errors
    ///
    /// Returns an error if TLS configuration fails to load.
    pub fn new_https(
        host: impl Into<String>,
        port: u16,
        cert_path: impl Into<String>,
        key_path: impl Into<String>,
    ) -> Result<Self, TlsError> {
        let tls_config = TlsConfig::new(cert_path, key_path);
        let server_config = tls_config.load_server_config()?;
        let tls_acceptor = tokio_rustls::TlsAcceptor::from(server_config);

        Ok(Self {
            config: ServerConfig::default()
                .with_host(host)
                .with_port(port)
                .with_tls(tls_config),
            tls_acceptor: Some(tls_acceptor),
            engine: Arc::new(RpcEngine::new()),
        })
    }

    /// Get the server address string.
    pub fn addr(&self) -> String {
        self.config.addr()
    }

    /// Get the server port.
    pub fn port(&self) -> u16 {
        self.config.port
    }

    /// Check if the server is using HTTPS.
    pub fn is_secure(&self) -> bool {
        self.tls_acceptor.is_some()
    }

    /// Get the protocol scheme.
    pub fn scheme(&self) -> &'static str {
        self.config.scheme()
    }

    /// Get the full URL for the RPC endpoint.
    pub fn rpc_url(&self) -> String {
        format!(
            "{}://{}{}",
            self.scheme(),
            self.addr(),
            crate::constants::RPC_ENDPOINT_PATH
        )
    }

    /// Bind the configured address before starting the serving task.
    ///
    /// Callers that own an application lifecycle can use this seam to report
    /// an occupied port synchronously instead of keeping the process alive
    /// with a background task that failed during startup.
    pub async fn bind_listener(
        &self,
    ) -> Result<tokio::net::TcpListener, Box<dyn std::error::Error + Send + Sync>> {
        use std::net::SocketAddr;

        let addr: SocketAddr = self.addr().parse()?;
        let listener = tokio::net::TcpListener::bind(addr).await?;
        tracing::info!("RPC server listening on {}://{}", self.scheme(), addr);
        Ok(listener)
    }

    /// Get a reference to the server configuration.
    pub fn config(&self) -> &ServerConfig {
        &self.config
    }

    /// Get a reference to the TLS acceptor (if configured).
    pub fn tls_acceptor(&self) -> Option<&tokio_rustls::TlsAcceptor> {
        self.tls_acceptor.as_ref()
    }

    /// Start the RPC HTTP server and serve requests.
    ///
    /// This method runs forever until the server is shut down.
    /// It handles JSON-RPC requests at `/jsonrpc` endpoint.
    ///
    /// # Features
    ///
    /// - HTTP or HTTPS (TLS) based on configuration
    /// - CORS support with configurable allowed origins
    /// - Token-based authentication
    /// - JSON-RPC 2.0 request handling
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use aria2_rpc::server::{RpcServer, ServerConfig};
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let server = RpcServer::new_http("127.0.0.1", 6800);
    ///     server.serve().await;
    /// }
    /// ```
    pub async fn serve(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let listener = self.bind_listener().await?;
        self.serve_on_listener(listener).await
    }

    /// Serve requests on a listener that was bound by the caller.
    ///
    /// This keeps listener ownership separate from router construction so an
    /// application can complete its startup handshake before spawning the
    /// long-lived server task.
    pub async fn serve_on_listener(
        &self,
        listener: tokio::net::TcpListener,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        use axum::{
            Router, middleware,
            routing::{get, post},
        };

        // Create shared state with the persistent RPC engine
        let state = RpcState {
            engine: self.engine.clone(),
            max_request_size: self.config.max_request_size,
            auth: self.config.auth.clone(),
        };

        // Build the configured CORS layer once. The layer is immutable and
        // shared by all connections, while origin matching remains per request.
        let cors_layer = build_cors_layer(&self.config.cors);

        // Build router
        let app = Router::new()
            .route("/jsonrpc", post(handle_jsonrpc))
            .route("/jsonrpc", get(handle_jsonrpc_or_ws)) // GET + WebSocket upgrade
            .route("/rpc", post(handle_xmlrpc))
            .layer(axum::extract::DefaultBodyLimit::max(
                self.config.max_request_size,
            ))
            .layer(middleware::from_fn_with_state(
                state.clone(),
                http_auth_middleware,
            ))
            .layer(cors_layer)
            .with_state(state);

        // Serve with or without TLS
        if let Some(ref tls_acceptor) = self.tls_acceptor {
            // HTTPS mode — accept TCP connections, perform TLS handshake,
            // then hand the encrypted stream to hyper/axum.
            tracing::info!("TLS enabled, serving HTTPS");
            self.serve_tls(listener, tls_acceptor.clone(), app).await?;
        } else {
            self.serve_http(listener, app).await?;
        }

        Ok(())
    }

    /// Serve cleartext HTTP with the same response-discard path as HTTPS.
    ///
    /// aria2_original closes a connection without writing an HTTP response
    /// when an authenticated non-WebSocket request advertises an oversized
    /// Content-Length. Axum's high-level server requires an infallible
    /// service, so it cannot represent that transport result directly.
    async fn serve_http(
        &self,
        listener: tokio::net::TcpListener,
        app: axum::Router,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        use axum::extract::Request;
        use hyper_util::rt::{TokioExecutor, TokioIo};
        use std::net::SocketAddr;
        use tower_service::Service;

        loop {
            let (connection, remote_addr) = listener.accept().await?;
            let mut make_service = app
                .clone()
                .into_make_service_with_connect_info::<SocketAddr>();

            tokio::spawn(async move {
                let router = make_service.call(remote_addr).await.unwrap();
                let io = TokioIo::new(connection);
                let hyper_service =
                    hyper::service::service_fn(move |request: Request<hyper::body::Incoming>| {
                        let mut router = router.clone();
                        async move {
                            let response = router.call(request).await.unwrap();
                            if response.extensions().get::<DropHttpConnection>().is_some() {
                                return Err(std::io::Error::new(
                                    std::io::ErrorKind::ConnectionAborted,
                                    "oversized aria2 RPC request",
                                ));
                            }
                            Ok::<_, std::io::Error>(response)
                        }
                    });

                if let Err(error) =
                    hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())
                        .serve_connection_with_upgrades(io, hyper_service)
                        .await
                {
                    tracing::debug!(%remote_addr, %error, "HTTP connection ended");
                }
            });
        }
    }

    /// Serve HTTPS by accepting TCP connections, wrapping each with TLS,
    /// then dispatching to the axum router via hyper's low-level connection API.
    ///
    /// This follows the official axum `low-level-rustls` example pattern:
    /// each incoming TCP connection is TLS-accepted, then handed to
    /// `hyper_util::server::conn::auto::Builder` which handles both
    /// HTTP/1.1 and HTTP/2 (h2) over the encrypted stream.
    async fn serve_tls(
        &self,
        listener: tokio::net::TcpListener,
        tls_acceptor: tokio_rustls::TlsAcceptor,
        app: axum::Router,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        use axum::extract::Request;
        use hyper_util::rt::{TokioExecutor, TokioIo};
        use std::net::SocketAddr;
        use tower_service::Service;

        loop {
            let (cnx, remote_addr) = listener.accept().await?;
            let tls_acceptor = tls_acceptor.clone();

            // Convert the Router into a MakeService that provides
            // ConnectInfo<SocketAddr> to handlers.
            let mut make_service = app
                .clone()
                .into_make_service_with_connect_info::<SocketAddr>();

            tokio::spawn(async move {
                // Perform TLS handshake
                let Ok(tls_stream) = tls_acceptor.accept(cnx).await else {
                    tracing::error!("TLS handshake failed for connection from {}", remote_addr);
                    return;
                };

                // Call the MakeService to obtain a per-connection Router.
                // IntoMakeServiceWithConnectInfo never returns Err, so unwrap is safe.
                let router = make_service.call(remote_addr).await.unwrap();

                // Bridge tokio AsyncRead/AsyncWrite → hyper's IO traits
                let io = TokioIo::new(tls_stream);

                // Build a hyper Service that delegates to the Router. The
                // response marker tells the connection layer to close without
                // writing bytes for aria2's oversized-request path.
                let hyper_service =
                    hyper::service::service_fn(move |request: Request<hyper::body::Incoming>| {
                        let mut router = router.clone();
                        async move {
                            let response = router.call(request).await.unwrap();
                            if response.extensions().get::<DropHttpConnection>().is_some() {
                                return Err(std::io::Error::new(
                                    std::io::ErrorKind::ConnectionAborted,
                                    "oversized aria2 RPC request",
                                ));
                            }
                            Ok::<_, std::io::Error>(response)
                        }
                    });

                let result = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())
                    .serve_connection_with_upgrades(io, hyper_service)
                    .await;

                if let Err(err) = result {
                    tracing::warn!("HTTPS connection error from {}: {}", remote_addr, err);
                }
            });
        }
    }
}

/// Shared state for RPC handlers
#[derive(Clone)]
pub struct RpcState {
    pub(crate) engine: Arc<RpcEngine>,
    /// HTTP Basic Auth configuration. Token auth remains in `RpcEngine` and
    /// is carried in the JSON/XML-RPC parameter contract.
    pub(crate) auth: AuthConfig,
    /// Maximum JSON/XML-RPC parser input size in bytes.
    pub(crate) max_request_size: usize,
}

/// Marks a response that must become a connection close without wire bytes.
///
/// The marker is consumed by the low-level HTTP/TLS connection services after
/// the regular Router middleware has preserved original authentication order.
#[derive(Clone, Debug)]
struct DropHttpConnection;

/// Convert the public CORS configuration into tower-http's request-aware
/// layer. `AllowOrigin::list` mirrors an allowed origin back to the browser,
/// while wildcard mode retains aria2's literal `*` response.
fn build_cors_layer(config: &CorsConfig) -> tower_http::cors::CorsLayer {
    use axum::http::{HeaderName, HeaderValue, Method};
    use std::time::Duration;
    use tower_http::cors::{AllowHeaders, AllowMethods, AllowOrigin, Any, CorsLayer};

    // An empty origin list is the aria2_original default: do not emit any
    // CORS response or preflight headers until the user opts in.
    if config.allowed_origins().is_empty() {
        return CorsLayer::new();
    }

    let methods = if config.allow_methods.trim() == "*" {
        AllowMethods::any()
    } else {
        AllowMethods::list(
            config
                .allow_methods
                .split(',')
                .filter_map(|method| method.trim().parse::<Method>().ok()),
        )
    };
    let headers = if config.allow_headers.trim() == "*" {
        AllowHeaders::any()
    } else {
        AllowHeaders::list(
            config
                .allow_headers
                .split(',')
                .filter_map(|header| header.trim().parse::<HeaderName>().ok()),
        )
    };
    let max_age = crate::constants::CORS_MAX_AGE;

    let origin = if config.is_wildcard() {
        if config.allow_credentials {
            AllowOrigin::mirror_request()
        } else {
            Any.into()
        }
    } else {
        AllowOrigin::list(
            config
                .allowed_origins()
                .iter()
                .filter_map(|origin| HeaderValue::from_str(origin).ok()),
        )
    };

    CorsLayer::new()
        .allow_origin(origin)
        .allow_methods(methods)
        .allow_headers(headers)
        .allow_credentials(config.allow_credentials)
        .max_age(Duration::from_secs(max_age))
}

/// Enforce HTTP Basic Auth at the transport seam. `OPTIONS` is deliberately
/// exempt, matching aria2's CORS preflight behavior; RPC token auth still
/// applies after a request reaches the JSON/XML engine.
async fn http_auth_middleware(
    axum::extract::State(state): axum::extract::State<RpcState>,
    request: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    use axum::http::{Method, StatusCode, header};
    use axum::response::IntoResponse;

    let authorized = request.method() == Method::OPTIONS
        || !state.auth.has_basic()
        || state.auth.verify_authorization(
            request
                .headers()
                .get(header::AUTHORIZATION)
                .and_then(|value| value.to_str().ok()),
        );

    if authorized {
        if request_content_length_exceeds_limit(&request, state.max_request_size) {
            let mut response = axum::response::Response::new(axum::body::Body::empty());
            response.extensions_mut().insert(DropHttpConnection);
            return response;
        }
        next.run(request).await
    } else {
        (
            StatusCode::UNAUTHORIZED,
            [(header::WWW_AUTHENTICATE, "Basic realm=\"aria2\"")],
            "Unauthorized",
        )
            .into_response()
    }
}

/// Match `HttpServerCommand`: only non-WebSocket requests with a declared
/// Content-Length greater than the configured cap are dropped at header time.
fn request_content_length_exceeds_limit(
    request: &axum::extract::Request,
    max_request_size: usize,
) -> bool {
    use axum::http::header;

    let is_websocket_upgrade = request
        .headers()
        .get(header::UPGRADE)
        .and_then(|value| value.to_str().ok())
        .is_some_and(|value| value.eq_ignore_ascii_case("websocket"))
        && request
            .headers()
            .get(header::CONNECTION)
            .and_then(|value| value.to_str().ok())
            .is_some_and(|value| {
                value
                    .split(',')
                    .any(|token| token.trim().eq_ignore_ascii_case("upgrade"))
            });
    if is_websocket_upgrade {
        return false;
    }

    request
        .headers()
        .get(header::CONTENT_LENGTH)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.parse::<u64>().ok())
        .is_some_and(|content_length| content_length > max_request_size as u64)
}

struct JsonGetRequest {
    body: Vec<u8>,
    callback: Option<String>,
}

/// Parse aria2's legacy JSON-RPC GET/JSONP query format.
///
/// The C++ implementation intentionally has a small, legacy grammar here:
/// it matches raw `key=value` prefixes, percent-decodes only `params`, and
/// copies `method`, `id`, and `jsoncallback` into the generated request or
/// response without form normalization. Keep those rules at this wire seam;
/// the POST JSON parser must not inherit them.
fn parse_json_get_query(query: &str) -> JsonGetRequest {
    let query = query.strip_prefix('?').unwrap_or(query);
    let mut method = None;
    let mut id = None;
    let mut params = None;
    let mut callback = None;

    for item in query.split('&') {
        if let Some(value) = item.strip_prefix("method=") {
            method = Some(value);
        } else if let Some(value) = item.strip_prefix("id=") {
            id = Some(value);
        } else if let Some(value) = item.strip_prefix("params=") {
            params = Some(value);
        } else if let Some(value) = item.strip_prefix("jsoncallback=") {
            callback = Some(value);
        }
    }

    let has_params = params.is_some_and(|encoded| !encoded.is_empty());
    let decoded_params = params.map(|encoded| {
        let decoded = crate::rpc_helpers::percent_decode(encoded);
        crate::rpc_helpers::decode_aria2_base64(&decoded)
    });

    let body = match (method, id) {
        (None, None) => decoded_params.unwrap_or_default(),
        (method, id) => {
            let mut body = Vec::new();
            body.extend_from_slice(b"{");
            if let Some(method) = method {
                body.extend_from_slice(b"\"method\":\"");
                body.extend_from_slice(method.as_bytes());
                body.extend_from_slice(b"\"");
            }
            if let Some(id) = id {
                // The leading comma when `method` is absent is an observable
                // quirk of aria2_original's string builder.
                body.extend_from_slice(b",\"id\":\"");
                body.extend_from_slice(id.as_bytes());
                body.extend_from_slice(b"\"");
            }
            if has_params {
                let params = decoded_params
                    .as_deref()
                    .expect("non-empty params must have a decoded value");
                body.extend_from_slice(b",\"params\":");
                body.extend_from_slice(params);
            }
            body.extend_from_slice(b"}");
            body
        }
    };

    JsonGetRequest {
        body,
        // aria2_original emits this value verbatim as JavaScript. In
        // particular, it does not percent-decode or validate the callback.
        callback: callback.map(str::to_owned),
    }
}

struct JsonRpcHttpResponse {
    status: axum::http::StatusCode,
    body: Vec<u8>,
    close_connection: bool,
}

fn http_status_for_jsonrpc_error(code: i32) -> axum::http::StatusCode {
    use axum::http::StatusCode;

    match code {
        // aria2 maps execution failures and malformed requests to 400. Keep
        // the standard MethodNotFound mapping available for callers that use
        // -32601, although aria2's own unknown-method path uses code 1.
        1 | -32600 => StatusCode::BAD_REQUEST,
        -32601 => StatusCode::NOT_FOUND,
        _ => StatusCode::INTERNAL_SERVER_ERROR,
    }
}

fn serialize_jsonrpc_response(response: crate::json_rpc::JsonRpcResponse) -> JsonRpcHttpResponse {
    let status = response
        .error
        .as_ref()
        .map(|error| http_status_for_jsonrpc_error(error.code))
        .unwrap_or(axum::http::StatusCode::OK);
    let body = response.to_bytes().unwrap_or_else(|error| {
        format!(
            "{{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{{\"code\":-32603,\"message\":{}}}}}",
            serde_json::Value::String(error.to_string())
        )
        .into_bytes()
    });
    JsonRpcHttpResponse {
        status,
        body,
        // `HttpServerBodyCommand::sendJsonRpcResponse` disables keep-alive
        // for every single-response error. Batch responses use a separate
        // original path and remain eligible for connection reuse.
        close_connection: response.error.is_some(),
    }
}

async fn dispatch_jsonrpc_body(engine: &RpcEngine, body: &[u8]) -> JsonRpcHttpResponse {
    use crate::json_rpc::{JsonRpcBatchResponse, JsonRpcWireEntry, parse_aria2_wire_document};

    match parse_aria2_wire_document(body) {
        Ok(document) if !document.is_batch => {
            let entry = document
                .entries
                .into_iter()
                .next()
                .expect("single JSON-RPC document must contain one entry");
            let response = match entry {
                JsonRpcWireEntry::Request(request) => engine.handle_request_owned(request).await,
                JsonRpcWireEntry::Error(response) => response,
            };
            serialize_jsonrpc_response(response)
        }
        Ok(document) => {
            let body = JsonRpcBatchResponse(dispatch_wire_entries(engine, document.entries).await)
                .to_bytes()
                .unwrap_or_else(|error| {
                    format!(
                        "{{\"jsonrpc\":\"2.0\",\"id\":null,\"error\":{{\"code\":-32603,\"message\":{}}}}}",
                        serde_json::Value::String(error.to_string())
                    )
                    .into_bytes()
                });
            // aria2 always returns HTTP 200 for a batch envelope, even when
            // individual entries contain RPC errors.
            JsonRpcHttpResponse {
                status: axum::http::StatusCode::OK,
                body,
                close_connection: false,
            }
        }
        Err(error) => serialize_jsonrpc_response(error.into_response(None)),
    }
}

fn into_jsonrpc_http_response(
    response: JsonRpcHttpResponse,
    content_type: &'static str,
) -> axum::response::Response {
    use axum::http::{HeaderValue, header};
    use axum::response::IntoResponse;

    let close_connection = response.close_connection;
    let mut http_response = (
        response.status,
        [(header::CONTENT_TYPE, content_type)],
        response.body,
    )
        .into_response();
    if close_connection {
        http_response
            .headers_mut()
            .insert(header::CONNECTION, HeaderValue::from_static("close"));
    }
    http_response
}

fn wrap_jsonp(body: Vec<u8>, callback: Option<&str>) -> Vec<u8> {
    match callback {
        Some(callback) => {
            let mut wrapped = Vec::with_capacity(callback.len() + body.len() + 2);
            wrapped.extend_from_slice(callback.as_bytes());
            wrapped.push(b'(');
            wrapped.extend_from_slice(&body);
            wrapped.push(b')');
            wrapped
        }
        None => body,
    }
}

impl std::fmt::Debug for RpcServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RpcServer")
            .field("addr", &self.addr())
            .field("secure", &self.is_secure())
            .field("config", &self.config)
            .finish()
    }
}

/// Handle JSON-RPC POST requests
async fn handle_jsonrpc(
    axum::extract::State(state): axum::extract::State<RpcState>,
    body: axum::body::Bytes,
) -> impl axum::response::IntoResponse {
    let response = dispatch_jsonrpc_body(&state.engine, &body).await;
    into_jsonrpc_http_response(response, "application/json-rpc")
}

/// Handle the original aria2 XML-RPC endpoint at `/rpc`.
async fn handle_xmlrpc(
    axum::extract::State(state): axum::extract::State<RpcState>,
    body: axum::body::Bytes,
) -> impl axum::response::IntoResponse {
    use crate::json_rpc::JsonRpcRequest;
    use crate::xml_rpc::{XmlRpcResponse, XmlRpcValue, parse_request};
    use axum::http::{StatusCode, header};

    let (status, content_type, response_body) = match parse_request(&body) {
        Ok(request) => {
            let params = request
                .params
                .iter()
                .map(XmlRpcValue::to_json_value)
                .collect::<Result<Vec<_>, _>>();
            match params {
                Ok(params) => {
                    let json_request =
                        JsonRpcRequest::new(request.method_name, serde_json::Value::Array(params))
                            .with_id(serde_json::Value::String("xmlrpc".into()));
                    let json_response = state.engine.handle_request(&json_request).await;
                    let response = match json_response.result {
                        Some(result) => XmlRpcValue::from_json_value(result)
                            .map(XmlRpcResponse::single)
                            .unwrap_or_else(|error| {
                                // Once XML-RPC parsing has succeeded, aria2
                                // reports method-side failures as faultCode=1
                                // regardless of the JSON-RPC adapter code.
                                XmlRpcResponse::fault(1, &error.to_string())
                            }),
                        None => {
                            let message = json_response
                                .error
                                .map(|error| error.message)
                                .unwrap_or_else(|| "Missing RPC response".into());
                            XmlRpcResponse::fault(1, &message)
                        }
                    };
                    (StatusCode::OK, Some("text/xml"), response.to_xml())
                }
                // aria2_original treats XML value conversion failures as
                // request parse failures: HTTP 400 with an empty body.
                Err(_) => (StatusCode::BAD_REQUEST, None, String::new()),
            }
        }
        // Keep the original HTTP/XML-RPC split. The C++ body command sends
        // `feedResponse(400)` for parser errors, which has no XML fault body.
        Err(_) => (StatusCode::BAD_REQUEST, None, String::new()),
    };

    let mut response = axum::response::Response::new(axum::body::Body::from(response_body));
    *response.status_mut() = status;
    if let Some(content_type) = content_type {
        response.headers_mut().insert(
            header::CONTENT_TYPE,
            axum::http::HeaderValue::from_static(content_type),
        );
    }
    response
}

/// Handle GET requests at `/jsonrpc`.
///
/// Supports WebSocket upgrades and aria2's legacy GET/JSONP transport.
/// 1. **WebSocket upgrade** — If the request has `Upgrade: websocket` headers,
///    the connection is upgraded to WebSocket for real-time download events.
/// 2. **Regular GET** — Dispatches aria2's legacy GET/JSONP transport.
///
/// Upstream aria2 accepts WebSocket upgrades only at `/jsonrpc`; regular GET
/// requests at that same path retain its legacy JSONP behavior.
async fn handle_jsonrpc_or_ws(
    axum::extract::State(state): axum::extract::State<RpcState>,
    ws: Option<axum::extract::ws::WebSocketUpgrade>,
    query: axum::extract::RawQuery,
) -> impl axum::response::IntoResponse {
    match ws {
        Some(upgrade) => {
            // WebSocket upgrade request from Aria2 Explorer or other clients.
            // An oversized RPC document receives a JSON-RPC parse error rather
            // than a transport-level disconnect.
            let max_request_size = state.max_request_size;
            upgrade.on_upgrade(move |socket| {
                handle_ws_socket(socket, state.engine.clone(), max_request_size)
            })
        }
        None => {
            let parsed = parse_json_get_query(query.0.as_deref().unwrap_or_default());
            let response = dispatch_jsonrpc_body(&state.engine, &parsed.body).await;
            let content_type = if parsed.callback.is_some() {
                "text/javascript"
            } else {
                "application/json-rpc"
            };
            let body = wrap_jsonp(response.body, parsed.callback.as_deref());
            into_jsonrpc_http_response(JsonRpcHttpResponse { body, ..response }, content_type)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_json_get_query_matches_aria2_wire_grammar() {
        use base64::Engine;

        let encoded = base64::engine::general_purpose::STANDARD.encode("[]");
        let parsed = parse_json_get_query(&format!(
            "method=aria2.getVersion&id=foo%20bar&params={encoded}&jsoncallback=cb%2Ename"
        ));

        assert_eq!(
            parsed.body,
            br#"{"method":"aria2.getVersion","id":"foo%20bar","params":[]}"#
        );
        assert_eq!(parsed.callback.as_deref(), Some("cb%2Ename"));
    }

    #[test]
    fn test_json_get_query_keeps_original_malformed_cases_for_json_parser() {
        let no_query = parse_json_get_query("");
        assert!(no_query.body.is_empty());

        let id_only = parse_json_get_query("id=only-id");
        assert_eq!(id_only.body, br#"{,"id":"only-id"}"#);

        let invalid_base64 = parse_json_get_query("method=aria2.getVersion&params=not-base64");
        assert!(!invalid_base64.body.is_empty());
    }

    #[test]
    fn test_json_get_query_omits_empty_params_like_aria2() {
        let parsed = parse_json_get_query("method=aria2.getVersion&id=empty&params=");
        assert_eq!(
            parsed.body,
            br#"{"method":"aria2.getVersion","id":"empty"}"#
        );
    }

    #[test]
    fn test_json_get_callback_is_not_normalized() {
        let parsed = parse_json_get_query("jsoncallback=bad;alert(1)//");
        assert_eq!(parsed.callback.as_deref(), Some("bad;alert(1)//"));
    }

    #[test]
    fn test_rpc_server_new_http() {
        let server = RpcServer::new_http("127.0.0.1", 6800);
        assert_eq!(server.addr(), "127.0.0.1:6800");
        assert_eq!(server.port(), 6800);
        assert!(!server.is_secure());
        assert_eq!(server.scheme(), "http");
        assert_eq!(server.rpc_url(), "http://127.0.0.1:6800/jsonrpc");
    }

    #[test]
    fn test_rpc_server_from_config() {
        let config = ServerConfig::default().with_host("0.0.0.0").with_port(8080);

        let server = RpcServer::new(config).expect("Failed to create server");
        assert_eq!(server.addr(), "0.0.0.0:8080");
        assert!(!server.is_secure());
    }

    #[test]
    fn test_rpc_server_debug_format() {
        let server = RpcServer::new_http("localhost", 6800);
        let debug_str = format!("{:?}", server);
        assert!(debug_str.contains("RpcServer"));
        assert!(debug_str.contains("localhost:6800"));
        assert!(debug_str.contains("secure: false"));
    }

    #[test]
    fn test_rpc_server_config_accessor() {
        let config = ServerConfig::default()
            .with_host("192.168.1.1")
            .with_port(9999);

        let server = RpcServer::new(config).expect("Failed to create server");
        let cfg = server.config();
        assert_eq!(cfg.host, "192.168.1.1");
        assert_eq!(cfg.port, 9999);
    }

    #[test]
    fn test_rpc_server_tls_acceptor_none_for_http() {
        let server = RpcServer::new_http("127.0.0.1", 6800);
        assert!(server.tls_acceptor().is_none());
    }
}