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
use crate::app::backend::windows::Window;
use crate::app::backend::worker;
use crate::app::mods::filter_cat::FilterCat;
use crate::app::mods::inspector;
use crate::app::mods::pathways::new_tree_from_uri;
use crate::app::mods::pathways::Paths;
use crate::app::mods::websockets::WebSocketViewer;
use crate::{app::backend::dbutils, tbl_dyn_col_v2};
use egui_extras::{Column, TableBuilder};
use poll_promise::Promise;
use std::fmt::Display;
use std::ops::Range;
use std::sync::mpsc;
use std::thread;
use crate::{filter, paginate, row, tbl_dyn_col};
use super::inspector::code_view_ui;
use super::inspectors::Inspectors;
use super::notes::Notes;
#[derive(PartialEq, Clone)]
pub enum View {
History,
Inspectors,
Websockets,
Notes,
Sitemap,
}
impl View {
fn possibilities() -> &'static [Self] {
&[
Self::History,
Self::Inspectors,
Self::Websockets,
Self::Notes,
Self::Sitemap,
]
}
fn display(&self, ui: &mut egui::Ui, is_active: bool) -> egui::Response {
ui.selectable_label(is_active, self.to_string())
}
}
impl Display for View {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::History => write!(f, "☰ History"),
Self::Inspectors => write!(f, "☰ Inspectors"),
Self::Websockets => write!(f, "☰ Websockets"),
Self::Notes => write!(f, "☰ Notes"),
Self::Sitemap => write!(f, "☰ Sitemap"),
}
}
}
#[derive(Clone)]
pub enum Selected {
Inspector(dbutils::Inspectors),
Histline(dbutils::HistLine),
Websockets(WebSocketViewer),
Note(dbutils::Note, bool),
}
#[derive(PartialEq, Clone, serde::Deserialize, serde::Serialize)]
pub enum Fields {
Selector,
Id,
SourceIp,
Path,
TargetHost,
ResponseSize,
HttpCode,
Tta,
Method,
Timestamp,
RequestSize,
ContentLength,
}
impl Fields {
fn display(&self, ui: &mut egui::Ui, is_active: bool) -> egui::Response {
ui.button(format!("{} {}", self, if is_active { "☑" } else { "☐" }))
}
fn possibilities() -> &'static [Self] {
&[
Self::Id,
Self::SourceIp,
Self::Path,
Self::TargetHost,
Self::ResponseSize,
Self::HttpCode,
Self::Tta,
Self::Method,
Self::Timestamp,
Self::RequestSize,
Self::ContentLength,
]
}
}
impl Display for Fields {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Selector => write!(f, " "),
Self::Id => write!(f, "Id"),
Self::SourceIp => write!(f, "Ip source"),
Self::Path => write!(f, "Path"),
Self::TargetHost => write!(f, "Target"),
Self::ResponseSize => write!(f, "Response size"),
Self::HttpCode => write!(f, "Status Code"),
Self::Tta => write!(f, "TTA"),
Self::Method => write!(f, "Method"),
Self::Timestamp => write!(f, "Timestamp"),
Self::RequestSize => write!(f, "Request size"),
Self::ContentLength => write!(f, "Content-Length"),
}
}
}
#[derive(serde::Deserialize, serde::Serialize)]
#[serde(default)] // if we add new fields, give them default values when deserializing old state
pub struct History {
last_id: usize,
history: Vec<dbutils::HistLine>,
#[serde(skip)]
pub inspectors: Inspectors,
#[serde(skip)]
pub active_view: View,
#[serde(skip)]
current_top_id: usize,
pub current_page: usize,
pub items_per_page: usize,
pub filter: Option<String>,
pub filter_input: String,
#[serde(skip)]
pub filter_cat: Option<FilterCat>,
#[serde(skip)]
pub selected: Option<Selected>,
#[serde(skip)]
pub response_promise: Option<Promise<Result<String, reqwest::Error>>>,
#[serde(skip)]
pub inspectors_promise: Option<Promise<Result<String, reqwest::Error>>>,
#[serde(skip)]
pub is_minimized: bool,
#[serde(skip)]
pub websockets: Vec<WebSocketViewer>,
#[serde(skip)]
pub websockets_promise: Option<Promise<Result<String, reqwest::Error>>>,
#[serde(skip)]
pub last_websocket_id: usize,
#[serde(skip)]
pub last_seen_idx: usize,
#[serde(skip)]
pub last_seen_idx_filtered: usize,
pub fields: Vec<Fields>,
#[serde(skip)]
pub notes: Notes,
//pub notes: Vec<dbutils::Note>,
#[serde(skip)]
pub notes_promise: Option<Promise<Result<String, reqwest::Error>>>,
pub last_note_id: usize,
#[serde(skip)]
pub paths: Paths,
#[serde(skip)]
pub had_errors: bool,
#[serde(skip)]
pub preview_id: usize,
#[serde(skip)]
pub worker_rx: Option<mpsc::Receiver<worker::TaskResult>>,
#[serde(skip)]
pub proxy_addr: Option<String>,
pub proxy_port: Option<usize>,
}
impl Default for History {
fn default() -> Self {
Self {
last_id: 0,
history: vec![],
inspectors: Inspectors::default(),
worker_rx: None,
current_top_id: 0,
current_page: 0,
items_per_page: 20,
active_view: View::History,
filter: None,
filter_input: String::new(),
response_promise: None,
inspectors_promise: None,
websockets_promise: None,
selected: None,
filter_cat: None,
is_minimized: false,
websockets: vec![],
last_websocket_id: 0,
notes: Notes::default(),
last_note_id: 0,
notes_promise: None,
fields: vec![
Fields::Selector,
Fields::Id,
Fields::TargetHost,
Fields::Method,
Fields::Path,
Fields::ResponseSize,
Fields::RequestSize,
Fields::HttpCode,
],
paths: Paths::new(),
had_errors: false,
last_seen_idx: 0,
last_seen_idx_filtered: 0,
preview_id: 0,
proxy_addr: None,
proxy_port: None,
}
}
}
impl History {
pub fn new(
api_url: &str,
api_addr: &str,
api_port: usize,
proxy_addr: &str,
proxy_port: usize,
api_secret: &str,
) -> Self {
let (tx, worker_rx) = mpsc::channel::<worker::TaskResult>();
let api_url = api_url.to_string();
let api_secret_t = api_secret.to_string();
thread::spawn(move || {
let mut w = worker::Worker::new(tx, api_url, api_secret_t);
w.run();
});
Self {
proxy_addr: Some(proxy_addr.to_string()),
proxy_port: Some(proxy_port),
worker_rx: Some(worker_rx),
inspectors: Inspectors::new(
Some(api_addr.to_string()),
Some(api_port),
Some(api_secret.to_string()),
),
notes: Notes::new(
Some(api_addr.to_string()),
Some(api_port),
Some(api_secret.to_string()),
),
..Default::default()
}
}
pub fn selected(&self) -> Option<Selected> {
self.selected.clone()
}
pub fn set_last_id(&mut self, id: usize) {
self.last_id = id;
}
pub fn history_mut(&mut self) -> &mut Vec<dbutils::HistLine> {
&mut self.history
}
pub fn history(&self) -> &Vec<dbutils::HistLine> {
&self.history
}
pub fn websockets_mut(&mut self) -> &mut Vec<WebSocketViewer> {
&mut self.websockets
}
pub fn _websockets(&self) -> &Vec<WebSocketViewer> {
&self.websockets
}
pub fn get_currently_selected(&self) -> Option<&dbutils::HistLine> {
let mut iter_no_filter;
let mut iter_with_filter;
let items: &mut dyn Iterator<Item = (usize, &dbutils::HistLine)> =
if self.filter_cat.is_some() && self.filter.is_some() {
iter_with_filter = self
.history()
.iter()
.filter(|item| filter!(item, &self.filter, &self.filter_cat))
.enumerate()
.skip(self.last_seen_idx_filtered + self.preview_id)
.take(1);
&mut iter_with_filter
} else {
iter_no_filter = self
.history()
.iter()
.enumerate()
.skip(self.last_seen_idx + self.preview_id)
.take(1);
&mut iter_no_filter
};
if let Some((_, item)) = items.next() {
Some(item)
} else {
None
}
}
pub fn preview_ui(&mut self, ui: &mut egui::Ui) {
let mut iter_no_filter;
let mut iter_with_filter;
let items: &mut dyn Iterator<Item = (usize, &dbutils::HistLine)> =
if self.filter_cat.is_some() && self.filter.is_some() {
iter_with_filter = self
.history()
.iter()
.filter(|item| filter!(item, &self.filter, &self.filter_cat))
.enumerate()
.skip(self.last_seen_idx_filtered + self.preview_id)
.take(1);
&mut iter_with_filter
} else {
iter_no_filter = self
.history()
.iter()
.enumerate()
.skip(self.last_seen_idx + self.preview_id)
.take(1);
&mut iter_no_filter
};
if let Some((_, item)) = items.next() {
let text_style = egui::TextStyle::Body;
let row_height = ui.text_style_height(&text_style);
ui.horizontal_wrapped(|ui| {
ui.columns(2, |uis| {
let requests_lines = item.raw().split("\r\n").collect::<Vec<&str>>();
let responses_lines = item.response().split("\r\n").collect::<Vec<&str>>();
egui::ScrollArea::vertical()
.id_source("preview_request")
.min_scrolled_height(row_height * 30.0)
.show_rows(
&mut uis[0],
row_height,
requests_lines.len(),
|ui, row_range| {
let mut full_request = String::new();
for idx in row_range {
if let Some(data) = requests_lines.get(idx) {
if data.len() < 1_500 {
full_request += &format!("{}\r\n", data);
} else {
full_request += &format!("{}\r\n", &data[..1_500]);
}
}
}
code_view_ui(ui, &full_request);
},
);
egui::ScrollArea::vertical()
.id_source("preview_response")
.min_scrolled_height(row_height * 30.0)
.show_rows(
&mut uis[1],
row_height,
responses_lines.len(),
|ui, row_range| {
let mut full_response = String::new();
for idx in row_range {
if let Some(data) = responses_lines.get(idx) {
full_response += &format!("{}\r\n", data);
}
}
code_view_ui(ui, &full_response);
},
);
});
});
}
}
pub fn display(&mut self, ui: &mut egui::Ui, w: &mut Window) {
ui.vertical(|ui| {
egui::menu::bar(ui, |ui| {
for view in View::possibilities() {
let is_active = &self.active_view == view;
if view.display(ui, is_active).clicked() {
self.active_view = view.clone();
}
ui.separator();
}
ui.with_layout(egui::Layout::top_down(egui::Align::RIGHT), |ui| {
ui.horizontal(|ui| {
if ui.button("x").clicked() {
w.is_active = false;
ui.ctx().request_repaint();
}
ui.separator();
let bt = if self.is_minimized { "+" } else { "-" };
if ui.button(bt).clicked() {
self.is_minimized = !self.is_minimized;
ui.ctx().request_repaint();
}
ui.separator();
if self.active_view == View::History {
ui.menu_button("Fields ⏷", |ui| {
for field in Fields::possibilities() {
let is_active = self.fields.contains(field);
if field.display(ui, is_active).clicked() {
if is_active {
self.fields.retain(|x| x != field);
} else {
self.fields.push(field.clone());
}
}
ui.separator();
}
});
}
if self.active_view == View::History {
ui.menu_button("Hosts ⏷", |ui| {
let mut hosts = vec![];
for x in self.history().iter() {
if !(hosts.contains(x.host())) {
hosts.push(x.host().to_owned());
}
}
for (idx, host) in hosts.iter().enumerate() {
if ui.button(host).clicked() {
self.filter = Some(host.to_owned());
self.filter_input = host.to_owned();
self.filter_cat = Some(FilterCat::Host);
}
if idx != (hosts.len() - 1) {
ui.separator();
}
}
});
ui.separator();
}
if self.active_view == View::Notes {
if ui.button("Add new").clicked() {
w.clicked = true;
self.selected =
Some(Selected::Note(dbutils::Note::default(), true));
}
ui.separator();
}
});
});
});
ui.separator();
if !self.is_minimized {
let mut data_to_append = vec![];
let mut inspectors_to_append = vec![];
let mut websockets_to_append = vec![];
if w.is_remote {
if let Ok(tr) = self.worker_rx.as_ref().unwrap().try_recv() {
match tr {
worker::TaskResult::Histories(vres, last_id) => {
for row in vres {
let full_uri = format!(
"{}/{}/{}",
if row.ssl() { "https" } else { "http" },
row.host(),
row.uri()
);
let partial_tree = new_tree_from_uri(&full_uri);
self.paths.merge(partial_tree);
data_to_append.push(row);
}
self.set_last_id(last_id);
}
worker::TaskResult::Inspectors(vres, _last_id) => {
inspectors_to_append.extend_from_slice(&vres);
}
worker::TaskResult::Notes(vres, last_id) => {
self.last_note_id = last_id;
self.notes.extend_from_slice(&vres);
}
worker::TaskResult::Websockets(vres, last_id) => {
self.last_websocket_id = last_id;
for row in vres {
let mut found = false;
for ws in self.websockets_mut() {
if ws.stream_rep == row.stream_rep {
ws.messages.push(row.clone());
found = true;
}
}
if !found {
websockets_to_append.push(row);
}
}
}
}
}
} else {
todo!();
}
for h in data_to_append {
self.history_mut().insert(0, h.clone());
}
for i in inspectors_to_append {
self.inspectors
.add_inspector(inspector::Inspector::from_inspector(
&i,
&self.proxy_addr,
&self.proxy_port,
));
}
for w in websockets_to_append {
if let Some(ws) = self
.websockets_mut()
.iter_mut()
.find(|ws| ws.stream_rep == w.stream_rep)
{
ws.messages.push(w);
} else {
self.websockets_mut().insert(
0,
WebSocketViewer {
id: w.id,
stream_rep: w.stream_rep.to_string(),
ssl: w.ssl,
is_minimized: false,
messages: vec![w.clone()],
},
)
}
}
let text_height = egui::TextStyle::Body.resolve(ui.style()).size;
let mut len = self.history().len();
let mut last_seen_idx: usize = self.last_seen_idx;
let mut last_seen_idx_filtered: usize = self.last_seen_idx_filtered;
ui.scope(|ui| {
ui.style_mut().override_text_style = Some(egui::TextStyle::Monospace);
match self.active_view {
View::History => {
tbl_dyn_col_v2!(
ui,
|body| {
let mut selected: Option<dbutils::HistLine> = None;
let mut iter_no_filter;
let mut iter_with_filter;
let items: &mut dyn Iterator<
Item = (usize, &dbutils::HistLine),
> = if self.filter_cat.is_some() && self.filter.is_some() {
iter_with_filter = self
.history()
.iter()
.filter(|item| {
filter!(item, &self.filter, &self.filter_cat)
})
.enumerate()
.skip(last_seen_idx_filtered)
.take(self.items_per_page);
&mut iter_with_filter
} else {
iter_no_filter = self
.history()
.iter()
.enumerate()
.skip(last_seen_idx)
.take(self.items_per_page);
&mut iter_no_filter
};
body.rows(text_height, self.items_per_page, |mut tblrow| {
if let Some((idx, item)) = items.next().as_ref() {
if tblrow.index() == 0 {
if self.filter.is_some() {
last_seen_idx_filtered = *idx;
} else {
last_seen_idx = *idx;
}
}
tblrow.set_selected(*idx
== last_seen_idx_filtered + self.preview_id
|| *idx == last_seen_idx + self.preview_id);
row!(
tblrow,
{
selected = Some(
dbutils::HistLine::from_histline_ref(*item),
);
},
(
item.id().to_string(),
self.fields.contains(&Fields::Id)
),
(
item.host().to_owned(),
self.fields.contains(&Fields::TargetHost)
),
(
item.remote_addr().to_string(),
self.fields.contains(&Fields::SourceIp)
),
(
item.method().to_owned(),
self.fields.contains(&Fields::Method)
),
(
item.content_length().to_string(),
self.fields.contains(&Fields::ContentLength)
),
(
item.raw().len().to_string(),
self.fields.contains(&Fields::RequestSize)
),
(
item.response().len().to_string(),
self.fields.contains(&Fields::ResponseSize)
),
(
item.status().to_string(),
self.fields.contains(&Fields::HttpCode)
),
(
item.response_time().to_owned(),
self.fields.contains(&Fields::Tta)
),
(
item.timestamp().to_owned(),
self.fields.contains(&Fields::Timestamp)
),
(
item.uri().to_owned(),
self.fields.contains(&Fields::Path)
)
);
}
});
if selected.is_some() {
self.inspectors.add_inspector(
inspector::Inspector::from_histline(
&selected.unwrap(),
&self.proxy_addr,
&self.proxy_port,
),
);
self.active_view = View::Inspectors;
}
},
last_seen_idx,
last_seen_idx_filtered,
self.items_per_page,
len,
self.filter,
self.filter_cat,
&mut self.filter_input,
(
Column::initial(50.0),
self.fields.contains(&Fields::Id),
Fields::Id.to_string()
),
(
Column::initial(120.0).clip(true),
self.fields.contains(&Fields::TargetHost),
Fields::TargetHost.to_string()
),
(
Column::initial(10.0).clip(true),
self.fields.contains(&Fields::SourceIp),
Fields::SourceIp.to_string()
),
(
Column::initial(80.0),
self.fields.contains(&Fields::Method),
Fields::Method.to_string()
),
(
Column::initial(90.0),
self.fields.contains(&Fields::ContentLength),
Fields::ContentLength.to_string()
),
(
Column::initial(90.0),
self.fields.contains(&Fields::RequestSize),
Fields::RequestSize.to_string()
),
(
Column::initial(60.0),
self.fields.contains(&Fields::ResponseSize),
Fields::ResponseSize.to_string()
),
(
Column::initial(70.0),
self.fields.contains(&Fields::HttpCode),
Fields::HttpCode.to_string()
),
(
Column::initial(90.0),
self.fields.contains(&Fields::Tta),
Fields::Tta.to_string()
),
(
Column::initial(180.0),
self.fields.contains(&Fields::Timestamp),
Fields::Timestamp.to_string()
),
(
Column::remainder().clip(true),
self.fields.contains(&Fields::Path),
Fields::Path.to_string()
)
);
if last_seen_idx != self.last_seen_idx {
self.last_seen_idx = last_seen_idx;
}
if last_seen_idx_filtered != self.last_seen_idx_filtered {
self.last_seen_idx_filtered = last_seen_idx_filtered;
}
}
View::Sitemap => {
self.paths.sort();
egui::ScrollArea::both()
.id_source("Sitemap")
.show(ui, |ui| {
ui.set_width(ui.available_width());
self.paths.ui(ui);
});
}
View::Inspectors => {
self.inspectors.display(ui);
}
View::Websockets => {
let mut curr = 0;
tbl_dyn_col!(
ui,
|mut body| {
let mut selected = None;
let filter = None;
let mut insp = vec![];
for h in self.websockets.iter() {
if filter!(h, &self.filter, &filter) {
insp.push(h.clone());
}
}
if len != insp.len() {
len = insp.len();
}
let range = paginate!(curr, self.items_per_page, len);
for item in &insp[range] {
body.row(text_height, |mut row| {
row!(
row,
{
selected = Some(item.clone());
},
(item.stream_rep.to_string(), true),
(item.ssl.to_string(), true),
(item.messages.len().to_string(), true)
);
})
}
if selected.is_some() {
w.clicked = true;
self.selected =
Some(Selected::Websockets(selected.unwrap()));
}
},
curr,
self.items_per_page,
len,
self.filter,
self.filter_cat,
&mut self.filter_input,
(Column::exact(40.0), true),
(Column::exact(120.0), true),
(Column::exact(120.0), true)
);
}
View::Notes => {
self.notes.display(ui);
}
}
});
}
});
}
}