-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathserver.rs
1349 lines (1097 loc) · 43.2 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
use core::cell::UnsafeCell;
use core::fmt::{Debug, Display};
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::server::{
Connection, FnHandler, Handler, HandlerError, HandlerResult, Request,
};
use embedded_svc::http::*;
use embedded_svc::io::{Io, Read, Write};
use embedded_svc::utils::http::server::registration::{ChainHandler, ChainRoot};
use esp_idf_sys::*;
use uncased::{Uncased, UncasedStr};
use crate::errors::EspIOError;
use crate::handle::RawHandle;
use crate::private::common::Newtype;
use crate::private::cstr::to_cstring_arg;
use crate::private::cstr::{CStr, CString};
use crate::private::mutex::{Mutex, RawMutex};
#[cfg(esp_idf_esp_https_server_enable)]
use crate::tls::X509;
#[derive(Copy, Clone, Debug)]
pub struct Configuration {
pub http_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_handlers: 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,
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_handlers: 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,
stack_size: conf.stack_size,
core_id: i32::MAX,
server_port: conf.http_port,
ctrl_port: 32768,
max_open_sockets: conf.max_open_sockets as _,
max_uri_handlers: conf.max_uri_handlers as _,
max_resp_headers: conf.max_resp_handlers 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::wrap(RawMutex::new(), BTreeMap::new());
static CLOSE_HANDLERS: Mutex<BTreeMap<u32, Vec<CloseHandler>>> =
Mutex::wrap(RawMutex::new(), BTreeMap::new());
type NativeHandler = Box<dyn Fn(*mut httpd_req_t) -> ffi::c_int>;
type CloseHandler = Box<dyn Fn(ffi::c_int) + Send>;
pub struct EspHttpServer {
sd: httpd_handle_t,
registrations: Vec<(CString, esp_idf_sys::httpd_uri_t)>,
}
impl EspHttpServer {
pub fn 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 = EspHttpServer {
sd: handle,
registrations: Vec::new(),
};
CLOSE_HANDLERS.lock().insert(server.sd as _, Vec::new());
Ok(server)
}
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);
};
info!(
"Unregistered Httpd server handler {:?} for URI \"{}\"",
conf.method,
uri.to_str().unwrap()
);
Ok(())
}
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 { esp_idf_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 {
esp_idf_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 { esp_idf_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,
{
chain.accept(self)?;
Ok(self)
}
pub fn handler<H>(
&mut self,
uri: &str,
method: Method,
handler: H,
) -> Result<&mut Self, EspError>
where
H: for<'a> Handler<EspHttpConnection<'a>> + 'static,
{
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 { esp_idf_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)
}
pub fn fn_handler<F>(&mut self, uri: &str, method: Method, f: F) -> Result<&mut Self, EspError>
where
F: for<'a> Fn(Request<&mut EspHttpConnection<'a>>) -> HandlerResult + Send + 'static,
{
self.handler(uri, method, FnHandler::new(f))
}
fn to_native_handler<H>(&self, handler: H) -> NativeHandler
where
H: for<'a> Handler<EspHttpConnection<'a>> + 'static,
{
Box::new(move |raw_req| {
let mut connection = EspHttpConnection::new(unsafe { raw_req.as_mut().unwrap() });
let mut result = EspHttpConnection::handle(&mut connection, &handler);
if result.is_ok() {
result = connection.complete();
}
if let Err(e) = result {
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;
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
}
}
pub fn fn_handler<F>(f: F) -> FnHandler<F>
where
F: for<'a> Fn(Request<&mut EspHttpConnection<'a>>) -> HandlerResult + Send + 'static,
{
FnHandler::new(f)
}
pub trait EspHttpTraversableChain {
fn accept(self, server: &mut EspHttpServer) -> Result<(), EspError>;
}
impl EspHttpTraversableChain for ChainRoot {
fn accept(self, _server: &mut EspHttpServer) -> Result<(), EspError> {
Ok(())
}
}
impl<H, N> EspHttpTraversableChain for ChainHandler<H, N>
where
H: for<'a> Handler<EspHttpConnection<'a>> + 'static,
N: EspHttpTraversableChain,
{
fn accept(self, server: &mut EspHttpServer) -> Result<(), EspError> {
self.next.accept(server)?;
server.handler(self.path, self.method, self.handler)?;
Ok(())
}
}
pub struct EspHttpRequest<'a>(&'a mut httpd_req_t);
impl<'a> RawHandle for EspHttpRequest<'a> {
type Handle = *mut httpd_req_t;
fn handle(&self) -> Self::Handle {
self.0 as *const _ as *mut _
}
}
impl<'a> Io for EspHttpRequest<'a> {
type Error = EspIOError;
}
impl<'a> Read for EspHttpRequest<'a> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
if !buf.is_empty() {
let fd = unsafe { httpd_req_to_sockfd(self.0) };
let len = unsafe { esp_idf_sys::read(fd, buf.as_ptr() as *mut _, buf.len()) };
Ok(len as _)
} else {
Ok(0)
}
}
}
impl<'a> Write for EspHttpRequest<'a> {
fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
if !buf.is_empty() {
let fd = unsafe { httpd_req_to_sockfd(self.0) };
let len = unsafe { esp_idf_sys::write(fd, buf.as_ptr() as *const _, buf.len()) };
Ok(len as _)
} else {
Ok(0)
}
}
fn flush(&mut self) -> Result<(), Self::Error> {
Ok(())
}
}
type EspHttpHeaders = BTreeMap<Uncased<'static>, String>;
pub struct EspHttpConnection<'a> {
request: EspHttpRequest<'a>,
headers: Option<UnsafeCell<EspHttpHeaders>>,
response_headers: Option<Vec<CString>>,
}
impl<'a> EspHttpConnection<'a> {
fn new(raw_req: &'a mut httpd_req_t) -> Self {
Self {
request: EspHttpRequest(raw_req),
headers: Some(UnsafeCell::new(EspHttpHeaders::new())),
response_headers: None,
}
}
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()
}
pub fn method(&self) -> Method {
self.assert_request();
Method::from(Newtype(self.request.0.method as u32))
}
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)
}
pub fn initiate_response<'b>(
&'b mut self,
status: u16,
message: Option<&'b str>,
headers: &'b [(&'b str, &'b 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(())
}
pub fn is_response_initiated(&self) -> bool {
self.headers.is_none()
}
pub fn read(&mut self, buf: &mut [u8]) -> Result<usize, EspError> {
self.assert_request();
unsafe {
let len = httpd_req_recv(self.request.0, buf.as_mut_ptr() as *mut _, buf.len());
if len < 0 {
esp!(len)?;
}
Ok(len as usize)
}
}
pub fn write(&mut self, buf: &[u8]) -> Result<usize, EspError> {
self.assert_response();
if !buf.is_empty() {
esp!(unsafe {
httpd_resp_send_chunk(self.request.0, buf.as_ptr().cast(), buf.len() as isize)
})?;
self.response_headers = None;
}
Ok(buf.len())
}
pub fn flush(&mut self) -> Result<(), EspError> {
self.assert_response();
Ok(())
}
pub fn raw_connection(&mut self) -> Result<&mut EspHttpRequest<'a>, EspError> {
Ok(&mut self.request)
}
fn handle<'b, H>(&'b mut self, handler: &'b H) -> Result<(), HandlerError>
where
H: Handler<Self>,
{
// TODO info!("About to handle query string {:?}", self.query_string());
handler.handle(self)?;
Ok(())
}
fn complete(&mut self) -> Result<(), HandlerError> {
let buf = &[];
if self.response_headers.is_some() {
esp!(unsafe { httpd_resp_send(self.request.0, buf.as_ptr() as *const _, 0) })?;
} else {
esp!(unsafe { httpd_resp_send_chunk(self.request.0, buf.as_ptr() as *const _, 0) })?;
}
self.response_headers = None;
Ok(())
}
fn handle_error<E>(&mut self, error: E)
where
E: Display,
{
if self.headers.is_some() {
info!(
"About to handle internal error [{}], response not sent yet",
&error
);
if let Err(error2) = self.render_error(&error) {
warn!(
"Internal error[{}] while rendering another internal error:\n{}",
error2, error
);
}
} else {
warn!(
"Unhandled internal error [{}], response is already sent",
error
);
}
}
fn render_error<E>(&mut self, error: E) -> Result<(), EspIOError>
where
E: Display,
{
self.initiate_response(500, Some("Internal Error"), &[content_type("text/html")])?;
self.write_all(
format!(
r#"
<!DOCTYPE html5>
<html>
<body style="font-family: Verdana, Sans;">
<h1>INTERNAL ERROR</h1>
<hr>
<pre>{error}</pre>
<body>
</html>
"#
)
.as_bytes(),
)?;
Ok(())
}
fn assert_request(&self) {
if self.headers.is_none() {
panic!("connection is not in request phase");
}
}
fn assert_response(&self) {
if self.headers.is_some() {
panic!("connection is not in response phase");
}
}
}
impl<'a> RawHandle for EspHttpConnection<'a> {
type Handle = *mut httpd_req_t;
fn handle(&self) -> Self::Handle {
self.request.handle()
}
}
impl<'a> Query for EspHttpConnection<'a> {
fn uri(&self) -> &str {
EspHttpConnection::uri(self)
}
fn method(&self) -> Method {
EspHttpConnection::method(self)
}
}
impl<'a> Headers for EspHttpConnection<'a> {
fn header(&self, name: &str) -> Option<&str> {
EspHttpConnection::header(self, name)
}
}
impl<'a> Io for EspHttpConnection<'a> {
type Error = EspIOError;
}
impl<'a> Read for EspHttpConnection<'a> {
fn read(&mut self, buf: &mut [u8]) -> Result<usize, Self::Error> {
EspHttpConnection::read(self, buf).map_err(EspIOError)
}
}
impl<'a> Write for EspHttpConnection<'a> {
fn write(&mut self, buf: &[u8]) -> Result<usize, Self::Error> {
EspHttpConnection::write(self, buf).map_err(EspIOError)
}
fn flush(&mut self) -> Result<(), Self::Error> {
EspHttpConnection::flush(self).map_err(EspIOError)
}
}
impl<'b> Connection for EspHttpConnection<'b> {
type Headers = Self;
type Read = Self;
type RawConnectionError = EspIOError;
type RawConnection = EspHttpRequest<'b>;
fn split(&mut self) -> (&Self::Headers, &mut Self::Read) {
EspHttpConnection::split(self)
}
fn initiate_response<'a>(
&'a mut self,
status: u16,
message: Option<&'a str>,
headers: &'a [(&'a str, &'a str)],
) -> Result<(), Self::Error> {
EspHttpConnection::initiate_response(self, status, message, headers).map_err(EspIOError)
}
fn is_response_initiated(&self) -> bool {
EspHttpConnection::is_response_initiated(self)
}
fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error> {
EspHttpConnection::raw_connection(self).map_err(EspIOError)
}
}
#[cfg(esp_idf_httpd_ws_support)]
pub mod ws {
use core::ffi;
use core::fmt::Debug;
use core::sync::atomic::{AtomicBool, Ordering};
extern crate alloc;
use alloc::boxed::Box;
use alloc::sync::Arc;
use ::log::*;
use embedded_svc::http::Method;
use embedded_svc::utils::mutex::{Condvar, Mutex};
use embedded_svc::ws::callback_server::*;
use esp_idf_sys::*;
use crate::private::common::Newtype;
use crate::private::cstr::to_cstring_arg;
use crate::private::mutex::{RawCondvar, RawMutex};
use super::EspHttpServer;
use super::CLOSE_HANDLERS;
use super::OPEN_SESSIONS;
use super::{CloseHandler, NativeHandler};
pub use asyncify::*;
pub enum EspHttpWsConnection {
New(httpd_handle_t, *mut httpd_req_t),
Receiving(httpd_handle_t, *mut httpd_req_t, Option<httpd_ws_frame_t>),
Closed(ffi::c_int),
}
impl EspHttpWsConnection {
pub fn session(&self) -> i32 {
match self {
Self::New(_, raw_req) | Self::Receiving(_, raw_req, _) => unsafe {
httpd_req_to_sockfd(*raw_req)
},
Self::Closed(fd) => *fd,
}
}
pub fn is_new(&self) -> bool {
matches!(self, Self::New(_, _))
}
pub fn is_closed(&self) -> bool {
matches!(self, Self::Closed(_))
}
pub fn create_detached_sender(&self) -> Result<EspHttpWsDetachedSender, EspError> {
match self {
Self::New(sd, raw_req) | Self::Receiving(sd, raw_req, _) => {
let fd = unsafe { httpd_req_to_sockfd(*raw_req) };
let mut sessions = OPEN_SESSIONS.lock();
let closed = sessions
.entry((*sd as u32, fd))
.or_insert_with(|| Arc::new(AtomicBool::new(false)));
Ok(EspHttpWsDetachedSender::new(*sd, fd, closed.clone()))
}
Self::Closed(_) => Err(EspError::from_infallible::<ESP_FAIL>()),
}
}
pub fn send(&mut self, frame_type: FrameType, frame_data: &[u8]) -> Result<(), EspError> {
match self {
Self::New(_, raw_req) | Self::Receiving(_, raw_req, _) => {
let raw_frame = Self::create_raw_frame(frame_type, frame_data);
esp!(unsafe {
httpd_ws_send_frame(*raw_req, &raw_frame as *const _ as *mut _)
})?;
Ok(())
}
_ => Err(EspError::from_infallible::<ESP_FAIL>()),
}
}
pub fn recv(&mut self, frame_data_buf: &mut [u8]) -> Result<(FrameType, usize), EspError> {
match self {
Self::New(_, _) => Err(EspError::from_infallible::<ESP_FAIL>()),
Self::Receiving(_, raw_req, ref mut raw_frame_mut) => {
let raw_frame = loop {
if let Some(raw_frame) = raw_frame_mut.as_mut() {
break raw_frame;
}
let mut raw_frame: httpd_ws_frame_t = Default::default();
esp!(unsafe {
httpd_ws_recv_frame(*raw_req, &mut raw_frame as *mut _, 0)
})?;
// This is necessary because the ESP IDF WS API requires us to
// call it exactly once with a frame that has a zero-sized buffer,
// and then also exactly once with the same frame instance, except
// its buffer set to a non-zero size
//
// On the other hand, we would like to allow the user the freedom