//! HTTP server: panel (SPA), JSON API and public stream endpoints. pub mod api; pub mod assets; pub mod public; pub mod tvh; mod tvhapi; use crate::app::State; use crate::auth; use crate::db::User; use crate::settings::ip_in; use axum::extract::{ConnectInfo, Request, State as AxState}; use axum::http::{Method, StatusCode}; use axum::middleware::{self, Next}; use axum::response::{IntoResponse, Response}; use axum::routing::{delete, get, post, put}; use axum::{Json, Router}; use std::net::SocketAddr; #[derive(Debug)] pub struct ApiError(pub StatusCode, pub String); impl ApiError { pub fn bad(msg: impl Into) -> Self { ApiError(StatusCode::BAD_REQUEST, msg.into()) } pub fn not_found(msg: impl Into) -> Self { ApiError(StatusCode::NOT_FOUND, msg.into()) } pub fn forbidden() -> Self { ApiError(StatusCode::FORBIDDEN, "permission denied".into()) } } impl From for ApiError { fn from(e: anyhow::Error) -> Self { ApiError(StatusCode::INTERNAL_SERVER_ERROR, format!("{e:#}")) } } impl IntoResponse for ApiError { fn into_response(self) -> Response { (self.0, Json(serde_json::json!({ "error": self.1 }))).into_response() } } pub type ApiResult = Result, ApiError>; /// Signed-in user (inserted by middleware). #[derive(Clone)] pub struct CurrentUser(pub User); async fn api_guard( AxState(state): AxState, ConnectInfo(peer): ConnectInfo, mut req: Request, next: Next, ) -> Response { let ip = auth::client_ip(&state, peer, req.headers()); { let s = state.settings.read().unwrap(); if !s.panel_allow_cidrs.is_empty() && !ip_in(&s.panel_allow_cidrs, ip) { return ApiError( StatusCode::FORBIDDEN, "panel not available from this network".into(), ) .into_response(); } } let path = req.uri().path().to_string(); let method = req.method().clone(); let mutating = !matches!(method, Method::GET | Method::HEAD | Method::OPTIONS); // CSRF protection: state-changing requests must carry a header that only the panel JS sets. if mutating && req .headers() .get("x-requested-with") .and_then(|v| v.to_str().ok()) != Some("simply-dvb") { return ApiError( StatusCode::FORBIDDEN, "missing X-Requested-With header".into(), ) .into_response(); } if path == "/api/login" || path == "/api/info" { return next.run(req).await; } let Some(user) = auth::session_user(&state, req.headers()).await else { return ApiError(StatusCode::UNAUTHORIZED, "login required".into()).into_response(); }; let viewer_ok = path == "/api/logout" || path == "/api/me/password" || path == "/api/me/prefs"; if mutating && user.role != "admin" && !viewer_ok { return ApiError::forbidden().into_response(); } req.extensions_mut().insert(CurrentUser(user)); next.run(req).await } /// Logs every request on the stream port (category "access"), so it is visible what a /// TV or app asks for – including paths simply-dvb does not provide. async fn request_log( AxState(state): AxState, ConnectInfo(peer): ConnectInfo, req: Request, next: Next, ) -> Response { let method = req.method().clone(); let uri = req.uri().clone(); let ip = auth::client_ip(&state, peer, req.headers()); let ua: String = req .headers() .get(axum::http::header::USER_AGENT) .and_then(|v| v.to_str().ok()) .unwrap_or("-") .chars() .take(120) .collect(); let started = std::time::Instant::now(); let res = next.run(req).await; let status = res.status(); let path = uri.path(); // hide tokens in the logged query string let query = uri .query() .map(|q| { url::form_urlencoded::parse(q.as_bytes()) .map(|(k, v)| { if matches!(&*k, "token" | "auth" | "ticket") { format!("{k}=***") } else { format!("{k}={v}") } }) .collect::>() .join("&") }) .filter(|q| !q.is_empty()) .map(|q| format!("?{q}")) .unwrap_or_default(); let ms = started.elapsed().as_millis(); let noisy = path.starts_with("/hls/") || path.starts_with("/imagecache/") || path.starts_with("/icons/") || path == "/healthz" || path == "/metrics"; if ms >= 300 { tracing::warn!(target: "access", "slow request: {ip} {method} {path}{query} status {} ({ms} ms) · {ua}", status.as_u16()); } else if status.is_client_error() || status.is_server_error() { tracing::warn!(target: "access", "{ip} {method} {path}{query} status {} ({ms} ms) · {ua}", status.as_u16()); } else if noisy { tracing::debug!(target: "access", "{ip} {method} {path}{query} status {} ({ms} ms) · {ua}", status.as_u16()); } else { tracing::info!(target: "access", "{ip} {method} {path}{query} status {} ({ms} ms) · {ua}", status.as_u16()); } res } async fn security_headers(req: Request, next: Next) -> Response { let mut res = next.run(req).await; let h = res.headers_mut(); h.entry("x-content-type-options") .or_insert("nosniff".parse().unwrap()); h.entry("referrer-policy") .or_insert("same-origin".parse().unwrap()); res } pub fn router(state: State) -> Router { let api = Router::new() .route("/api/info", get(api::info)) .route("/api/login", post(api::login)) .route("/api/logout", post(api::logout)) .route("/api/me", get(api::me)) .route("/api/me/password", post(api::change_password)) .route("/api/me/prefs", get(api::my_prefs).put(api::save_my_prefs)) .route("/api/me/sessions", get(api::my_sessions)) .route("/api/pair/{code}", get(api::pair_info)) .route("/api/pair/{code}/confirm", post(api::pair_confirm)) .route("/api/me/sessions/others", post(api::end_other_sessions)) .route("/api/me/sessions/{id}", delete(api::end_session)) .route("/api/backup/database", get(api::backup_download)) .route("/api/signal/hold", post(api::signal_hold)) .route( "/api/stats/viewing", get(api::viewing_stats).delete(api::viewing_stats_clear), ) .route("/api/status", get(api::status)) .route("/api/stats", get(api::stats)) .route("/api/logs", get(api::logs)) .route("/api/logs/download", get(api::logs_download)) .route("/api/recordings/schedule", get(api::recordings_schedule)) .route("/api/adapters", get(api::adapters)) .route("/api/adapters/refresh", post(api::adapters_refresh)) .route("/api/adapters/{id}", put(api::adapter_update)) .route("/api/muxes", get(api::muxes).post(api::mux_create)) .route( "/api/muxes/{id}", put(api::mux_update).delete(api::mux_delete), ) .route("/api/services", get(api::services)) .route( "/api/scan", get(api::scan_status) .post(api::scan_start) .delete(api::scan_cancel), ) .route("/api/scan/presets", get(api::scan_presets)) .route( "/api/channels", get(api::channels).post(api::channel_create), ) .route("/api/channels/order", post(api::channels_order)) .route("/api/channels/probe", post(api::channels_probe)) .route( "/api/channels/icons/search", post(api::icons_search).get(api::icons_search_status), ) .route( "/api/channels/{id}", put(api::channel_update).delete(api::channel_delete), ) .route("/api/channels/{id}/share", post(api::channel_share)) .route( "/api/channels/{id}/icon", post(api::channel_icon_upload).delete(api::channel_icon_delete), ) .route("/api/epg", get(api::epg)) .route("/api/epg/grab", post(api::epg_grab)) .route("/api/epg/xmltv", post(api::epg_xmltv)) .route("/api/epg/status", get(api::epg_status)) .route("/api/epg/xmltv/channels", get(api::xmltv_channels)) .route( "/api/recordings", get(api::recordings).post(api::recording_create), ) .route( "/api/recordings/{id}", put(api::recording_update).delete(api::recording_delete), ) .route("/api/recordings/{id}/stop", post(api::recording_stop)) .route("/api/autorec", get(api::autorecs).post(api::autorec_create)) .route("/api/autorec/preview", get(api::autorec_preview)) .route( "/api/autorec/{id}", put(api::autorec_update).delete(api::autorec_delete), ) .route("/api/backup", get(api::backup)) .route("/api/restore", post(api::restore)) .route( "/api/settings", get(api::settings_get).put(api::settings_put), ) .route("/api/users", get(api::users).post(api::user_create)) .route( "/api/users/{id}", put(api::user_update).delete(api::user_delete), ) .route("/api/tokens", get(api::tokens).post(api::token_create)) .route( "/api/tokens/{id}", put(api::token_update).delete(api::token_delete), ) .route("/api/clients", get(api::clients)) .route("/api/links", get(api::links)) .layer(axum::extract::DefaultBodyLimit::max(16 * 1024 * 1024)) .layer(middleware::from_fn_with_state(state.clone(), api_guard)); // streams and the tvheadend JSON API work on the panel port as well (tvheadend serves both on // one port, so apps keep working whichever port they are pointed at); requests are logged let shared = public_routes() .merge(tvhapi::routes()) .layer(middleware::from_fn_with_state(state.clone(), request_log)); Router::new() .merge(api) .merge(shared) .merge(assets::routes()) .layer(middleware::from_fn(security_headers)) .with_state(state) } /// Stream, playlist and EPG endpoints – shared by the panel port and the stream port. fn public_routes() -> Router { Router::new() // natywne .route("/playlist.m3u", get(public::playlist)) .route("/playlist.m3u8", get(public::playlist)) .route("/epg.xml", get(public::epg_xml)) .route("/hls/leave", post(public::hls_leave)) .route("/hls/{ch}/index.m3u8", get(public::hls_playlist)) .route("/hls/{ch}/{seg}", get(public::hls_segment)) .route("/stream/{ch}", get(public::ts_stream)) .route("/icons/{id}", get(public::icon)) .route("/watch/{token}", get(public::watch_page)) .route( "/recordings/{id}/index.m3u8", get(public::recording_playlist), ) .route("/recordings/{id}/file", get(public::recording_file)) .route("/metrics", get(public::metrics)) .route("/healthz", get(|| async { "ok" })) // TV app pairing (QR code) .route("/api/pair/start", post(api::pair_start)) .route("/api/pair/poll", get(api::pair_poll)) // tvheadend-compatible .route("/playlist", get(tvh::playlist_all)) .route("/playlist/{a}", get(tvh::playlist_all_sub)) .route("/playlist/{kind}/{key}", get(tvh::playlist_one)) .route("/stream/{kind}/{key}", get(tvh::stream)) .route("/xmltv", get(public::epg_xml)) .route("/xmltv/{a}", get(public::epg_xml)) .route("/imagecache/{id}", get(public::icon)) } /// Stream port router (9981 by default, like tvheadend's HTTP): no panel and no API. pub fn stream_router(state: State) -> Router { Router::new() .merge(public_routes()) .merge(tvhapi::routes()) .merge(assets::stream_routes()) .layer(middleware::from_fn(security_headers)) .layer(middleware::from_fn_with_state(state.clone(), request_log)) .with_state(state) }