-
Notifications
You must be signed in to change notification settings - Fork 188
/
server.rs
1999 lines (1667 loc) · 68 KB
/
server.rs
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
//!
//! Provides an HTTP(S) server in `EspHttpServer`, plus all related structs.
//!
//! Typical usage of `EspHttpServer` involves creating a function (or closure)
//! for every URI+method that the server is meant to handle. A minimal server that
//! only handles HTTP GET requests to `index.html` looks like this:
//!
//! ```
//! use esp_idf_svc::http::server::{Configuration, EspHttpServer};
//!
//! let mut server = EspHttpServer::new(&Configuration::default())?;
//!
//! server.fn_handler("/index.html", Method::Get, |request| {
//! request
//! .into_ok_response()?
//! .write_all(b"<html><body>Hello world!</body></html>")
//! })?;
//! ```
//!
//! Note that the server is automatically started when instantiated, and stopped
//! when dropped. If you want to keep the server running indefinitely then
//! make sure it's not dropped - you may add an infinite loop after the server
//! is created, use `core::mem::forget`, or keep around a reference to it somehow.
//!
//! You can find an example of handling GET/POST requests at [`examples/http_server.rs`](https://github.com/esp-rs/esp-idf-svc/blob/master/examples/http_server.rs).
//!
//! You can find an example of HTTP+Websockets at [`examples/http_ws_server.rs`](https://github.com/esp-rs/esp-idf-svc/blob/master/examples/http_ws_server.rs).
//!
//! By default, the ESP-IDF library allocates 512 bytes for reading and parsing
//! HTTP headers, but desktop web browsers might send headers longer than that.
//! If this becomes a problem, add `CONFIG_HTTPD_MAX_REQ_HDR_LEN=1024` to your
//! `sdkconfig.defaults` file.
use core::cell::UnsafeCell;
use core::fmt::Debug;
use core::marker::PhantomData;
use core::sync::atomic::{AtomicBool, Ordering};
use core::time::*;
use core::{ffi, ptr};
extern crate alloc;
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::string::ToString;
use alloc::sync::Arc;
use alloc::vec::Vec;
use ::log::{info, warn};
use embedded_svc::http::headers::content_type;
use embedded_svc::http::*;
use embedded_svc::io::{ErrorType, Read, Write};
use crate::sys::*;
use uncased::{Uncased, UncasedStr};
use crate::handle::RawHandle;
use crate::io::EspIOError;
use crate::private::common::Newtype;
use crate::private::cstr::to_cstring_arg;
use crate::private::cstr::{CStr, CString};
use crate::private::mutex::Mutex;
#[cfg(esp_idf_esp_https_server_enable)]
use crate::tls::X509;
pub use embedded_svc::http::server::{
CompositeHandler, Connection, FnHandler, Handler, Middleware, Request, Response,
};
pub use embedded_svc::utils::http::server::registration::*;
pub use super::*;
#[derive(Copy, Clone, Debug)]
pub struct Configuration {
pub http_port: u16,
pub ctrl_port: u16,
pub https_port: u16,
pub max_sessions: usize,
pub session_timeout: Duration,
pub stack_size: usize,
pub max_open_sockets: usize,
pub max_uri_handlers: usize,
pub max_resp_headers: usize,
pub lru_purge_enable: bool,
pub uri_match_wildcard: bool,
#[cfg(esp_idf_esp_https_server_enable)]
pub server_certificate: Option<X509<'static>>,
#[cfg(esp_idf_esp_https_server_enable)]
pub private_key: Option<X509<'static>>,
}
impl Default for Configuration {
fn default() -> Self {
Configuration {
http_port: 80,
ctrl_port: 32768,
https_port: 443,
max_sessions: 16,
session_timeout: Duration::from_secs(20 * 60),
#[cfg(not(esp_idf_esp_https_server_enable))]
stack_size: 6144,
#[cfg(esp_idf_esp_https_server_enable)]
stack_size: 10240,
max_open_sockets: 4,
max_uri_handlers: 32,
max_resp_headers: 8,
lru_purge_enable: true,
uri_match_wildcard: false,
#[cfg(esp_idf_esp_https_server_enable)]
server_certificate: None,
#[cfg(esp_idf_esp_https_server_enable)]
private_key: None,
}
}
}
impl From<&Configuration> for Newtype<httpd_config_t> {
#[allow(clippy::needless_update)]
fn from(conf: &Configuration) -> Self {
Self(httpd_config_t {
task_priority: 5,
// Since 5.3.0
#[cfg(any(
all(not(esp_idf_version_major = "4"), not(esp_idf_version_major = "5")),
all(
esp_idf_version_major = "5",
not(any(
esp_idf_version_minor = "0",
esp_idf_version_minor = "1",
esp_idf_version_minor = "2"
))
),
))]
task_caps: (MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT),
stack_size: conf.stack_size,
core_id: i32::MAX,
server_port: conf.http_port,
ctrl_port: conf.ctrl_port,
max_open_sockets: conf.max_open_sockets as _,
max_uri_handlers: conf.max_uri_handlers as _,
max_resp_headers: conf.max_resp_headers as _,
backlog_conn: 5,
lru_purge_enable: conf.lru_purge_enable,
recv_wait_timeout: 5,
send_wait_timeout: 5,
global_user_ctx: ptr::null_mut(),
global_user_ctx_free_fn: None,
global_transport_ctx: ptr::null_mut(),
global_transport_ctx_free_fn: None,
open_fn: None,
close_fn: None,
uri_match_fn: conf.uri_match_wildcard.then_some(httpd_uri_match_wildcard),
// Latest 4.4 and master branches have options to control SO linger,
// but these are not released yet so we cannot (yet) support these
// conditionally
..Default::default()
})
}
}
#[allow(non_upper_case_globals)]
impl From<Newtype<ffi::c_uint>> for Method {
fn from(method: Newtype<ffi::c_uint>) -> Self {
match method.0 {
http_method_HTTP_GET => Method::Get,
http_method_HTTP_POST => Method::Post,
http_method_HTTP_DELETE => Method::Delete,
http_method_HTTP_HEAD => Method::Head,
http_method_HTTP_PUT => Method::Put,
http_method_HTTP_CONNECT => Method::Connect,
http_method_HTTP_OPTIONS => Method::Options,
http_method_HTTP_TRACE => Method::Trace,
http_method_HTTP_COPY => Method::Copy,
http_method_HTTP_LOCK => Method::Lock,
http_method_HTTP_MKCOL => Method::MkCol,
http_method_HTTP_MOVE => Method::Move,
http_method_HTTP_PROPFIND => Method::Propfind,
http_method_HTTP_PROPPATCH => Method::Proppatch,
http_method_HTTP_SEARCH => Method::Search,
http_method_HTTP_UNLOCK => Method::Unlock,
http_method_HTTP_BIND => Method::Bind,
http_method_HTTP_REBIND => Method::Rebind,
http_method_HTTP_UNBIND => Method::Unbind,
http_method_HTTP_ACL => Method::Acl,
http_method_HTTP_REPORT => Method::Report,
http_method_HTTP_MKACTIVITY => Method::MkActivity,
http_method_HTTP_CHECKOUT => Method::Checkout,
http_method_HTTP_MERGE => Method::Merge,
http_method_HTTP_MSEARCH => Method::MSearch,
http_method_HTTP_NOTIFY => Method::Notify,
http_method_HTTP_SUBSCRIBE => Method::Subscribe,
http_method_HTTP_UNSUBSCRIBE => Method::Unsubscribe,
http_method_HTTP_PATCH => Method::Patch,
http_method_HTTP_PURGE => Method::Purge,
http_method_HTTP_MKCALENDAR => Method::MkCalendar,
http_method_HTTP_LINK => Method::Link,
http_method_HTTP_UNLINK => Method::Unlink,
_ => unreachable!(),
}
}
}
#[cfg(esp_idf_esp_https_server_enable)]
impl From<&Configuration> for Newtype<httpd_ssl_config_t> {
fn from(conf: &Configuration) -> Self {
let http_config: Newtype<httpd_config_t> = conf.into();
// start in insecure mode if no certificates are set
let transport_mode = match (conf.server_certificate, conf.private_key) {
(Some(_), Some(_)) => httpd_ssl_transport_mode_t_HTTPD_SSL_TRANSPORT_SECURE,
_ => {
warn!("Starting server in insecure mode because no certificates were set in the http config.");
httpd_ssl_transport_mode_t_HTTPD_SSL_TRANSPORT_INSECURE
}
};
// Default values taken from: https://github.com/espressif/esp-idf/blob/master/components/esp_https_server/include/esp_https_server.h#L114
#[allow(clippy::needless_update)]
Self(httpd_ssl_config_t {
httpd: http_config.0,
session_tickets: false,
#[cfg(not(esp_idf_version_major = "4"))]
use_secure_element: false,
port_secure: conf.https_port,
port_insecure: conf.http_port,
transport_mode,
cacert_pem: ptr::null(),
cacert_len: 0,
prvtkey_pem: ptr::null(),
prvtkey_len: 0,
#[cfg(esp_idf_version_major = "4")]
client_verify_cert_pem: ptr::null(),
#[cfg(esp_idf_version_major = "4")]
client_verify_cert_len: 0,
#[cfg(not(esp_idf_version_major = "4"))]
servercert: ptr::null(),
#[cfg(not(esp_idf_version_major = "4"))]
servercert_len: 0,
user_cb: None,
..Default::default()
})
}
}
impl From<Method> for Newtype<ffi::c_uint> {
fn from(method: Method) -> Self {
Self(match method {
Method::Get => http_method_HTTP_GET,
Method::Post => http_method_HTTP_POST,
Method::Delete => http_method_HTTP_DELETE,
Method::Head => http_method_HTTP_HEAD,
Method::Put => http_method_HTTP_PUT,
Method::Connect => http_method_HTTP_CONNECT,
Method::Options => http_method_HTTP_OPTIONS,
Method::Trace => http_method_HTTP_TRACE,
Method::Copy => http_method_HTTP_COPY,
Method::Lock => http_method_HTTP_LOCK,
Method::MkCol => http_method_HTTP_MKCOL,
Method::Move => http_method_HTTP_MOVE,
Method::Propfind => http_method_HTTP_PROPFIND,
Method::Proppatch => http_method_HTTP_PROPPATCH,
Method::Search => http_method_HTTP_SEARCH,
Method::Unlock => http_method_HTTP_UNLOCK,
Method::Bind => http_method_HTTP_BIND,
Method::Rebind => http_method_HTTP_REBIND,
Method::Unbind => http_method_HTTP_UNBIND,
Method::Acl => http_method_HTTP_ACL,
Method::Report => http_method_HTTP_REPORT,
Method::MkActivity => http_method_HTTP_MKACTIVITY,
Method::Checkout => http_method_HTTP_CHECKOUT,
Method::Merge => http_method_HTTP_MERGE,
Method::MSearch => http_method_HTTP_MSEARCH,
Method::Notify => http_method_HTTP_NOTIFY,
Method::Subscribe => http_method_HTTP_SUBSCRIBE,
Method::Unsubscribe => http_method_HTTP_UNSUBSCRIBE,
Method::Patch => http_method_HTTP_PATCH,
Method::Purge => http_method_HTTP_PURGE,
Method::MkCalendar => http_method_HTTP_MKCALENDAR,
Method::Link => http_method_HTTP_LINK,
Method::Unlink => http_method_HTTP_UNLINK,
})
}
}
static OPEN_SESSIONS: Mutex<BTreeMap<(u32, ffi::c_int), Arc<AtomicBool>>> =
Mutex::new(BTreeMap::new());
static CLOSE_HANDLERS: Mutex<BTreeMap<u32, Vec<CloseHandler<'static>>>> =
Mutex::new(BTreeMap::new());
type NativeHandler<'a> = Box<dyn Fn(*mut httpd_req_t) -> ffi::c_int + 'a>;
type CloseHandler<'a> = Box<dyn Fn(ffi::c_int) + Send + 'a>;
pub struct EspHttpServer<'a> {
sd: httpd_handle_t,
registrations: Vec<(CString, crate::sys::httpd_uri_t)>,
_reg: PhantomData<&'a ()>,
}
impl EspHttpServer<'static> {
pub fn new(conf: &Configuration) -> Result<Self, EspIOError> {
Self::internal_new(conf)
}
}
/// HTTP server
impl<'a> EspHttpServer<'a> {
/// # Safety
///
/// This method - in contrast to method `new` - allows the user to set
/// non-static callbacks/closures as handlers into the returned `EspHttpServer` service. This enables users to borrow
/// - in the closure - variables that live on the stack - or more generally - in the same
/// scope where the service is created.
///
/// HOWEVER: care should be taken NOT to call `core::mem::forget()` on the service,
/// as that would immediately lead to an UB (crash).
/// Also note that forgetting the service might happen with `Rc` and `Arc`
/// when circular references are introduced: https://github.com/rust-lang/rust/issues/24456
///
/// The reason is that the closure is actually sent to a hidden ESP IDF thread.
/// This means that if the service is forgotten, Rust is free to e.g. unwind the stack
/// and the closure now owned by this other thread will end up with references to variables that no longer exist.
///
/// The destructor of the service takes care - prior to the service being dropped and e.g.
/// the stack being unwind - to remove the closure from the hidden thread and destroy it.
/// Unfortunately, when the service is forgotten, the un-subscription does not happen
/// and invalid references are left dangling.
///
/// This "local borrowing" will only be possible to express in a safe way once/if `!Leak` types
/// are introduced to Rust (i.e. the impossibility to "forget" a type and thus not call its destructor).
pub unsafe fn new_nonstatic(conf: &Configuration) -> Result<Self, EspIOError> {
Self::internal_new(conf)
}
fn internal_new(conf: &Configuration) -> Result<Self, EspIOError> {
let mut handle: httpd_handle_t = ptr::null_mut();
let handle_ref = &mut handle;
#[cfg(not(esp_idf_esp_https_server_enable))]
{
let mut config: Newtype<httpd_config_t> = conf.into();
config.0.close_fn = Some(Self::close_fn);
esp!(unsafe { httpd_start(handle_ref, &config.0 as *const _) })?;
}
#[cfg(esp_idf_esp_https_server_enable)]
{
let mut config: Newtype<httpd_ssl_config_t> = conf.into();
config.0.httpd.close_fn = Some(Self::close_fn);
if let (Some(cert), Some(private_key)) = (conf.server_certificate, conf.private_key) {
// NOTE: Contrary to other components in ESP IDF (HTTP & MQTT client),
// HTTP server does allocate internal buffers for the certificates
// Moreover - due to internal implementation details - it needs the
// full length of the certificate, even for the PEM case
#[cfg(esp_idf_version_major = "4")]
{
config.0.cacert_pem = cert.as_esp_idf_raw_ptr() as _;
config.0.cacert_len = cert.as_esp_idf_raw_len();
}
#[cfg(not(esp_idf_version_major = "4"))]
{
config.0.servercert = cert.as_esp_idf_raw_ptr() as _;
config.0.servercert_len = cert.as_esp_idf_raw_len();
}
config.0.prvtkey_pem = private_key.as_esp_idf_raw_ptr() as _;
config.0.prvtkey_len = private_key.as_esp_idf_raw_len();
esp!(unsafe { httpd_ssl_start(handle_ref, &mut config.0) })?;
} else {
esp!(unsafe { httpd_ssl_start(handle_ref, &mut config.0) })?;
}
}
info!("Started Httpd server with config {:?}", conf);
let server = Self {
sd: handle,
registrations: Vec::new(),
_reg: PhantomData,
};
CLOSE_HANDLERS.lock().insert(server.sd as _, Vec::new());
Ok(server)
}
/// Unregisters a URI.
fn unregister(&mut self, uri: CString, conf: httpd_uri_t) -> Result<(), EspIOError> {
unsafe {
esp!(httpd_unregister_uri_handler(
self.sd,
uri.as_ptr() as _,
conf.method
))?;
let _drop = Box::from_raw(conf.user_ctx as *mut NativeHandler<'static>);
};
info!(
"Unregistered Httpd server handler {:?} for URI \"{}\"",
conf.method,
uri.to_str().unwrap()
);
Ok(())
}
/// Stops the server.
fn stop(&mut self) -> Result<(), EspIOError> {
if !self.sd.is_null() {
while let Some((uri, registration)) = self.registrations.pop() {
self.unregister(uri, registration)?;
}
// Maybe its better to always call httpd_stop because httpd_ssl_stop directly wraps httpd_stop anyways
// https://github.com/espressif/esp-idf/blob/e6fda46a02c41777f1d116a023fbec6a1efaffb9/components/esp_https_server/src/https_server.c#L268
#[cfg(not(esp_idf_esp_https_server_enable))]
esp!(unsafe { crate::sys::httpd_stop(self.sd) })?;
// httpd_ssl_stop doesn't return EspErr for some reason. It returns void.
#[cfg(all(esp_idf_esp_https_server_enable, esp_idf_version_major = "4"))]
unsafe {
crate::sys::httpd_ssl_stop(self.sd)
};
// esp-idf version 5 does return EspErr
#[cfg(all(esp_idf_esp_https_server_enable, not(esp_idf_version_major = "4")))]
esp!(unsafe { crate::sys::httpd_ssl_stop(self.sd) })?;
CLOSE_HANDLERS.lock().remove(&(self.sd as u32));
self.sd = ptr::null_mut();
}
info!("Httpd server stopped");
Ok(())
}
pub fn handler_chain<C>(&mut self, chain: C) -> Result<&mut Self, EspError>
where
C: EspHttpTraversableChain<'a>,
{
chain.accept(self)?;
Ok(self)
}
/// # Safety
///
/// This method - in contrast to method `handler_chain` - allows the user to pass
/// a chain of non-static callbacks/closures. This enables users to borrow
/// - in the closure - variables that live on the stack - or more generally - in the same
/// scope where the service is created.
///
/// HOWEVER: care should be taken NOT to call `core::mem::forget()` on the service,
/// as that would immediately lead to an UB (crash).
/// Also note that forgetting the service might happen with `Rc` and `Arc`
/// when circular references are introduced: https://github.com/rust-lang/rust/issues/24456
///
/// The reason is that the closure is actually sent to a hidden ESP IDF thread.
/// This means that if the service is forgotten, Rust is free to e.g. unwind the stack
/// and the closure now owned by this other thread will end up with references to variables that no longer exist.
///
/// The destructor of the service takes care - prior to the service being dropped and e.g.
/// the stack being unwind - to remove the closure from the hidden thread and destroy it.
/// Unfortunately, when the service is forgotten, the un-subscription does not happen
/// and invalid references are left dangling.
///
/// This "local borrowing" will only be possible to express in a safe way once/if `!Leak` types
/// are introduced to Rust (i.e. the impossibility to "forget" a type and thus not call its destructor).
pub unsafe fn handler_chain_nonstatic<C>(&mut self, chain: C) -> Result<&mut Self, EspError>
where
C: EspHttpTraversableChainNonstatic<'a>,
{
chain.accept(self)?;
Ok(self)
}
/// Registers a `Handler` for a URI and a method (GET, POST, etc).
pub fn handler<H>(
&mut self,
uri: &str,
method: Method,
handler: H,
) -> Result<&mut Self, EspError>
where
H: for<'r> Handler<EspHttpConnection<'r>> + Send + 'static,
{
unsafe { self.handler_nonstatic(uri, method, handler) }
}
/// Registers a `Handler` for a URI and a method (GET, POST, etc).
///
/// # Safety
///
/// This method - in contrast to method `handler` - allows the user to pass
/// a non-static callback/closure. This enables users to borrow
/// - in the closure - variables that live on the stack - or more generally - in the same
/// scope where the service is created.
///
/// HOWEVER: care should be taken NOT to call `core::mem::forget()` on the service,
/// as that would immediately lead to an UB (crash).
/// Also note that forgetting the service might happen with `Rc` and `Arc`
/// when circular references are introduced: https://github.com/rust-lang/rust/issues/24456
///
/// The reason is that the closure is actually sent to a hidden ESP IDF thread.
/// This means that if the service is forgotten, Rust is free to e.g. unwind the stack
/// and the closure now owned by this other thread will end up with references to variables that no longer exist.
///
/// The destructor of the service takes care - prior to the service being dropped and e.g.
/// the stack being unwind - to remove the closure from the hidden thread and destroy it.
/// Unfortunately, when the service is forgotten, the un-subscription does not happen
/// and invalid references are left dangling.
///
/// This "local borrowing" will only be possible to express in a safe way once/if `!Leak` types
/// are introduced to Rust (i.e. the impossibility to "forget" a type and thus not call its destructor).
pub unsafe fn handler_nonstatic<H>(
&mut self,
uri: &str,
method: Method,
handler: H,
) -> Result<&mut Self, EspError>
where
H: for<'r> Handler<EspHttpConnection<'r>> + Send + 'a,
{
let c_str = to_cstring_arg(uri)?;
#[allow(clippy::needless_update)]
let conf = httpd_uri_t {
uri: c_str.as_ptr() as _,
method: Newtype::<ffi::c_uint>::from(method).0,
user_ctx: Box::into_raw(Box::new(self.to_native_handler(handler))) as *mut _,
handler: Some(EspHttpServer::handle_req),
..Default::default()
};
esp!(unsafe { crate::sys::httpd_register_uri_handler(self.sd, &conf) })?;
info!(
"Registered Httpd server handler {:?} for URI \"{}\"",
method,
c_str.to_str().unwrap()
);
self.registrations.push((c_str, conf));
Ok(self)
}
/// Registers a function as the handler for the given URI and HTTP method (GET, POST, etc).
///
/// The function will be called every time an HTTP client requests that URI
/// (via the appropriate HTTP method), receiving a different `Request` each
/// call. The `Request` contains a reference to the underlying `EspHttpConnection`.
pub fn fn_handler<E, F>(
&mut self,
uri: &str,
method: Method,
f: F,
) -> Result<&mut Self, EspError>
where
F: for<'r> Fn(Request<&mut EspHttpConnection<'r>>) -> Result<(), E> + Send + 'static,
E: Debug,
{
unsafe { self.fn_handler_nonstatic(uri, method, f) }
}
/// Registers a function as the handler for the given URI and HTTP method (GET, POST, etc).
///
/// The function will be called every time an HTTP client requests that URI
/// (via the appropriate HTTP method), receiving a different `Request` each
/// call. The `Request` contains a reference to the underlying `EspHttpConnection`.
///
/// # Safety
///
/// This method - in contrast to method `fn_handler` - allows the user to pass
/// a non-static callback/closure. This enables users to borrow
/// - in the closure - variables that live on the stack - or more generally - in the same
/// scope where the service is created.
///
/// HOWEVER: care should be taken NOT to call `core::mem::forget()` on the service,
/// as that would immediately lead to an UB (crash).
/// Also note that forgetting the service might happen with `Rc` and `Arc`
/// when circular references are introduced: https://github.com/rust-lang/rust/issues/24456
///
/// The reason is that the closure is actually sent to a hidden ESP IDF thread.
/// This means that if the service is forgotten, Rust is free to e.g. unwind the stack
/// and the closure now owned by this other thread will end up with references to variables that no longer exist.
///
/// The destructor of the service takes care - prior to the service being dropped and e.g.
/// the stack being unwind - to remove the closure from the hidden thread and destroy it.
/// Unfortunately, when the service is forgotten, the un-subscription does not happen
/// and invalid references are left dangling.
///
/// This "local borrowing" will only be possible to express in a safe way once/if `!Leak` types
/// are introduced to Rust (i.e. the impossibility to "forget" a type and thus not call its destructor).
pub unsafe fn fn_handler_nonstatic<E, F>(
&mut self,
uri: &str,
method: Method,
f: F,
) -> Result<&mut Self, EspError>
where
F: for<'r> Fn(Request<&mut EspHttpConnection<'r>>) -> Result<(), E> + Send + 'a,
E: Debug,
{
self.handler_nonstatic(uri, method, FnHandler::new(f))
}
fn to_native_handler<H>(&self, handler: H) -> NativeHandler<'a>
where
H: for<'r> Handler<EspHttpConnection<'a>> + Send + 'a,
{
Box::new(move |raw_req| {
let mut connection = EspHttpConnection::new(unsafe { raw_req.as_mut().unwrap() });
let result = connection.invoke(&handler);
match result {
Ok(()) => {
if let Err(e) = connection.complete() {
connection.handle_error(e);
}
}
Err(e) => {
connection.handle_error(e);
if let Err(e) = connection.complete() {
connection.handle_error(e);
}
}
}
ESP_OK as _
})
}
extern "C" fn handle_req(raw_req: *mut httpd_req_t) -> ffi::c_int {
let handler_ptr = (unsafe { *raw_req }).user_ctx as *mut NativeHandler<'static>;
let handler = unsafe { handler_ptr.as_ref() }.unwrap();
(handler)(raw_req)
}
extern "C" fn close_fn(sd: httpd_handle_t, sockfd: ffi::c_int) {
{
let mut sessions = OPEN_SESSIONS.lock();
if let Some(closed) = sessions.remove(&(sd as u32, sockfd)) {
closed.store(true, Ordering::SeqCst);
}
}
let all_close_handlers = CLOSE_HANDLERS.lock();
let close_handlers = all_close_handlers.get(&(sd as u32)).unwrap();
for close_handler in close_handlers {
(close_handler)(sockfd);
}
esp_nofail!(unsafe { close(sockfd) });
}
}
impl Drop for EspHttpServer<'_> {
fn drop(&mut self) {
self.stop().expect("Unable to stop the server cleanly");
}
}
impl RawHandle for EspHttpServer<'_> {
type Handle = httpd_handle_t;
fn handle(&self) -> Self::Handle {
self.sd
}
}
/// Wraps the given function into an `FnHandler`.
///
/// Do not confuse with `EspHttpServer::fn_handler`.
pub fn fn_handler<F, E>(f: F) -> FnHandler<F>
where
F: for<'a> Fn(Request<&mut EspHttpConnection<'a>>) -> Result<(), E> + Send,
E: Debug,
{
FnHandler::new(f)
}
pub trait EspHttpTraversableChain<'a> {
fn accept(self, server: &mut EspHttpServer<'a>) -> Result<(), EspError>;
}
/// # Safety
///
/// Implementing this trait means that the chain can contain non-`'static` handlers
/// and that the chain can be used with method `EspHttpServer::handler_chain_nonstatic`.
///
/// Consult the documentation of `EspHttpServer::handler_chain_nonstatic` for more
/// information on how to use non-static handler chains.
pub unsafe trait EspHttpTraversableChainNonstatic<'a>: EspHttpTraversableChain<'a> {}
impl<'a> EspHttpTraversableChain<'a> for ChainRoot {
fn accept(self, _server: &mut EspHttpServer<'a>) -> Result<(), EspError> {
Ok(())
}
}
impl<'a, H, N> EspHttpTraversableChain<'a> for ChainHandler<H, N>
where
H: for<'r> Handler<EspHttpConnection<'r>> + Send + 'static,
N: EspHttpTraversableChain<'a>,
{
fn accept(self, server: &mut EspHttpServer<'a>) -> Result<(), EspError> {
self.next.accept(server)?;
server.handler(self.path, self.method, self.handler)?;
Ok(())
}
}
/// A newtype wrapper for `ChainHandler` that allows
/// non-`'static`` handlers in the chain to be registered
/// and passed to the server.
pub struct NonstaticChain<H, N>(ChainHandler<H, N>);
impl<H, N> NonstaticChain<H, N> {
/// Wraps the given chain with a `NonstaticChain` newtype.
pub fn new(handler: ChainHandler<H, N>) -> Self {
Self(handler)
}
}
unsafe impl EspHttpTraversableChainNonstatic<'_> for ChainRoot {}
impl<'a, H, N> EspHttpTraversableChain<'a> for NonstaticChain<H, N>
where
H: for<'r> Handler<EspHttpConnection<'r>> + Send + 'a,
N: EspHttpTraversableChain<'a>,
{
fn accept(self, server: &mut EspHttpServer<'a>) -> Result<(), EspError> {
self.0.next.accept(server)?;
unsafe {
server.handler_nonstatic(self.0.path, self.0.method, self.0.handler)?;
}
Ok(())
}
}
unsafe impl<'a, H, N> EspHttpTraversableChainNonstatic<'a> for NonstaticChain<H, N>
where
H: for<'r> Handler<EspHttpConnection<'r>> + Send + 'a,
N: EspHttpTraversableChain<'a>,
{
}
pub struct EspHttpRawConnection<'a>(&'a mut httpd_req_t);
impl EspHttpRawConnection<'_> {
pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, EspError> {
if !buf.is_empty() {
let fd = unsafe { httpd_req_to_sockfd(self.0) };
let len = unsafe { crate::sys::read(fd, buf.as_mut_ptr() as *mut _, buf.len()) };
Ok(len as _)
} else {
Ok(0)
}
}
pub fn write(&mut self, buf: &[u8]) -> Result<usize, EspError> {
if !buf.is_empty() {
let fd = unsafe { httpd_req_to_sockfd(self.0) };
let len = unsafe { crate::sys::write(fd, buf.as_ptr() as *const _, buf.len()) };
Ok(len as _)
} else {
Ok(0)
}
}
pub fn write_all(&mut self, data: &[u8]) -> Result<(), EspError> {
let mut offset = 0;
while offset < data.len() {
offset += self.write(&data[offset..])?;
}
Ok(())
}
}
impl RawHandle for EspHttpRawConnection<'_> {
type Handle = *mut httpd_req_t;
fn handle(&self) -> Self::Handle {
self.0 as *const _ as *mut _
}
}
impl ErrorType for EspHttpRawConnection<'_> {
type Error = EspIOError;
}
impl Read for EspHttpRawConnection<'_> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
EspHttpRawConnection::read(self, buf).map_err(EspIOError)
}
}
impl Write for EspHttpRawConnection<'_> {
fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
EspHttpRawConnection::write(self, buf).map_err(EspIOError)
}
fn flush(&mut self) -> Result<(), Self::Error> {
Ok(())
}
}
type EspHttpHeaders = BTreeMap<Uncased<'static>, String>;
pub struct EspHttpConnection<'a> {
request: EspHttpRawConnection<'a>,
headers: Option<UnsafeCell<EspHttpHeaders>>,
response_headers: Option<Vec<CString>>,
}
/// Represents the two-way connection between an HTTP request and its response.
impl<'a> EspHttpConnection<'a> {
fn new(raw_req: &'a mut httpd_req_t) -> Self {
Self {
request: EspHttpRawConnection(raw_req),
headers: Some(UnsafeCell::new(EspHttpHeaders::new())),
response_headers: None,
}
}
// Returns the URI for the current request in this connection.
pub fn uri(&self) -> &str {
self.assert_request();
let c_uri = unsafe { CStr::from_ptr(self.request.0.uri.as_ptr()) };
c_uri.to_str().unwrap()
}
// Returns the HTTP method for the current request in this connection.
pub fn method(&self) -> Method {
self.assert_request();
Method::from(Newtype(self.request.0.method as u32))
}
// Searches for the header of the given name in the HTTP request's headers.
pub fn header(&self, name: &str) -> Option<&str> {
self.assert_request();
let headers = self.headers.as_ref().unwrap();
if let Some(value) = unsafe { headers.get().as_ref().unwrap() }.get(UncasedStr::new(name)) {
Some(value.as_ref())
} else {
let raw_req = self.request.0 as *const httpd_req_t as *mut httpd_req_t;
if let Ok(c_name) = to_cstring_arg(name) {
match unsafe { httpd_req_get_hdr_value_len(raw_req, c_name.as_ptr() as _) } {
0 => None,
len => {
// TODO: Would've been much more effective, if ESP-IDF was capable of returning a
// pointer to the header value that is in the scratch buffer
//
// Check if we can implement it ourselves vy traversing the scratch buffer manually
let mut buf: Vec<u8> = Vec::with_capacity(len + 1);
esp_nofail!(unsafe {
httpd_req_get_hdr_value_str(
raw_req,
c_name.as_ptr(),
buf.as_mut_ptr().cast(),
len + 1,
)
});
unsafe {
buf.set_len(len + 1);
}
// TODO: Replace with a proper conversion from ISO-8859-1 to UTF8
let value = String::from_utf8_lossy(&buf[..len]).into_owned();
unsafe { headers.get().as_mut().unwrap() }
.insert(Uncased::from(name.to_owned()), value);
unsafe { headers.get().as_ref().unwrap() }
.get(UncasedStr::new(name))
.map(|s| s.as_ref())
}
}
} else {
None
}
}
}
pub fn split(&mut self) -> (&EspHttpConnection<'a>, &mut Self) {
self.assert_request();
let headers_ptr: *const EspHttpConnection<'a> = self as *const _;
let headers = unsafe { headers_ptr.as_ref().unwrap() };
(headers, self)
}
/// Sends the HTTP status (e.g. "200 OK") and the response headers to the
/// HTTP client.
pub fn initiate_response(
&mut self,
status: u16,
message: Option<&str>,
headers: &[(&str, &str)],
) -> Result<(), EspError> {
self.assert_request();
let mut c_headers = Vec::new();
let status = if let Some(message) = message {
format!("{status} {message}")
} else {
status.to_string()
};
let c_status = to_cstring_arg(status.as_str())?;
esp!(unsafe { httpd_resp_set_status(self.request.0, c_status.as_ptr() as _) })?;
c_headers.push(c_status);
for (key, value) in headers {
if key.eq_ignore_ascii_case("Content-Type") {
let c_type = to_cstring_arg(value)?;
esp!(unsafe { httpd_resp_set_type(self.request.0, c_type.as_c_str().as_ptr()) })?;
c_headers.push(c_type);
} else if key.eq_ignore_ascii_case("Content-Length") {
let c_len = to_cstring_arg(value)?;
//esp!(unsafe { httpd_resp_set_len(self.raw_req, c_len.as_c_str().as_ptr()) })?;
c_headers.push(c_len);
} else {
let name = to_cstring_arg(key)?;
let value = to_cstring_arg(value)?;
esp!(unsafe {
httpd_resp_set_hdr(
self.request.0,
name.as_c_str().as_ptr() as _,
value.as_c_str().as_ptr() as _,
)
})?;
c_headers.push(name);
c_headers.push(value);
}
}
self.response_headers = Some(c_headers);
self.headers = None;
Ok(())
}
/// Returns `true` if the response headers have been sent to the HTTP client.
pub fn is_response_initiated(&self) -> bool {
self.headers.is_none()
}
/// Reads bytes from the body of the HTTP request.
///
/// This is typically used whenever the HTTP server has to parse the body
/// of an HTTP POST request.
///
/// ```
/// server.fn_handler("/foo", Method::Post, move |mut request| {
/// let (_headers, connection) = request.split();
/// let mut buffer: [u8; 1024] = [0; 1024];
/// let bytes_read = connection.read(&mut buffer)?;