-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttp.rs
More file actions
3439 lines (3231 loc) · 119 KB
/
Copy pathhttp.rs
File metadata and controls
3439 lines (3231 loc) · 119 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
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! HTTP server (axum) — REST API + stats endpoints.
//!
//! Endpoints:
//! GET /api/v1/health public `status`; details with Bearer
//! GET /api/v1/streams Bearer token (includes keys)
//! POST /api/v1/streams Bearer token, returns keys
//! DELETE /api/v1/streams/:id Bearer token
//!
//! GET /stats?key=<stats_key> flat JSON stats (no stream ids)
//! GET /api/v1/streams/:id/stats Bearer = full JSON; key = flat public JSON
//! GET /stats-nginx?key=<stats_key> XML (nginx-rtmp compatible)
use axum::extract::{ConnectInfo, DefaultBodyLimit, FromRequestParts, Path, Query, State};
use axum::http::{HeaderMap, StatusCode, request::Parts};
use axum::middleware;
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post};
use axum::{Json, Router};
use parking_lot::Mutex;
use serde::Deserialize;
use serde_json::{Value, json};
use std::collections::HashSet;
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use crate::config::ServerConfig;
use crate::db::{Db, DbLookup, Stream, StreamViewer};
use crate::keygen::keygen_stream_key;
use crate::rate_limit::{self, RateLimiter};
use crate::rtmp_bridge::DbRtmpBridge;
use crate::state::{CoordError, StateCoordinator};
pub struct AppState {
pub db: Arc<Db>,
pub config: ServerConfig,
/// Live bearer token (may be refreshed when a joiner installs the cluster token).
pub api_token: Arc<parking_lot::RwLock<String>>,
pub rtmp_bridge: Arc<DbRtmpBridge>,
/// Durable mutations (standalone DB or Raft).
pub coordinator: Arc<StateCoordinator>,
/// Stream IDs deleted via this API while RTMP connections are active.
/// The RTMP poll loop reads this set and evicts matching connections.
pub deleted_streams: Arc<Mutex<HashSet<String>>>,
/// Viewer slot IDs revoked via HTTP while RTMP player sessions are active.
pub revoked_viewers: Arc<Mutex<HashSet<String>>>,
}
/// Build the Axum router, wiring all HTTP handlers to the shared application state.
pub fn router(state: Arc<AppState>) -> Router {
let limiter = RateLimiter::new(
state.config.http_rate_limit_config(),
state.config.http_trusted_proxies.clone(),
Arc::clone(&state.api_token),
);
Router::new()
.route("/api/v1/health", get(handle_health))
.route("/stats", get(handle_stats_json))
.route("/stats-nginx", get(handle_stats_nginx))
.route("/stat.xsl", get(handle_stat_xsl))
.route(
"/api/v1/streams",
get(handle_streams_list).post(handle_stream_create),
)
.route("/api/v1/streams/{id}", delete(handle_stream_delete))
.route("/api/v1/streams/{id}/stats", get(handle_stream_stats))
.route(
"/api/v1/streams/{id}/players",
get(handle_stream_players_list).post(handle_stream_player_create),
)
.route(
"/api/v1/streams/{id}/players/{player_id}",
delete(handle_stream_player_delete),
)
.route("/api/v1/cluster", get(handle_cluster_get))
.route("/api/v1/cluster/nodes", get(handle_cluster_nodes))
.route("/api/v1/cluster/streams", get(handle_cluster_streams))
.route(
"/api/v1/cluster/nodes/{id}/drain",
post(handle_cluster_drain_node),
)
.route(
"/api/v1/cluster/nodes/{id}/resume",
post(handle_cluster_resume_node),
)
.route(
"/api/v1/cluster/nodes/{id}/promote",
post(handle_cluster_promote_node),
)
.route(
"/api/v1/cluster/nodes/{id}",
delete(handle_cluster_remove_node),
)
.layer(DefaultBodyLimit::max(state.config.http_max_body_bytes))
.layer(middleware::from_fn_with_state(
limiter,
rate_limit::middleware,
))
.with_state(state)
}
fn now_ts() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64
}
fn http_peer(state: &AppState, addr: ClientAddr, headers: &HeaderMap) -> String {
// Without a real peer address (e.g. `ConnectInfo` missing from a
// non-standard embedding), there is no basis for deciding whether the
// peer is a trusted proxy, so X-Forwarded-For must not be honored.
let Some(peer) = addr.0 else {
return "unknown".to_string();
};
rate_limit::resolve_client_ip(
peer,
headers.get("X-Forwarded-For"),
&state.config.http_trusted_proxies,
)
.to_string()
}
/// Optional peer address for access logs. Missing in unit tests that use
/// `oneshot` without `ConnectInfo`; production always has it via
/// `into_make_service_with_connect_info`.
struct ClientAddr(Option<std::net::IpAddr>);
impl<S> FromRequestParts<S> for ClientAddr
where
S: Send + Sync,
{
type Rejection = Infallible;
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
Ok(ClientAddr(
parts
.extensions
.get::<ConnectInfo<SocketAddr>>()
.map(|ConnectInfo(addr)| addr.ip()),
))
}
}
fn log_http_access(method: &str, path: &str, peer: &str, status: StatusCode, detail: &str) {
let code = status.as_u16();
if detail.is_empty() {
crate::log_info!("HTTP: {method} {path} from {peer} → {code}");
} else {
crate::log_info!("HTTP: {method} {path} from {peer} → {code} {detail}");
}
}
// ---------- errors ----------
fn err_json(status: StatusCode, code: &str, msg: &str) -> Response {
(
status,
Json(json!({"error": {"code": code, "message": msg}})),
)
.into_response()
}
fn err_xml(status: StatusCode, msg: &str) -> Response {
let body = format!(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rtmp><error>{}</error></rtmp>\n",
xml_escape(msg)
);
xml_response(status, body)
}
fn xml_response(status: StatusCode, body: String) -> Response {
(
status,
[("Content-Type", "application/xml; charset=utf-8")],
body,
)
.into_response()
}
fn public_stats_text(status: StatusCode, msg: &str) -> Response {
(
status,
[("Content-Type", "text/plain; charset=utf-8")],
msg.to_string(),
)
.into_response()
}
const PUBLIC_STATS_OFFLINE_MSG: &str = "Stream offline";
/// Uniform offline response for public stats routes. Returned for both valid
/// keys with no active publisher and failed stats-key auth so remote clients
/// cannot distinguish guesses from offline streams.
fn public_stats_offline_response() -> Response {
public_stats_text(StatusCode::OK, PUBLIC_STATS_OFFLINE_MSG)
}
fn public_stats_offline_nginx(db: &Db) -> Response {
xml_response(
StatusCode::OK,
// Scoped to a non-existent stream id so the shell matches a valid offline key.
build_nginx_xml(db, Some(""), true),
)
}
/// XML 1.0 forbids most control characters; the rest of the five reserved
/// characters are escaped so attacker-controlled strings (RTMP `app`,
/// stream names) can't inject markup into the stats document.
fn xml_escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
'\t' | '\n' | '\r' => out.push(c),
c if (c as u32) < 0x20 => {}
c => out.push(c),
}
}
out
}
// ---------- auth ----------
/// Real request authorization for Bearer-protected handlers. Delegates to
/// `rate_limit::bearer_authenticated`, which the rate-limit middleware also
/// uses (to preview auth status for bucket selection) — sharing one
/// implementation keeps the two checks from drifting apart.
fn bearer_ok(state: &AppState, headers: &HeaderMap) -> bool {
let token = state.api_token.read().clone();
rate_limit::bearer_authenticated(headers, &token)
}
fn stats_key_lookup(
state: &AppState,
key: &str,
stream_id: Option<&str>,
) -> Option<crate::db::Stream> {
if key.is_empty() {
return None;
}
match state.db.stream_find_by_stats_key(key) {
DbLookup::Ok(s) if stream_id.is_none_or(|id| s.id == id) => Some(s),
DbLookup::Ok(_) | DbLookup::Missing | DbLookup::Failed => None,
}
}
const STATS_MIN_RESPONSE: Duration = Duration::from_millis(50);
async fn pace_public_stats(start: Instant, response: Response) -> Response {
if let Some(remaining) = STATS_MIN_RESPONSE.checked_sub(start.elapsed()) {
tokio::time::sleep(remaining).await;
}
response
}
#[derive(Deserialize, Default)]
pub struct KeyQuery {
#[serde(default)]
key: String,
}
fn is_valid_stream_key_part(value: &str) -> bool {
if value.is_empty() || value.len() > 63 {
return false;
}
let mut chars = value.chars();
let Some(first) = chars.next() else {
return false;
};
first.is_ascii_alphanumeric()
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}
/// Publish/play/stats keys: safe ASCII, no slashes, minimum entropy via length.
fn is_valid_access_key(value: &str) -> bool {
crate::keygen::is_valid_access_key(value)
}
fn trim_optional_string(value: Option<String>) -> Option<String> {
value
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
enum AccessKeyFieldError {
Invalid,
GenerationFailed,
}
fn resolve_or_generate_access_key(
provided: Option<String>,
prefix: &str,
) -> Result<String, AccessKeyFieldError> {
match trim_optional_string(provided) {
Some(key) => {
if !is_valid_access_key(&key) {
return Err(AccessKeyFieldError::Invalid);
}
Ok(key)
}
None => keygen_stream_key(prefix).map_err(|_| AccessKeyFieldError::GenerationFailed),
}
}
const ACCESS_KEY_VALIDATION_MSG: &str = crate::keygen::ACCESS_KEY_VALIDATION_MSG;
fn access_keys_must_be_unique(keys: &[&str]) -> bool {
let mut seen = HashSet::with_capacity(keys.len());
keys.iter().all(|k| seen.insert(*k))
}
fn is_valid_display_name(value: &str) -> bool {
!value.is_empty() && value.chars().count() <= 128 && !value.chars().any(char::is_control)
}
fn viewer_to_json(v: &StreamViewer) -> Value {
json!({
"id": v.id,
"name": v.name,
"play_key": v.play_key,
"enabled": v.enabled,
"created_at": v.created_at,
})
}
fn stream_to_json_with_players(s: &Stream, players: Vec<Value>) -> Value {
json!({
"id": s.id,
"name": s.name,
"app": s.app,
"publish_key": s.publish_key,
"play_key": s.play_key,
"stats_key": s.stats_key,
"players": players,
"enabled": s.enabled,
"created_at": s.created_at,
})
}
fn stream_to_json(db: &Db, s: &Stream) -> Value {
let players: Vec<Value> = db.viewer_list(&s.id).iter().map(viewer_to_json).collect();
stream_to_json_with_players(s, players)
}
fn create_viewer_row(
stream_id: &str,
name: &str,
play_key: &str,
created_at: i64,
) -> Option<StreamViewer> {
let viewer_id = keygen_stream_key(crate::keygen::PREFIX_VIEWER_ID).ok()?;
Some(StreamViewer {
id: viewer_id,
stream_id: stream_id.to_string(),
name: name.to_string(),
play_key: play_key.to_string(),
enabled: true,
created_at,
})
}
// ---------- JSON stats builder ----------
fn build_json_stats(db: &Db, stream_id: Option<&str>) -> Value {
let (pubs, players) = match stream_id {
Some(id) => (db.publisher_list(Some(id)), db.player_list(Some(id))),
None => (db.publisher_list_all(), db.player_list_all()),
};
let now = now_ts();
let streams: Vec<Value> = pubs
.iter()
.map(|p| {
json!({
"id": p.stream_id,
"name": p.stream_name,
"app": p.app,
"uptime": (now - p.connected_at).max(0),
"bitrate_kbps": p.bitrate_kbps,
"rtt_ms": p.rtt_ms,
"bytes_in": p.bytes_in,
"video": {
"codec": p.video_codec,
"width": p.video_width,
"height": p.video_height,
"fps": p.fps,
},
"audio": { "codec": p.audio_codec },
})
})
.collect();
let players_json: Vec<Value> = players
.iter()
.map(|pl| {
json!({
"id": pl.id,
"stream_name": pl.stream_name,
"app": pl.app,
"uptime": (now - pl.connected_at).max(0),
"bitrate_kbps": pl.bitrate_kbps,
"rtt_ms": pl.rtt_ms,
"bytes_out": pl.bytes_out,
})
})
.collect();
json!({
"streams": streams,
"players": players_json,
"summary": {
"publishers": pubs.len(),
"players": players.len(),
"total_clients": pubs.len() + players.len(),
},
})
}
/// Key-protected public stats: flat JSON while live; `None` when offline.
fn build_public_json_stats(db: &Db, stream_id: &str) -> Option<Value> {
let pubs = db.publisher_list(Some(stream_id));
let p = pubs.first()?;
let now = now_ts();
Some(json!({
"uptime": (now - p.connected_at).max(0),
"bitrate_kbps": p.bitrate_kbps,
"rtt_ms": p.rtt_ms,
"bytes_in": p.bytes_in,
"video": {
"codec": p.video_codec,
"width": p.video_width,
"height": p.video_height,
"fps": p.fps,
},
"audio": { "codec": p.audio_codec },
}))
}
// ---------- XML stats (nginx-rtmp compatible) ----------
fn build_nginx_xml(db: &Db, stream_id: Option<&str>, redact_identifiers: bool) -> String {
let (pubs, players) = match stream_id {
Some(id) => (db.publisher_list(Some(id)), db.player_list(Some(id))),
None => (db.publisher_list_all(), db.player_list_all()),
};
let now = now_ts();
let app_name = if redact_identifiers {
"live"
} else {
pubs.first()
.map(|p| p.app.as_str())
.or_else(|| players.first().map(|pl| pl.app.as_str()))
.unwrap_or("live")
};
let mut out = String::with_capacity(8192);
out.push_str(&format!(
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\
<?xml-stylesheet type=\"text/xsl\" href=\"/stat.xsl\"?>\n<rtmp>\n <server>\n\
\x20\x20\x20\x20<application>\n <name>{}</name>\n <live>\n",
xml_escape(app_name),
));
// nginx-rtmp represents a stream as one <stream> element per stream name,
// with one <client> child per connected session (publisher and players
// alike). Emitting a separate <stream> per publisher/player — as this
// used to — makes a viewer session shadow the publisher's bitrate under
// the same (possibly redacted) name, since consumers like NOALBS match
// on stream name and take the last hit.
struct StreamGroup {
label: String,
uptime_ms: i64,
bw_in: i64,
bytes_in: u64,
bw_out: i64,
bytes_out: u64,
publishing: bool,
video: Option<(u32, u32, f64, String)>,
audio: Option<(String, u32, u32)>,
clients: String,
}
fn find_group<'g>(groups: &'g mut Vec<StreamGroup>, label: &str) -> &'g mut StreamGroup {
if !groups.iter().any(|g| g.label == label) {
groups.push(StreamGroup {
label: label.to_string(),
uptime_ms: 0,
bw_in: 0,
bytes_in: 0,
bw_out: 0,
bytes_out: 0,
publishing: false,
video: None,
audio: None,
clients: String::new(),
});
}
groups.iter_mut().find(|g| g.label == label).unwrap()
}
let mut groups: Vec<StreamGroup> = Vec::new();
for p in &pubs {
let uptime_ms = (now - p.connected_at).max(0) * 1000;
// librtmp2-server tracks one combined bitrate per publisher, not separate
// audio/video bandwidth like nginx-rtmp does, so bw_video mirrors bw_in —
// nginx-rtmp-compatible consumers (e.g. NOALBS) read bw_video for switching.
let bw_in = (p.bitrate_kbps * 1000.0) as i64;
let stream_label = if redact_identifiers {
"stream"
} else {
p.stream_name.as_str()
};
let group = find_group(&mut groups, stream_label);
group.uptime_ms = uptime_ms;
group.bw_in = bw_in;
group.bytes_in = p.bytes_in;
group.publishing = true;
if !p.video_codec.is_empty() {
group.video = Some((p.video_width, p.video_height, p.fps, p.video_codec.clone()));
}
if !p.audio_codec.is_empty() {
group.audio = Some((p.audio_codec.clone(), p.audio_sample_rate, p.audio_channels));
}
group.clients.push_str(&format!(
" <client>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<time>{uptime_ms}</time>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<flashver>FMLE/3.0</flashver>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<dropped>0</dropped>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<avsync>0</avsync>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<timestamp>{uptime_ms}</timestamp>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<active>1</active>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<publisher>1</publisher>\n\
\x20\x20\x20\x20\x20\x20\x20\x20</client>\n",
));
}
for pl in &players {
let uptime_ms = (now - pl.connected_at).max(0) * 1000;
let bw_out = (pl.bitrate_kbps * 1000.0) as i64;
let stream_label = if redact_identifiers {
"stream"
} else {
pl.stream_name.as_str()
};
let group = find_group(&mut groups, stream_label);
if group.clients.is_empty() {
group.uptime_ms = uptime_ms;
}
group.bw_out += bw_out;
group.bytes_out += pl.bytes_out;
group.clients.push_str(&format!(
" <client>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<time>{uptime_ms}</time>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<flashver>FMLE/3.0</flashver>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<dropped>0</dropped>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<avsync>0</avsync>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<timestamp>{uptime_ms}</timestamp>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<active>1</active>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<publisher>0</publisher>\n\
\x20\x20\x20\x20\x20\x20\x20\x20</client>\n",
));
}
for g in &groups {
out.push_str(&format!(
" <stream>\n\
\x20\x20\x20\x20\x20\x20\x20\x20<name>{}</name>\n\
\x20\x20\x20\x20\x20\x20\x20\x20<time>{}</time>\n\
\x20\x20\x20\x20\x20\x20\x20\x20<bw_in>{}</bw_in>\n\
\x20\x20\x20\x20\x20\x20\x20\x20<bytes_in>{}</bytes_in>\n\
\x20\x20\x20\x20\x20\x20\x20\x20<bw_out>{}</bw_out>\n\
\x20\x20\x20\x20\x20\x20\x20\x20<bytes_out>{}</bytes_out>\n\
\x20\x20\x20\x20\x20\x20\x20\x20<bw_audio>0</bw_audio>\n\
\x20\x20\x20\x20\x20\x20\x20\x20<bw_video>{}</bw_video>\n",
xml_escape(&g.label),
g.uptime_ms,
g.bw_in,
g.bytes_in,
g.bw_out,
g.bytes_out,
g.bw_in,
));
if g.publishing {
out.push_str(" <publishing/>\n <active/>\n");
}
if g.video.is_some() || g.audio.is_some() {
// NOALBS's Nginx provider models <meta> as requiring both <video>
// and <audio> children (neither is optional in its Rust struct),
// so a <meta> with only one of them fails to deserialize and the
// whole stream reads as unparseable — i.e. offline. Always emit
// both; an empty self-closing element is valid since every field
// inside Video/Audio on the NOALBS side is itself optional.
out.push_str(" <meta>\n");
if let Some((width, height, fps, codec)) = &g.video {
out.push_str(&format!(
" <video>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<width>{width}</width>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<height>{height}</height>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<frame_rate>{fps:.1}</frame_rate>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<codec>{}</codec>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<profile>baseline</profile>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<level>3.1</level>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20</video>\n",
xml_escape(codec),
));
} else {
out.push_str(" <video/>\n");
}
if let Some((codec, sample_rate, channels)) = &g.audio {
out.push_str(&format!(
" <audio>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<codec>{}</codec>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<sample_rate>{sample_rate}</sample_rate>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20<channels>{channels}</channels>\n\
\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20</audio>\n",
xml_escape(codec),
));
} else {
out.push_str(" <audio/>\n");
}
out.push_str(" </meta>\n");
}
out.push_str(&g.clients);
out.push_str(" </stream>\n");
}
out.push_str(&format!(
" <nclients>{}</nclients>\n </live>\n </application>\n </server>\n</rtmp>\n",
pubs.len() + players.len()
));
out
}
// ---------- handlers ----------
async fn handle_health(State(state): State<Arc<AppState>>, headers: HeaderMap) -> Response {
if bearer_ok(&state, &headers) {
#[cfg(feature = "cluster")]
{
if let Some(mgr) = state.coordinator.cluster_manager() {
return Json(json!({
"status": "ok",
"timestamp": now_ts(),
"rtmp_port": state.config.rtmp_port(),
"rtmps_enabled": state.config.tls_enabled,
"rtmps_port": state.config.rtmps_port(),
"cluster": mgr.health_cluster_block(),
}))
.into_response();
}
}
return Json(json!({
"status": "ok",
"timestamp": now_ts(),
"rtmp_port": state.config.rtmp_port(),
"rtmps_enabled": state.config.tls_enabled,
"rtmps_port": state.config.rtmps_port(),
"cluster": { "enabled": false },
}))
.into_response();
}
Json(json!({"status": "ok"})).into_response()
}
async fn handle_stats_json(
State(state): State<Arc<AppState>>,
addr: ClientAddr,
headers: HeaderMap,
Query(q): Query<KeyQuery>,
) -> Response {
let peer = http_peer(&state, addr, &headers);
let start = Instant::now();
if q.key.is_empty() {
let status = StatusCode::UNAUTHORIZED;
log_http_access("GET", "/stats", &peer, status, "stats_key required");
return pace_public_stats(start, public_stats_text(status, "stats_key required")).await;
}
let Some(s) = stats_key_lookup(&state, &q.key, None) else {
log_http_access("GET", "/stats", &peer, StatusCode::OK, "invalid stats key");
return pace_public_stats(start, public_stats_offline_response()).await;
};
let (response, detail) = match build_public_json_stats(&state.db, &s.id) {
Some(body) => (Json(body).into_response(), format!("stream='{}'", s.id)),
None => (
public_stats_offline_response(),
format!("stream='{}' offline", s.id),
),
};
log_http_access("GET", "/stats", &peer, StatusCode::OK, &detail);
pace_public_stats(start, response).await
}
/// Dark-themed nginx-rtmp-compatible XSLT stylesheet for `/stats-nginx`. The
/// XML response links here via an `<?xml-stylesheet?>` processing
/// instruction, so browsers render the raw XML as an HTML table instead —
/// same idea as `nginx-rtmp-module`'s classic `stat.xsl`, just dark.
const STAT_XSL: &str = r#"<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" encoding="utf-8" indent="yes" doctype-system="about:legacy-compat"/>
<xsl:template match="/rtmp">
<html>
<head>
<title>librtmp2-server stats</title>
<meta charset="utf-8"/>
<style>
:root { color-scheme: dark; }
* { box-sizing: border-box; }
body {
background: #0d1117; color: #c9d1d9; margin: 1rem;
font-family: Roboto, -apple-system, "Segoe UI", sans-serif;
}
table { border-collapse: collapse; width: 100%; background: #161b22; border: 1px solid #21262d; }
th, td { padding: 0.35rem 0.6rem; border-bottom: 1px solid #21262d; border-right: 1px solid #21262d; text-align: left; font-size: 0.85rem; }
th:last-child, td:last-child { border-right: none; }
tr:last-child td { border-bottom: none; }
th { background: #0d1117; color: #8b949e; font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.05em; }
tbody tr:hover { background: #1c2128; }
.state-live { color: #3fb950; font-weight: 600; }
.state-off { color: #f85149; font-weight: 600; }
.section { background: #21262d; font-weight: 600; }
.clients { margin: 0; padding: 0.5rem 0.6rem 0.6rem; background: #0d1117; }
.clients table { background: transparent; border: none; }
.clients th, .clients td { font-size: 0.78rem; padding: 0.3rem 0.6rem; border-right: none; border-bottom: 1px solid #1c2128; }
details summary { cursor: pointer; color: #58a6ff; font-size: 0.8rem; list-style: none; }
details summary::-webkit-details-marker { display: none; }
details summary::before { content: "▸ "; }
details[open] summary::before { content: "▾ "; }
.empty { color: #484f58; font-style: italic; padding: 0.6rem; }
</style>
</head>
<body>
<xsl:for-each select="server/application">
<table>
<thead>
<tr>
<th rowspan="2">RTMP</th>
<th rowspan="2">#clients</th>
<th colspan="4">Video</th>
<th colspan="4">Audio</th>
<th rowspan="2">In bytes</th>
<th rowspan="2">Out bytes</th>
<th rowspan="2">In bits/s</th>
<th rowspan="2">Out bits/s</th>
<th rowspan="2">State</th>
<th rowspan="2">Time</th>
</tr>
<tr>
<th>codec</th><th>bits/s</th><th>size</th><th>fps</th>
<th>codec</th><th>bits/s</th><th>freq</th><th>chan</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="15">Accepted: <xsl:value-of select="live/nclients"/></td>
</tr>
<tr class="section">
<td colspan="15"><xsl:value-of select="name"/></td>
</tr>
<xsl:choose>
<xsl:when test="live/stream">
<xsl:for-each select="live/stream">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="count(client)"/></td>
<td><xsl:value-of select="meta/video/codec"/></td>
<td><xsl:value-of select="round(bw_video div 1000)"/>K</td>
<td><xsl:value-of select="meta/video/width"/>x<xsl:value-of select="meta/video/height"/></td>
<td><xsl:value-of select="meta/video/frame_rate"/></td>
<td><xsl:value-of select="meta/audio/codec"/></td>
<td><xsl:value-of select="round(bw_audio div 1000)"/>K</td>
<td><xsl:value-of select="meta/audio/sample_rate"/></td>
<td><xsl:value-of select="meta/audio/channels"/></td>
<td><xsl:value-of select="bytes_in"/></td>
<td><xsl:value-of select="bytes_out"/></td>
<td><xsl:value-of select="round(bw_in div 1000)"/>Kb/s</td>
<td><xsl:value-of select="round(bw_out div 1000)"/>Kb/s</td>
<td>
<xsl:choose>
<xsl:when test="active"><span class="state-live">LIVE</span></xsl:when>
<xsl:otherwise><span class="state-off">OFFLINE</span></xsl:otherwise>
</xsl:choose>
</td>
<td><xsl:value-of select="round(time div 1000)"/>s</td>
</tr>
<tr>
<td colspan="16" style="padding: 0;">
<details>
<summary style="padding: 0.3rem 0.6rem;">
<xsl:value-of select="count(client)"/> client(s)
</summary>
<div class="clients">
<table>
<thead>
<tr><th>Role</th><th>Time</th><th>Dropped</th></tr>
</thead>
<tbody>
<xsl:for-each select="client">
<tr>
<td>
<xsl:choose>
<xsl:when test="publisher = 1">publisher</xsl:when>
<xsl:otherwise>player</xsl:otherwise>
</xsl:choose>
</td>
<td><xsl:value-of select="round(time div 1000)"/>s</td>
<td><xsl:value-of select="dropped"/></td>
</tr>
</xsl:for-each>
</tbody>
</table>
</div>
</details>
</td>
</tr>
</xsl:for-each>
</xsl:when>
<xsl:otherwise>
<tr><td colspan="16" class="empty">live streams: 0</td></tr>
</xsl:otherwise>
</xsl:choose>
</tbody>
</table>
</xsl:for-each>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
"#;
async fn handle_stat_xsl(
addr: ClientAddr,
headers: HeaderMap,
State(state): State<Arc<AppState>>,
) -> Response {
let peer = http_peer(&state, addr, &headers);
log_http_access("GET", "/stat.xsl", &peer, StatusCode::OK, "");
(
StatusCode::OK,
[("Content-Type", "text/xsl; charset=utf-8")],
STAT_XSL,
)
.into_response()
}
async fn handle_stats_nginx(
State(state): State<Arc<AppState>>,
addr: ClientAddr,
headers: HeaderMap,
Query(q): Query<KeyQuery>,
) -> Response {
let peer = http_peer(&state, addr, &headers);
let start = Instant::now();
if q.key.is_empty() {
let status = StatusCode::UNAUTHORIZED;
log_http_access("GET", "/stats-nginx", &peer, status, "stats_key required");
return pace_public_stats(start, err_xml(status, "Missing stats key")).await;
}
let Some(s) = stats_key_lookup(&state, &q.key, None) else {
log_http_access(
"GET",
"/stats-nginx",
&peer,
StatusCode::OK,
"invalid stats key",
);
return pace_public_stats(start, public_stats_offline_nginx(&state.db)).await;
};
log_http_access(
"GET",
"/stats-nginx",
&peer,
StatusCode::OK,
&format!("stream='{}'", s.id),
);
let response = xml_response(
StatusCode::OK,
build_nginx_xml(&state.db, Some(&s.id), true),
);
pace_public_stats(start, response).await
}
async fn handle_streams_list(State(state): State<Arc<AppState>>, headers: HeaderMap) -> Response {
if !bearer_ok(&state, &headers) {
return err_json(
StatusCode::UNAUTHORIZED,
"UNAUTHORIZED",
"Missing or invalid token",
);
}
// Bearer-authenticated admin view — includes keys for panels like librtmp2-server-panel.
let list: Vec<Value> = state
.db
.stream_list()
.iter()
.map(|s| stream_to_json(&state.db, s))
.collect();
Json(list).into_response()
}
#[derive(Deserialize, Default)]
struct CreateStreamRequest {
id: Option<String>,
name: Option<String>,
app: Option<String>,
publish_key: Option<String>,
play_key: Option<String>,
stats_key: Option<String>,
}
async fn handle_stream_create(
State(state): State<Arc<AppState>>,
addr: ClientAddr,
headers: HeaderMap,
body: Option<Json<CreateStreamRequest>>,
) -> Response {
const PATH: &str = "/api/v1/streams";
let peer = http_peer(&state, addr, &headers);
if !bearer_ok(&state, &headers) {
log_http_access(
"POST",
PATH,
&peer,
StatusCode::UNAUTHORIZED,
"missing or invalid token",
);
return err_json(
StatusCode::UNAUTHORIZED,
"UNAUTHORIZED",
"Missing or invalid token",
);
}
let req = body.map(|Json(r)| r).unwrap_or_default();
let Some(id) = req
.id
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
else {
log_http_access(
"POST",
PATH,
&peer,
StatusCode::BAD_REQUEST,
"missing 'id' field",
);
return err_json(StatusCode::BAD_REQUEST, "BAD_REQUEST", "Missing 'id' field");
};
let app = req
.app
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "live".to_string());
let name = req
.name
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| id.clone());
if !is_valid_stream_key_part(&id) {
log_http_access(
"POST",
PATH,
&peer,
StatusCode::BAD_REQUEST,
"invalid stream id",
);
return err_json(
StatusCode::BAD_REQUEST,
"BAD_REQUEST",
"Stream id must be 1-63 characters and use only letters, numbers, dots, underscores, or hyphens",
);
}
if !is_valid_stream_key_part(&app) {
log_http_access("POST", PATH, &peer, StatusCode::BAD_REQUEST, "invalid app");
return err_json(
StatusCode::BAD_REQUEST,
"BAD_REQUEST",
"App must be 1-63 characters and use only letters, numbers, dots, underscores, or hyphens",
);
}
if !is_valid_display_name(&name) {
log_http_access("POST", PATH, &peer, StatusCode::BAD_REQUEST, "invalid name");