Repository navigation
Expand file tree
/
Copy pathMainForm.cs
More file actions
892 lines (802 loc) · 36.9 KB
/
Copy pathMainForm.cs
File metadata and controls
892 lines (802 loc) · 36.9 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
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace wordlist2sql
{
public sealed class MainForm : Form
{
private WordlistDb _db;
private ExportServer _server;
private string _serverBaseText = "";
private CancellationTokenSource _cts;
// --- Controls ---
private TextBox _dbPathBox;
private Button _openDbBtn;
private ListView _tablesView;
private Button _refreshBtn;
private Button _renameBtn;
private Button _dropBtn;
private Button _importBtn;
private CheckBox _dedupeChk;
private Button _importBlobsBtn;
private Button _exportBtn;
private TextBox _searchBox;
private CheckBox _revealChk;
private CheckBox _ignoreCaseChk;
private CheckBox _partialChk;
private Button _searchBtn;
private Label _searchResult;
private NumericUpDown _portBox;
private CheckBox _lanChk;
private Button _serverBtn;
private Button _lanSetupBtn;
private Label _serverStatus;
private TextBox _logBox;
private ProgressBar _progress;
private Label _statusLabel;
private Button _cancelBtn;
public MainForm()
{
Text = "wordlist2sql";
ClientSize = new Size(900, 620);
MinimumSize = new Size(760, 560);
Font = new Font("Segoe UI", 9f);
LoadAppIcon();
BuildUi();
UpdateEnabled();
}
private void LoadAppIcon()
{
try
{
var asm = System.Reflection.Assembly.GetExecutingAssembly();
using (var st = asm.GetManifestResourceStream("wordlist2sql.app.ico"))
{
if (st != null)
Icon = new Icon(st);
}
}
catch { /* fall back to default icon */ }
}
// ---------------------------------------------------------------- UI
private void BuildUi()
{
// ---- Database row ----
var dbGroup = new GroupBox { Text = "Database", Dock = DockStyle.Top, Height = 64, Padding = new Padding(10) };
_dbPathBox = new TextBox { ReadOnly = true, Dock = DockStyle.Fill, Text = "(no database open)" };
_openDbBtn = new Button { Text = "Open / Create…", Dock = DockStyle.Right, Width = 130 };
_openDbBtn.Click += OnOpenDb;
var dbInner = new Panel { Dock = DockStyle.Fill };
dbInner.Controls.Add(_dbPathBox);
dbInner.Controls.Add(_openDbBtn);
dbGroup.Controls.Add(dbInner);
// ---- Tables list ----
var tablesGroup = new GroupBox { Text = "Tables", Dock = DockStyle.Fill, Padding = new Padding(10) };
_tablesView = new ListView
{
Dock = DockStyle.Fill,
View = View.Details,
FullRowSelect = true,
MultiSelect = false,
HideSelection = false,
};
_tablesView.Columns.Add("Table", 180);
_tablesView.Columns.Add("Kind", 55);
_tablesView.Columns.Add("Rows", 100, HorizontalAlignment.Right);
_tablesView.Columns.Add("Unique", 60);
_tablesView.Columns.Add("Source", 240);
_tablesView.Columns.Add("Imported (UTC)", 160);
_tablesView.SelectedIndexChanged += (s, e) => UpdateEnabled();
var tablesButtons = new FlowLayoutPanel { Dock = DockStyle.Bottom, Height = 40, FlowDirection = FlowDirection.LeftToRight };
_refreshBtn = new Button { Text = "Refresh", Width = 90 };
_refreshBtn.Click += (s, e) => RefreshTables();
_renameBtn = new Button { Text = "Rename…", Width = 90 };
_renameBtn.Click += OnRenameTable;
_dropBtn = new Button { Text = "Drop table", Width = 100 };
_dropBtn.Click += OnDropTable;
_exportBtn = new Button { Text = "Export to file…", Width = 130 };
_exportBtn.Click += OnExport;
tablesButtons.Controls.Add(_refreshBtn);
tablesButtons.Controls.Add(_renameBtn);
tablesButtons.Controls.Add(_dropBtn);
tablesButtons.Controls.Add(_exportBtn);
tablesGroup.Controls.Add(_tablesView);
tablesGroup.Controls.Add(tablesButtons);
// ---- Import controls ----
var importGroup = new GroupBox { Text = "Import", Dock = DockStyle.Top, Height = 72, Padding = new Padding(10) };
var importInner = new FlowLayoutPanel { Dock = DockStyle.Fill, FlowDirection = FlowDirection.LeftToRight, WrapContents = false };
_importBtn = new Button { Text = "Import wordlist file(s)…", Width = 180, Height = 30 };
_importBtn.Click += OnImport;
_dedupeChk = new CheckBox { Text = "De-duplicate (unique words only)", AutoSize = true, Margin = new Padding(16, 8, 0, 0) };
_importBlobsBtn = new Button { Text = "Import file(s) as BLOBs…", Width = 175, Height = 30, Margin = new Padding(24, 0, 0, 0) };
_importBlobsBtn.Click += OnImportBlobs;
var importHint = new Label
{
Text = "Wordlists: one table per file. BLOBs: store whole files in one table.",
AutoSize = true,
ForeColor = SystemColors.GrayText,
Margin = new Padding(16, 9, 0, 0)
};
importInner.Controls.Add(_importBtn);
importInner.Controls.Add(_dedupeChk);
importInner.Controls.Add(_importBlobsBtn);
importInner.Controls.Add(importHint);
importGroup.Controls.Add(importInner);
// ---- Search ----
var searchGroup = new GroupBox { Text = "Search", Dock = DockStyle.Top, Height = 64, Padding = new Padding(10) };
var searchInner = new FlowLayoutPanel { Dock = DockStyle.Fill, FlowDirection = FlowDirection.LeftToRight, WrapContents = false };
searchInner.Controls.Add(new Label { Text = "Find word:", AutoSize = true, Margin = new Padding(0, 8, 4, 0) });
_searchBox = new TextBox { Width = 220, UseSystemPasswordChar = true };
_searchBox.KeyDown += (s, e) =>
{
if (e.KeyCode == Keys.Enter) { e.SuppressKeyPress = true; OnSearch(s, e); }
};
_revealChk = new CheckBox { Text = "Show", AutoSize = true, Margin = new Padding(8, 8, 0, 0) };
_revealChk.CheckedChanged += (s, e) => _searchBox.UseSystemPasswordChar = !_revealChk.Checked;
_ignoreCaseChk = new CheckBox { Text = "Ignore case", AutoSize = true, Margin = new Padding(12, 8, 0, 0) };
_partialChk = new CheckBox { Text = "Partial match", AutoSize = true, Margin = new Padding(8, 8, 0, 0) };
_searchBtn = new Button { Text = "Search all tables", Width = 130 };
_searchBtn.Click += OnSearch;
_searchResult = new Label { Text = "", AutoSize = true, Margin = new Padding(14, 8, 0, 0), ForeColor = SystemColors.GrayText };
searchInner.Controls.Add(_searchBox);
searchInner.Controls.Add(_revealChk);
searchInner.Controls.Add(_ignoreCaseChk);
searchInner.Controls.Add(_partialChk);
searchInner.Controls.Add(_searchBtn);
searchInner.Controls.Add(_searchResult);
searchGroup.Controls.Add(searchInner);
// ---- HTTP server ----
var serverGroup = new GroupBox { Text = "Curl / HTTP server", Dock = DockStyle.Bottom, Height = 150, Padding = new Padding(10) };
var serverTop = new FlowLayoutPanel { Dock = DockStyle.Top, Height = 36, FlowDirection = FlowDirection.LeftToRight, WrapContents = false };
serverTop.Controls.Add(new Label { Text = "Port:", AutoSize = true, Margin = new Padding(0, 8, 4, 0) });
_portBox = new NumericUpDown { Minimum = 1, Maximum = 65535, Value = 8088, Width = 80 };
_lanChk = new CheckBox { Text = "Allow LAN access", AutoSize = true, Margin = new Padding(12, 8, 0, 0) };
_serverBtn = new Button { Text = "Start server", Width = 110 };
_serverBtn.Click += OnToggleServer;
_lanSetupBtn = new Button { Text = "Set up LAN access (admin)…", Width = 190 };
_lanSetupBtn.Click += OnSetupLan;
_serverStatus = new Label { Text = "Stopped.", AutoSize = true, Margin = new Padding(12, 8, 0, 0), ForeColor = SystemColors.GrayText };
serverTop.Controls.Add(_portBox);
serverTop.Controls.Add(_lanChk);
serverTop.Controls.Add(_serverBtn);
serverTop.Controls.Add(_lanSetupBtn);
serverTop.Controls.Add(_serverStatus);
_logBox = new TextBox { Dock = DockStyle.Fill, Multiline = true, ReadOnly = true, ScrollBars = ScrollBars.Vertical, BackColor = Color.White, Font = new Font("Consolas", 8.5f) };
serverGroup.Controls.Add(_logBox);
serverGroup.Controls.Add(serverTop);
// ---- Status bar ----
var statusBar = new Panel { Dock = DockStyle.Bottom, Height = 56, Padding = new Padding(10, 6, 10, 6) };
_progress = new ProgressBar { Dock = DockStyle.Top, Height = 18 };
var statusRow = new Panel { Dock = DockStyle.Fill };
_statusLabel = new Label { Dock = DockStyle.Fill, Text = "Ready.", TextAlign = ContentAlignment.MiddleLeft };
_cancelBtn = new Button { Text = "Cancel", Dock = DockStyle.Right, Width = 90, Enabled = false };
_cancelBtn.Click += (s, e) => _cts?.Cancel();
statusRow.Controls.Add(_statusLabel);
statusRow.Controls.Add(_cancelBtn);
statusBar.Controls.Add(statusRow);
statusBar.Controls.Add(_progress);
// Add in z-order: Fill first, then Top groups inner→outer.
Controls.Add(tablesGroup); // Fill
Controls.Add(searchGroup); // Top (just above the table list)
Controls.Add(importGroup); // Top
Controls.Add(dbGroup); // Top
Controls.Add(serverGroup); // Bottom
Controls.Add(statusBar); // Bottom
}
// ----------------------------------------------------------- Helpers
private void Log(string msg)
{
if (InvokeRequired) { BeginInvoke((Action)(() => Log(msg))); return; }
_logBox.AppendText(DateTime.Now.ToString("HH:mm:ss ") + msg + Environment.NewLine);
}
private void SetStatus(string msg)
{
if (InvokeRequired) { BeginInvoke((Action)(() => SetStatus(msg))); return; }
_statusLabel.Text = msg;
}
private bool _busy;
private void SetBusy(bool busy)
{
_busy = busy;
_cancelBtn.Enabled = busy;
UpdateEnabled();
}
private void UpdateEnabled()
{
bool hasDb = _db != null;
bool hasSel = _tablesView != null && _tablesView.SelectedItems.Count > 0;
bool idle = !_busy;
_openDbBtn.Enabled = idle;
_importBtn.Enabled = hasDb && idle;
_importBlobsBtn.Enabled = hasDb && idle;
_refreshBtn.Enabled = hasDb && idle;
_renameBtn.Enabled = hasDb && hasSel && idle;
_dropBtn.Enabled = hasDb && hasSel && idle;
_exportBtn.Enabled = hasDb && hasSel && idle;
// Reflect what export will do for the selected table.
_exportBtn.Text = SelectedIsBlobTable() ? "Export BLOBs…" : "Export to file…";
_serverBtn.Enabled = hasDb;
_dedupeChk.Enabled = hasDb && idle;
_searchBox.Enabled = hasDb && idle;
_searchBtn.Enabled = hasDb && idle;
_ignoreCaseChk.Enabled = hasDb && idle;
_partialChk.Enabled = hasDb && idle;
}
private string SelectedTable()
=> _tablesView.SelectedItems.Count > 0 ? _tablesView.SelectedItems[0].Text : null;
private bool SelectedIsBlobTable()
=> _tablesView != null && _tablesView.SelectedItems.Count > 0
&& (_tablesView.SelectedItems[0].Tag as string) == WordlistDb.KindBlobs;
// -------------------------------------------------------- DB actions
private void OnOpenDb(object sender, EventArgs e)
{
// OpenFileDialog (button reads "Open"); CheckFileExists=false still
// allows typing a new filename to create a database.
using (var dlg = new OpenFileDialog
{
Title = "Open or create a SQLite database",
Filter = "SQLite database (*.db;*.sqlite)|*.db;*.sqlite|All files (*.*)|*.*",
CheckFileExists = false,
CheckPathExists = true,
FileName = "wordlists.db",
})
{
if (dlg.ShowDialog(this) != DialogResult.OK) return;
try
{
StopServerIfRunning();
_db?.Dispose();
_db = WordlistDb.Open(dlg.FileName);
_dbPathBox.Text = dlg.FileName;
SetStatus("Opened " + Path.GetFileName(dlg.FileName));
Log("Opened database: " + dlg.FileName);
RefreshTables();
}
catch (Exception ex)
{
Error("Could not open database", ex);
}
}
UpdateEnabled();
}
private void RefreshTables()
{
if (_db == null) return;
_tablesView.BeginUpdate();
_tablesView.Items.Clear();
try
{
foreach (var t in _db.ListTables())
{
bool blobs = t.Kind == WordlistDb.KindBlobs;
var item = new ListViewItem(t.Name);
item.SubItems.Add(blobs ? "blobs" : "words");
item.SubItems.Add(t.WordCount >= 0 ? t.WordCount.ToString("n0") : "?");
item.SubItems.Add(blobs ? "" : (t.WordCount >= 0 ? (t.Deduped ? "yes" : "no") : ""));
item.SubItems.Add(t.SourceFile ?? "");
item.SubItems.Add(string.IsNullOrEmpty(t.ImportedUtc) ? "" : t.ImportedUtc.Replace("T", " ").Substring(0, Math.Min(19, t.ImportedUtc.Length)));
item.Tag = t.Kind;
_tablesView.Items.Add(item);
}
}
catch (Exception ex)
{
Error("Could not list tables", ex);
}
_tablesView.EndUpdate();
UpdateEnabled();
}
private void OnRenameTable(object sender, EventArgs e)
{
string table = SelectedTable();
if (table == null || _db == null) return;
string input = Prompt("Rename table", $"New name for \"{table}\":", table);
if (input == null) return; // cancelled
try
{
string actual = _db.RenameTable(table, input);
Log($"Renamed table: \"{table}\" → \"{actual}\"");
SetStatus($"Renamed to \"{actual}\".");
RefreshTables();
// Re-select the renamed table for convenience.
foreach (ListViewItem it in _tablesView.Items)
{
if (it.Text == actual) { it.Selected = true; it.EnsureVisible(); break; }
}
}
catch (Exception ex)
{
Error("Could not rename table", ex);
}
}
private void OnDropTable(object sender, EventArgs e)
{
string table = SelectedTable();
if (table == null) return;
if (MessageBox.Show(this, $"Drop table \"{table}\"? This cannot be undone.",
"Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes)
return;
try
{
_db.DropTable(table);
Log("Dropped table: " + table);
RefreshTables();
}
catch (Exception ex)
{
Error("Could not drop table", ex);
}
}
// ---------------------------------------------------------- Import
private async void OnImport(object sender, EventArgs e)
{
if (_db == null) return;
string[] files;
using (var dlg = new OpenFileDialog
{
Title = "Choose wordlist file(s)",
Filter = "Text wordlists (*.txt;*.lst;*.dic;*.words)|*.txt;*.lst;*.dic;*.words|All files (*.*)|*.*",
Multiselect = true,
})
{
if (dlg.ShowDialog(this) != DialogResult.OK) return;
files = dlg.FileNames;
}
bool dedupe = _dedupeChk.Checked;
_cts = new CancellationTokenSource();
SetBusy(true);
try
{
for (int i = 0; i < files.Length; i++)
{
string file = files[i];
string table = WordlistDb.SanitizeTableName(file);
// Prompt only if a name clashes with an existing table.
if (_db.TableExists(table))
{
var ans = MessageBox.Show(this,
$"Table \"{table}\" already exists. Replace it with \"{Path.GetFileName(file)}\"?",
"Table exists", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (ans == DialogResult.Cancel) break;
if (ans == DialogResult.No) continue;
}
int index = i + 1;
SetStatus($"Importing {Path.GetFileName(file)} → \"{table}\" ({index}/{files.Length})…");
Log($"Import start: {file} → \"{table}\" (dedupe={dedupe})");
var progress = new Progress<WordlistDb.ImportProgress>(p =>
{
int pct = p.TotalBytes > 0 ? (int)(p.BytesRead * 100 / p.TotalBytes) : 0;
_progress.Value = Math.Min(100, Math.Max(0, pct));
SetStatus($"\"{table}\" ({index}/{files.Length}): {p.WordsInserted:n0} words, {pct}%");
});
var token = _cts.Token;
var result = await Task.Run(
() => _db.ImportWordlist(file, table, dedupe, progress, token), token);
Log($"Import done: \"{table}\" — {result.WordsInserted:n0} words from {result.LinesRead:n0} lines.");
RefreshTables();
}
SetStatus("Import complete.");
}
catch (OperationCanceledException)
{
SetStatus("Import cancelled.");
Log("Import cancelled by user.");
}
catch (Exception ex)
{
Error("Import failed", ex);
}
finally
{
_progress.Value = 0;
_cts?.Dispose();
_cts = null;
SetBusy(false);
RefreshTables();
}
}
// ---------------------------------------------------------- Import BLOBs
private async void OnImportBlobs(object sender, EventArgs e)
{
if (_db == null) return;
string[] files;
using (var dlg = new OpenFileDialog
{
Title = "Choose file(s) to store as BLOBs",
Filter = "All files (*.*)|*.*",
Multiselect = true,
})
{
if (dlg.ShowDialog(this) != DialogResult.OK) return;
files = dlg.FileNames;
}
string table = WordlistDb.SanitizeTableName(
Prompt("BLOB table", "Store the selected file(s) in table:", "blobs"));
if (table == null) return;
bool append = false;
if (_db.TableExists(table))
{
var ans = MessageBox.Show(this,
$"Table \"{table}\" already exists.\n\n" +
"Yes = add these files to it, No = replace it, Cancel = abort.",
"Table exists", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (ans == DialogResult.Cancel) return;
append = ans == DialogResult.Yes;
}
_cts = new CancellationTokenSource();
SetBusy(true);
try
{
SetStatus($"Importing {files.Length} file(s) as BLOBs → \"{table}\"…");
Log($"BLOB import start: {files.Length} file(s) → \"{table}\" (append={append})");
var progress = new Progress<WordlistDb.BlobProgress>(p =>
{
int pct = p.TotalFiles > 0 ? (int)((long)p.FilesDone * 100 / p.TotalFiles) : 0;
_progress.Value = Math.Min(100, Math.Max(0, pct));
SetStatus($"\"{table}\": {p.FilesDone}/{p.TotalFiles} files, {p.BytesDone:n0} bytes ({p.CurrentFile})");
});
var token = _cts.Token;
int n = await Task.Run(() => _db.ImportBlobs(table, files, append, progress, token), token);
Log($"BLOB import done: \"{table}\" — {n} file(s) stored.");
SetStatus($"Stored {n} file(s) as BLOBs in \"{table}\".");
}
catch (OperationCanceledException)
{
SetStatus("BLOB import cancelled.");
Log("BLOB import cancelled by user.");
}
catch (Exception ex)
{
Error("BLOB import failed", ex);
}
finally
{
_progress.Value = 0;
_cts?.Dispose();
_cts = null;
SetBusy(false);
RefreshTables();
}
}
// ---------------------------------------------------------- Export
private async void OnExport(object sender, EventArgs e)
{
string table = SelectedTable();
if (table == null || _db == null) return;
if (SelectedIsBlobTable())
{
await ExportBlobsAsync(table);
return;
}
string outPath;
using (var dlg = new SaveFileDialog
{
Title = "Export table to text file",
Filter = "Text file (*.txt)|*.txt|All files (*.*)|*.*",
FileName = table + ".txt",
})
{
if (dlg.ShowDialog(this) != DialogResult.OK) return;
outPath = dlg.FileName;
}
_cts = new CancellationTokenSource();
SetBusy(true);
try
{
SetStatus($"Exporting \"{table}\"…");
Log($"Export start: \"{table}\" → {outPath}");
var progress = new Progress<WordlistDb.ExportProgress>(p =>
{
int pct = p.TotalWords > 0 ? (int)(p.WordsWritten * 100 / p.TotalWords) : 0;
_progress.Value = Math.Min(100, Math.Max(0, pct));
SetStatus($"Exporting \"{table}\": {p.WordsWritten:n0} words, {pct}%");
});
var token = _cts.Token;
long written = await Task.Run(
() => _db.ExportTable(table, outPath, progress, token), token);
SetStatus($"Exported {written:n0} words to {Path.GetFileName(outPath)}.");
Log($"Export done: {written:n0} words → {outPath}");
}
catch (OperationCanceledException)
{
SetStatus("Export cancelled.");
Log("Export cancelled by user.");
}
catch (Exception ex)
{
Error("Export failed", ex);
}
finally
{
_progress.Value = 0;
_cts?.Dispose();
_cts = null;
SetBusy(false);
}
}
private async Task ExportBlobsAsync(string table)
{
string folder;
using (var dlg = new FolderBrowserDialog
{
Description = $"Choose a folder to extract the BLOBs of \"{table}\" into",
UseDescriptionForTitle = true,
})
{
if (dlg.ShowDialog(this) != DialogResult.OK) return;
folder = dlg.SelectedPath;
}
_cts = new CancellationTokenSource();
SetBusy(true);
try
{
SetStatus($"Extracting BLOBs from \"{table}\"…");
Log($"BLOB export start: \"{table}\" → {folder}");
var progress = new Progress<WordlistDb.BlobProgress>(p =>
{
int pct = p.TotalFiles > 0 ? (int)((long)p.FilesDone * 100 / p.TotalFiles) : 0;
_progress.Value = Math.Min(100, Math.Max(0, pct));
SetStatus($"Extracting \"{table}\": {p.FilesDone}/{p.TotalFiles} files ({p.CurrentFile})");
});
var token = _cts.Token;
int n = await Task.Run(() => _db.ExportBlobs(table, folder, progress, token), token);
SetStatus($"Extracted {n} file(s) to {folder}.");
Log($"BLOB export done: {n} file(s) → {folder}");
}
catch (OperationCanceledException)
{
SetStatus("BLOB export cancelled.");
Log("BLOB export cancelled by user.");
}
catch (Exception ex)
{
Error("BLOB export failed", ex);
}
finally
{
_progress.Value = 0;
_cts?.Dispose();
_cts = null;
SetBusy(false);
}
}
// ---------------------------------------------------------- Search
private async void OnSearch(object sender, EventArgs e)
{
if (_db == null) return;
// Read and immediately clear the box so the secret isn't left on screen.
string word = _searchBox.Text;
_searchBox.Clear();
if (string.IsNullOrWhiteSpace(word))
{
_searchResult.Text = "Type a word to search for.";
_searchResult.ForeColor = SystemColors.GrayText;
return;
}
bool ignoreCase = _ignoreCaseChk.Checked;
bool partial = _partialChk.Checked;
_cts = new CancellationTokenSource();
SetBusy(true);
_searchResult.Text = "Searching…";
_searchResult.ForeColor = SystemColors.GrayText;
// Note: the searched word is never logged or displayed — only the mode.
string mode = (partial ? "partial" : "exact") + (ignoreCase ? ", ignore case" : ", case-sensitive");
Log($"Search started across all tables ({mode}).");
try
{
// Progress reports the current table name only — not the word.
var progress = new Progress<string>(table => SetStatus($"Searching \"{table}\"…"));
var token = _cts.Token;
var res = await Task.Run(() => _db.SearchWord(word, ignoreCase, partial, progress, token), token);
if (res.TablesContaining.Count == 0)
{
_searchResult.Text = $"Not found in any of {res.TablesSearched} table(s).";
_searchResult.ForeColor = Color.Firebrick;
Log($"Search complete: no match in {res.TablesSearched} table(s).");
ClearTableHighlight();
}
else
{
string list = string.Join(", ", res.TablesContaining);
_searchResult.Text = $"Found in {res.TablesContaining.Count} of {res.TablesSearched}: {list}";
_searchResult.ForeColor = Color.ForestGreen;
Log($"Search complete: found in {res.TablesContaining.Count} table(s): {list}");
HighlightTables(res.TablesContaining);
}
SetStatus("Search complete.");
}
catch (OperationCanceledException)
{
_searchResult.Text = "Search cancelled.";
_searchResult.ForeColor = SystemColors.GrayText;
SetStatus("Search cancelled.");
Log("Search cancelled by user.");
}
catch (Exception ex)
{
Error("Search failed", ex);
}
finally
{
// Scrub the captured secret from memory's reach as best we can.
word = null;
_cts?.Dispose();
_cts = null;
SetBusy(false);
}
}
private void ClearTableHighlight()
{
foreach (ListViewItem it in _tablesView.Items)
it.BackColor = _tablesView.BackColor;
}
private void HighlightTables(System.Collections.Generic.List<string> names)
{
var set = new System.Collections.Generic.HashSet<string>(names, StringComparer.Ordinal);
foreach (ListViewItem it in _tablesView.Items)
it.BackColor = set.Contains(it.Text) ? Color.FromArgb(216, 244, 216) : _tablesView.BackColor;
}
// ---------------------------------------------------------- Server
private void OnToggleServer(object sender, EventArgs e)
{
if (_server != null) { StopServerIfRunning(); return; }
if (_db == null) return;
try
{
int port = (int)_portBox.Value;
bool lan = _lanChk.Checked;
_server = new ExportServer(_db.DatabasePath, port, lan);
_server.Log += Log;
_serverBaseText = (lan ? "LAN" : "Local") + $" — running at {_server.BaseUrl}";
_server.ConnectionsChanged += OnConnectionsChanged;
_server.Start();
_serverBtn.Text = "Stop server";
_serverStatus.Text = _serverBaseText + " · 0 active";
_serverStatus.ForeColor = Color.ForestGreen;
_portBox.Enabled = false;
_lanChk.Enabled = false;
Log($"Try: curl {_server.BaseUrl}{(SelectedTable() ?? "<table>")} -o out.txt");
}
catch (Exception ex)
{
_server = null;
Error("Could not start server", ex);
}
}
/// <summary>
/// One-time elevated setup so LAN binding works without running the
/// whole app as admin: reserve the URL ACL and open the firewall port.
/// Triggers a single UAC prompt.
/// </summary>
private void OnSetupLan(object sender, EventArgs e)
{
int port = (int)_portBox.Value;
if (MessageBox.Show(this,
$"This will (as Administrator) allow LAN access on port {port}:\r\n\r\n" +
$" • Reserve URL http://+:{port}/ (so the app can bind without admin)\r\n" +
$" • Add an inbound firewall rule for TCP {port} (Private network)\r\n\r\n" +
"Windows will show a UAC prompt. Continue?",
"Set up LAN access", MessageBoxButtons.OKCancel, MessageBoxIcon.Information)
!= DialogResult.OK)
return;
// Build both commands; '&' so the firewall rule is still added even
// if the URL ACL already exists. /c keeps the window only as long as
// needed; we read the exit code to report success.
string cmd =
$"netsh http add urlacl url=http://+:{port}/ user=Everyone & " +
$"netsh advfirewall firewall add rule name=\"wordlist2sql {port}\" " +
$"dir=in action=allow protocol=TCP localport={port} profile=private";
try
{
var psi = new ProcessStartInfo("cmd.exe", "/c " + cmd)
{
UseShellExecute = true, // required for Verb=runas
Verb = "runas", // elevate (UAC)
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
};
using (var p = Process.Start(psi))
{
p.WaitForExit();
if (p.ExitCode == 0)
{
Log($"LAN setup applied for port {port} (URL ACL + firewall rule).");
SetStatus("LAN access configured. Tick 'Allow LAN access' and start the server.");
MessageBox.Show(this,
$"LAN access is set up for port {port}.\r\n\r\n" +
"Now tick \"Allow LAN access\" and click Start server.",
"Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
_lanChk.Checked = true;
}
else
{
Log($"LAN setup finished with exit code {p.ExitCode} (a rule/ACL may already exist).");
SetStatus("LAN setup ran; check the log.");
}
}
}
catch (Win32Exception ex) when (ex.NativeErrorCode == 1223) // ERROR_CANCELLED
{
Log("LAN setup cancelled at the UAC prompt.");
SetStatus("LAN setup cancelled.");
}
catch (Exception ex)
{
Error("LAN setup failed", ex);
}
}
private void StopServerIfRunning()
{
if (_server == null) return;
try { _server.ConnectionsChanged -= OnConnectionsChanged; } catch { }
try { _server.Stop(); } catch { }
_server = null;
_serverBtn.Text = "Start server";
_serverStatus.Text = "Stopped.";
_serverStatus.ForeColor = SystemColors.GrayText;
_portBox.Enabled = true;
_lanChk.Enabled = true;
}
// Live connection count from the server (fires on a pool thread).
private void OnConnectionsChanged(int active, long total, long peak)
{
if (IsDisposed) return;
if (InvokeRequired)
{
try { BeginInvoke((Action)(() => OnConnectionsChanged(active, total, peak))); } catch { }
return;
}
if (_server == null) return;
_serverStatus.Text =
$"{_serverBaseText} · {active} active (peak {peak}, {total:n0} served)";
}
// ------------------------------------------------------------- misc
/// <summary>Simple modal text-input dialog. Returns null if cancelled.</summary>
private string Prompt(string title, string label, string initial)
{
using (var dlg = new Form
{
Text = title,
FormBorderStyle = FormBorderStyle.FixedDialog,
StartPosition = FormStartPosition.CenterParent,
MinimizeBox = false,
MaximizeBox = false,
ClientSize = new Size(380, 110),
})
{
var lbl = new Label { Text = label, AutoSize = true, Left = 12, Top = 14 };
var txt = new TextBox { Left = 12, Top = 36, Width = 356, Text = initial };
var ok = new Button { Text = "OK", DialogResult = DialogResult.OK, Left = 212, Top = 70, Width = 75 };
var cancel = new Button { Text = "Cancel", DialogResult = DialogResult.Cancel, Left = 293, Top = 70, Width = 75 };
dlg.Controls.Add(lbl);
dlg.Controls.Add(txt);
dlg.Controls.Add(ok);
dlg.Controls.Add(cancel);
dlg.AcceptButton = ok;
dlg.CancelButton = cancel;
txt.SelectAll();
if (dlg.ShowDialog(this) != DialogResult.OK) return null;
string value = txt.Text.Trim();
return value.Length == 0 ? null : value;
}
}
private void Error(string title, Exception ex)
{
Log($"ERROR: {title}: {ex.Message}");
MessageBox.Show(this, ex.Message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
SetStatus(title + " — see log.");
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
_cts?.Cancel();
StopServerIfRunning();
_db?.Dispose();
base.OnFormClosing(e);
}
}
}