forked from ImpulseAdventure/JPEGsnoop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JPEGsnoop.cpp
1729 lines (1451 loc) · 50.8 KB
/
JPEGsnoop.cpp
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
// JPEGsnoop - JPEG Image Decoder & Analysis Utility
// Copyright (C) 2017 - Calvin Hass
// http://www.impulseadventure.com/photo/jpeg-snoop.html
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// JPEGsnoop is written in Microsoft Visual C++ using MFC
// JPEGsnoop.cpp : Defines the class behaviors for the application.
//
#include "stdafx.h"
#include "MainFrm.h"
#include "JPEGsnoop.h"
#include "JPEGsnoopDoc.h"
#include "JPEGsnoopView.h"
#include "snoop.h"
#include "SnoopConfig.h"
#include "AboutDlg.h"
#include "DbSubmitDlg.h"
#include "SettingsDlg.h"
#include "DbManageDlg.h"
#include "TermsDlg.h"
#include "UpdateAvailDlg.h"
#include "ModelessDlg.h"
#include "NoteDlg.h"
#include "HyperlinkStatic.h"
#include "afxinet.h" // For internet
#include "io.h" // For _open_osfhandle
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// Global log file
CDocLog* glb_pDocLog = NULL;
// CJPEGsnoopApp
BEGIN_MESSAGE_MAP(CJPEGsnoopApp, CWinApp)
ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
// Standard file based document commands
ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
//CAL! ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
//ON_COMMAND(ID_FILE_NEW, MyOnFileNew)
ON_COMMAND(ID_FILE_OPEN, MyOnFileOpen)
// Standard print setup command
ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
ON_COMMAND(ID_OPTIONS_DHTEXPAND, OnOptionsDhtexpand)
ON_COMMAND(ID_OPTIONS_MAKERNOTES, OnOptionsMakernotes)
ON_COMMAND(ID_OPTIONS_CONFIGURATION, OnOptionsConfiguration)
ON_COMMAND(ID_OPTIONS_CHECKFORUPDATES, OnOptionsCheckforupdates)
ON_COMMAND(ID_OPTIONS_SIGNATURESEARCH, OnOptionsSignaturesearch)
ON_COMMAND(ID_TOOLS_MANAGELOCALDB, OnToolsManagelocaldb)
ON_COMMAND(ID_SCANSEGMENT_DECODEIMAGE, OnScansegmentDecodeimage)
ON_COMMAND(ID_SCANSEGMENT_FULLIDCT, OnScansegmentFullidct)
ON_COMMAND(ID_SCANSEGMENT_HISTOGRAMY, OnScansegmentHistogramy)
ON_COMMAND(ID_SCANSEGMENT_DUMP, OnScansegmentDump)
ON_UPDATE_COMMAND_UI(ID_OPTIONS_DHTEXPAND, OnUpdateOptionsDhtexpand)
ON_UPDATE_COMMAND_UI(ID_OPTIONS_MAKERNOTES, OnUpdateOptionsMakernotes)
ON_UPDATE_COMMAND_UI(ID_OPTIONS_SIGNATURESEARCH, OnUpdateOptionsSignaturesearch)
ON_UPDATE_COMMAND_UI(ID_SCANSEGMENT_DECODEIMAGE, OnUpdateScansegmentDecodeimage)
ON_UPDATE_COMMAND_UI(ID_SCANSEGMENT_FULLIDCT, OnUpdateScansegmentFullidct)
ON_UPDATE_COMMAND_UI(ID_SCANSEGMENT_HISTOGRAMY, OnUpdateScansegmentHistogramy)
ON_UPDATE_COMMAND_UI(ID_SCANSEGMENT_DUMP, OnUpdateScansegmentDump)
ON_COMMAND(ID_SCANSEGMENT_NOIDCT, OnScansegmentNoidct)
ON_UPDATE_COMMAND_UI(ID_SCANSEGMENT_NOIDCT, OnUpdateScansegmentNoidct)
ON_COMMAND(ID_SCANSEGMENT_HISTOGRAM, OnScansegmentHistogram)
ON_UPDATE_COMMAND_UI(ID_SCANSEGMENT_HISTOGRAM, OnUpdateScansegmentHistogram)
ON_COMMAND(ID_OPTIONS_HIDEUKNOWNEXIFTAGS, OnOptionsHideuknownexiftags)
ON_UPDATE_COMMAND_UI(ID_OPTIONS_HIDEUKNOWNEXIFTAGS, OnUpdateOptionsHideuknownexiftags)
ON_COMMAND(ID_FILE_BATCHPROCESS, OnFileBatchprocess)
ON_COMMAND(ID_OPTIONS_RELAXEDPARSING, &CJPEGsnoopApp::OnOptionsRelaxedparsing)
ON_UPDATE_COMMAND_UI(ID_OPTIONS_RELAXEDPARSING, &CJPEGsnoopApp::OnUpdateOptionsRelaxedparsing)
END_MESSAGE_MAP()
// FIXME:
// Would like to change string table JPEGsnoop.rc to add:
// AFX_IDS_OPENFILE 0xF000 (61440) = _T("Open Image / Movie") for Open Dialog
// but linker complains error RC2151 "cannot reuse string constants"
// ======================================
// Command Line option support
// ======================================
// Display the command-line help/options summary
void CJPEGsnoopApp::CmdLineHelp()
{
CString strMsg = _T("");
CString strLine = _T("");
strMsg += _T("\n");
strLine.Format(_T("JPEGsnoop v%s\n"),VERSION_STR);
strMsg += strLine;
strMsg += _T("\n");
strMsg += _T("JPEGsnoop.exe <parameters>\n");
strMsg += _T("\n");
strMsg += _T(" One of the following input parameters:\n");
strMsg += _T(" -help : Show command summary\n");
strMsg += _T(" -i <fname_in> : Defines input JPEG filename\n");
strMsg += _T(" -b <dir> : Batch process directory\n");
strMsg += _T(" -br <dir> : Batch process directory (recursive)\n");
strMsg += _T(" Zero or more of the following input parameters:\n");
strMsg += _T(" -o <fname_log> : Defines output log filename\n");
strMsg += _T(" -ext_all : Extract all from file\n");
strMsg += _T(" -ext_dht_avi : Force insert DHT for AVI (-ext_all mode)\n");
strMsg += _T(" -scan : Enables Scan Segment decode\n");
strMsg += _T(" -maker : Enables Makernote decode\n");
strMsg += _T(" -scandump : Enables Scan Segment dumping\n");
strMsg += _T(" -histo_y : Enables luminance histogram\n");
strMsg += _T(" -dhtexp : Enables DHT table expansion into huffman bitstrings\n");
strMsg += _T(" -exif_hide_unk : Disables decoding of unknown makernotes\n");
strMsg += _T(" -offset_start : Decode at start of file\n");
strMsg += _T(" -offset_srch1 : Decode at 1st SOI found in file\n");
strMsg += _T(" -offset_srch2 : Decode at 1st SOI found after start of file\n");
strMsg += _T(" -offset_pos <###> : Decode from byte ### (decimal) in file\n");
strMsg += _T(" -done : Indicate when operations complete\n");
strMsg += _T("\n");
CmdLineMessage(strMsg);
}
// Command-line parser class
class CMyCommandParser : public CCommandLineInfo
{
typedef enum {cla_idle,cla_input,cla_output,cla_err,cla_batchdir,cla_offset_pos} cla_e;
int index;
cla_e next_arg;
CSnoopConfig* m_pCfg;
CString strTmp;
public:
CMyCommandParser(CSnoopConfig* pCfg) {
m_pCfg = pCfg;
CCommandLineInfo();
index=0; // initializes an index to allow make a positional analysis
next_arg = cla_idle;
};
virtual void ParseParam(LPCTSTR pszParam, BOOL bFlag, BOOL bLast) {
bLast; // Unreferenced param
CString msg;
// GUI mode decision
// - Default to GUI mode
// - If any command-line parameter identified, change to non-GUI mode
// - Drag & drop will remain GUI mode
bool bCmdLineDetected = false;
switch(next_arg) {
case cla_idle:
if (bFlag && !_tcscmp(pszParam,_T("i"))) {
next_arg = cla_input;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("o"))) {
next_arg = cla_output;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("b"))) {
next_arg = cla_batchdir;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("br"))) {
m_pCfg->bCmdLineBatchRec = true;
next_arg = cla_batchdir;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("help"))) {
m_nShellCommand = FileNothing;
m_pCfg->bCmdLineHelp = true;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("h"))) {
m_nShellCommand = FileNothing;
m_pCfg->bCmdLineHelp = true;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("?"))) {
m_nShellCommand = FileNothing;
m_pCfg->bCmdLineHelp = true;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("offset_start"))) {
m_pCfg->eCmdLineOffset = DEC_OFFSET_START;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("offset_srch1"))) {
m_pCfg->eCmdLineOffset = DEC_OFFSET_SRCH1;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("offset_srch2"))) {
m_pCfg->eCmdLineOffset = DEC_OFFSET_SRCH2;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("offset_pos"))) {
m_pCfg->eCmdLineOffset = DEC_OFFSET_POS;
m_pCfg->nCmdLineOffsetPos = 0;
next_arg = cla_offset_pos;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("ext_all"))) {
m_pCfg->bCmdLineExtractEn = true;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("ext_dht_avi"))) {
m_pCfg->bCmdLineExtractDhtAvi = true;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("scan"))) {
m_pCfg->bDecodeScanImg = true;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("maker"))) {
m_pCfg->bDecodeMaker = true;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("scandump"))) {
m_pCfg->bOutputScanDump = true;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("histo_y"))) {
m_pCfg->bHistoEn = true;
m_pCfg->bDumpHistoY = true;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("dhtexp"))) {
m_pCfg->bOutputDHTexpand = true;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("exif_hide_unk"))) {
m_pCfg->bExifHideUnknown = true;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag && !_tcscmp(pszParam,_T("done"))) {
m_pCfg->bCmdLineDoneMsg = true;
next_arg = cla_idle;
bCmdLineDetected = true;
}
else if (bFlag) {
// Unknown flag
strTmp.Format(_T("ERROR: Unknown command-line flag [-%s]"),pszParam);
// Don't disable dialog in non-interactive mode as this could be an important error
// Show dialog box with info
AfxMessageBox(strTmp);
// And also report command line options
next_arg = cla_err;
m_nShellCommand = FileNothing;
m_pCfg->bCmdLineHelp = true;
bCmdLineDetected = true;
}
else {
// Not a flag, so assume it is a drag & drop file open
// Note that drag & drop doesn't appear to suffer from '-' prefix issues (see below)
m_pCfg->bCmdLineOpenEn = true;
m_pCfg->strCmdLineOpenFname = pszParam;
// This will run in default mode which is GUI mode
m_nShellCommand = FileOpen;
m_strFileName = pszParam;
}
break;
case cla_input:
msg = _T("Input=[");
msg += pszParam;
msg += _T("]");
// Handle case where filename was preceded by dash ('-')
// Per CCommandLineInfo::ParseParam http://msdn.microsoft.com/en-us/library/bss6bxss.aspx
// If first char is '-' or '/' then it is treated as flag and
// the character is removed.
//
// Since we are in "cla_input" state due to preceding "-i" flag,
// we should not have bFlag set here. If so, we need to re-instate the
// character.
//
// NOTE: We actually roll-back the pszParam pointer as CWinApp::ParseCommandLine()
// increments the pointer when setting bFlag=true.
// Reference: C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\atlmfc\src\mfc\appcore.cpp
//
if (bFlag) {
// Fixing hyphen filename prefix by rolling back the pointer
pszParam--;
}
m_pCfg->bCmdLineOpenEn = true;
m_pCfg->strCmdLineOpenFname = pszParam;
m_nShellCommand = FileNothing;
m_strFileName = _T(""); // Unused
next_arg = cla_idle;
break;
// Batch directory processing
case cla_batchdir:
msg = _T("BatchDir=[");
msg += pszParam;
msg += _T("]");
if (bFlag) {
// Fixing hyphen filename prefix by rolling back the pointer
pszParam--;
}
// Store the batch directory name
m_pCfg->bCmdLineBatchEn = true;
m_pCfg->strCmdLineBatchDirName = pszParam;
// Set the ShellCommand to FileNothing so that the InitProcess()
// call doesn't take any action. Instead, we can perform the
// batch processing ourself.
m_nShellCommand = FileNothing;
m_strFileName = _T(""); // Unused
next_arg = cla_idle;
break;
case cla_output:
msg = _T("Output=[");
msg += pszParam;
msg += _T("]");
if (bFlag) {
// Fixing hyphen filename prefix by rolling back the pointer
pszParam--;
}
m_pCfg->bCmdLineOutputEn = true;
m_pCfg->strCmdLineOutputFname = pszParam;
next_arg = cla_idle;
break;
case cla_offset_pos:
msg = _T("OffsetPos=[");
msg += pszParam;
msg += _T("]");
m_pCfg->nCmdLineOffsetPos = _ttoi(pszParam);
next_arg = cla_idle;
break;
case cla_err:
default:
break;
}
// Now update to non-GUI mode if command-line param detected
if (bCmdLineDetected) {
m_pCfg->bGuiMode = false;
m_pCfg->bInteractive = false;
}
};
};
// CJPEGsnoopApp construction
// Constructor
CJPEGsnoopApp::CJPEGsnoopApp()
{
// Reset fatal error flag
m_bFatal = false;
// Application-level config options
m_pAppConfig = new CSnoopConfig();
if (!m_pAppConfig) {
AfxMessageBox(_T("ERROR: Couldn't allocate memory for SnoopConfig"));
m_bFatal = true;
}
if (DEBUG_EN) m_pAppConfig->DebugLogCreate();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::CJPEGsnoopApp() Checkpoint 1"));
glb_pDocLog = new CDocLog();
if (!glb_pDocLog) {
AfxMessageBox(_T("ERROR: Not enough memory for Log"));
exit(1);
}
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::CJPEGsnoopApp() Checkpoint 2"));
m_pDbSigs = new CDbSigs();
if (!m_pDbSigs) {
AfxMessageBox(_T("ERROR: Couldn't allocate memory for DbSigs"));
m_bFatal = true;
}
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::CJPEGsnoopApp() Checkpoint 3"));
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::CJPEGsnoopApp() End"));
}
// Destructor
CJPEGsnoopApp::~CJPEGsnoopApp()
{
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::~CJPEGsnoopApp() Start"));
// Save and then Delete
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::~CJPEGsnoopApp() About to destroy Config"));
if (m_pAppConfig != NULL)
{
m_pAppConfig->RegistryStore();
delete m_pAppConfig;
m_pAppConfig = NULL;
}
if (glb_pDocLog != NULL) {
delete glb_pDocLog;
glb_pDocLog = NULL;
}
if (m_pDbSigs != NULL)
{
delete m_pDbSigs;
m_pDbSigs = NULL;
}
}
// The one and only CJPEGsnoopApp object
CJPEGsnoopApp theApp;
// CJPEGsnoopApp initialization
// Override localization virtual function to avoid potential for
// satellite DLL hijacking
HINSTANCE CJPEGsnoopApp::LoadAppLangResourceDLL()
{
return NULL;
}
BOOL CJPEGsnoopApp::InitInstance()
{
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Start"));
// InitCommonControls() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
InitCommonControls();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 1"));
CWinApp::InitInstance();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 2"));
// Initialize OLE libraries
if (!AfxOleInit())
{
AfxMessageBox(IDP_OLE_INIT_FAILED);
return FALSE;
}
AfxEnableControlContainer();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 3"));
// Check to see if we had any fatal errors yet (e.g. mem alloc)
if (m_bFatal) {
return FALSE;
}
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// This call actually concatenates CWinApp::m_pszAppName ("JPEGsnoop")
// with the "REG_COMPANY_NAME" to create the full
// key path "Software/ImpulseAdventure/JPEGsnoop/Recent File List"
SetRegistryKey(REG_COMPANY_NAME);
LoadStdProfileSettings(4); // Load standard INI file options (including MRU)
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 4"));
// ------------------------------------
m_pAppConfig->RegistryLoad();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 5"));
// Now that we've loaded the registry, assign the first-run status (from EULA)
// Set the "First Run" flag for the Signature database to avoid warning messages
m_pDbSigs->SetFirstRun(!m_pAppConfig->bEulaAccepted);
// Assign defaults
m_pAppConfig->UseDefaults();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 6"));
// Ensure that the user has previously signed the EULA
if (!CheckEula()) {
return false;
}
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 7"));
// Has the user enabled checking for program updates?
if (m_pAppConfig->bUpdateAuto) {
CheckUpdates(false);
}
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 8"));
m_pAppConfig->RegistryStore();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 9"));
// Update the User database directory setting
m_pDbSigs->SetDbDir(m_pAppConfig->strDbDir);
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 10"));
// Register the application's document templates. Document templates
// serve as the connection between documents, frame windows and views
// FIXME:
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(
IDR_MAINFRAME,
RUNTIME_CLASS(CJPEGsnoopDoc),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CJPEGsnoopView));
if (!pDocTemplate)
return FALSE;
pDocTemplate->SetContainerInfo(IDR_CNTR_INPLACE);
AddDocTemplate(pDocTemplate);
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 11"));
// Establish GUI mode defaults that can be overridden by the
// command line parsing results.
m_pAppConfig->bGuiMode = true;
m_pAppConfig->bInteractive = true;
// Parse command line for standard shell commands, DDE, file open
CMyCommandParser cmdInfo(m_pAppConfig);
ParseCommandLine(cmdInfo);
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 12"));
if (m_pAppConfig->bGuiMode) {
// If the user has requested that we open up a file in GUI mode:
// - Normal operation
// - Drag & drop
// then we need to ensure that the view has been created before we
// enter the OnOpenDocument() in OpenDocumentFile(). The reason for this
// is that OnOpenDocument will call AnalyzeFile() and insert the log into
// the view. The view is only created at the end of OpenDocumentFile() as
// a result of OnInitialUpdate().
//
// To achieve this, the easiest method is to force a New file operation
// first. This ensures that we create the view (in OnInitialUpdate)
// before we launch into any processing.
//
// For cosmetic reasons, also call UpdateWindow to ensure that the
// frame is drawn fully before any further processing.
OnFileNew();
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
}
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 13"));
// Do my own ProcessShellCommand(). The following is based
// on part of what exists in appui2.cpp with no real changes.
// I have dropped off some of the unsupported m_nShellCommand modes.
// Perhaps this will provide us with an easier means of extending
// support to other batch commands later.
// ----------------------------------------------------------
if (!ProcessShellCommand(cmdInfo))
return FALSE;
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 14"));
// ----------------------------------------------------------
// Now handle any other command-line directives that we haven't
// already covered above
if (m_pAppConfig->bGuiMode == false) {
//bool bCmdLineRet = false;
DoCmdLineCore();
return false;
}
// We only arrive here if there is a window to show (bResult)
// Original wizard code follows
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 20"));
// The one and only window has been initialized, so show and update it
m_pMainWnd->ShowWindow(SW_SHOW);
m_pMainWnd->UpdateWindow();
// call DragAcceptFiles only if there's a suffix
// In an SDI app, this should occur after ProcessShellCommand
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() Checkpoint 21"));
// ----------------
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CJPEGsnoopApp::InitInstance() End"));
return TRUE;
}
// Process any command-line operations
void CJPEGsnoopApp::DoCmdLineCore()
{
ASSERT(m_pAppConfig->bGuiMode == false);
// Allocate the command-line processing core
CJPEGsnoopCore* pSnoopCore = NULL;
pSnoopCore = new CJPEGsnoopCore;
ASSERT(pSnoopCore);
if (!pSnoopCore) {
exit(1);
}
BOOL bStatus = false;
// Perform processing requested by command-line
if (m_pAppConfig->bCmdLineHelp) {
// Display command-line summary
CmdLineHelp();
} else if (m_pAppConfig->bCmdLineOpenEn) {
// Single file processing
// ===================================
// Handle "-i"
// ===================================
// Process the file
bStatus = pSnoopCore->DoAnalyzeOffset(m_pAppConfig->strCmdLineOpenFname);
if (!bStatus) {
// Issues during file open
// Error message was already added to the log file in AnalyzeOpen()
// So just report to user in console
CString strErr;
strErr.Format(_T("ERROR: during open of file [%s]\n"),(LPCTSTR)m_pAppConfig->strCmdLineOpenFname);
CmdLineMessage(strErr);
}
// Save the output log if enabled
// Note that we will do this even if the input file open had
// an issue, so that post-processing will reveal error in
// the associated log report.
if (theApp.m_pAppConfig->bCmdLineOutputEn) {
pSnoopCore->DoLogSave(m_pAppConfig->strCmdLineOutputFname);
}
if (bStatus) {
// Now proceed to "extract all" if requested
if (m_pAppConfig->bCmdLineExtractEn) {
CString strInputFname = m_pAppConfig->strCmdLineOpenFname;
CString strExportFname = m_pAppConfig->strCmdLineOutputFname;
bool bOverlayEn = false;
bool bForceSoi = false;
bool bForceEoi = false;
bool bIgnoreEoi = false;
bool bExtractAllEn = true;
bool bDhtAviInsert = false;
CString strOutPath = _T(""); // unused
// If the user didn't explicitly provide an output filename, default to one
if (strExportFname == _T("")) {
strExportFname = strInputFname + _T(".export.jpg");
}
pSnoopCore->DoExtractEmbeddedJPEG(strInputFname,strExportFname,bOverlayEn,bForceSoi,bForceEoi,bIgnoreEoi,bExtractAllEn,bDhtAviInsert,strOutPath);
} // bCmdLineExtractEn
} // bStatus
} else if (m_pAppConfig->bCmdLineBatchEn) {
// Batch file processing
// ===================================
// Handle "-b" and "-br"
// ===================================
// Settings for batch operations
CString strDirSrc;
CString strDirDst;
bool bSubdirs;
bool bExtractAll;
strDirSrc = m_pAppConfig->strCmdLineBatchDirName;
strDirDst = m_pAppConfig->strCmdLineBatchDirName; // Only support same dir for now
bSubdirs = m_pAppConfig->bCmdLineBatchRec;
bExtractAll = m_pAppConfig->bCmdLineExtractEn;
// Generate the batch file list
pSnoopCore->GenBatchFileList(strDirSrc,strDirDst,bSubdirs,bExtractAll);
// Now that we've created the list of files, start processing them
unsigned nBatchFileCount;
nBatchFileCount = pSnoopCore->GetBatchFileCount();
// TODO: Clear the current RichEdit log
for (unsigned nFileInd=0;nFileInd<nBatchFileCount;nFileInd++) {
// Process file
pSnoopCore->DoBatchFileProcess(nFileInd,true,bExtractAll);
}
// TODO: ...
}
// Deallocate the command-line core
if (pSnoopCore) {
delete pSnoopCore;
pSnoopCore = NULL;
}
// If requested, issue done indication to the prompt
if (m_pAppConfig->bCmdLineDoneMsg) {
CmdLineDoneMessage();
}
}
// Report that application is finished to console
// This is an optional indicator to say that command-line
// operations have completed.
void CJPEGsnoopApp::CmdLineDoneMessage()
{
CString strMsg;
strMsg = "\n";
strMsg += "JPEGsnoop operations complete\n";
strMsg += "\n";
CmdLineMessage(strMsg);
}
// Report a message to the console
//
// Note that this reporting may interject with
// the user's input to the command prompt since GUI application
// will release to command prompt immediately after launching
// and will not block.
void CJPEGsnoopApp::CmdLineMessage(CString strMsg)
{
// Report to the console
// REF: http://stackoverflow.com/questions/5094502/how-do-i-write-to-stdout-from-an-mfc-program
bool bConsoleAttached = FALSE;
if (AttachConsole(ATTACH_PARENT_PROCESS))
{
int osfh = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), 8);
if ((HANDLE)osfh != INVALID_HANDLE_VALUE)
{
*stdout = *_tfdopen(osfh, _T("a"));
bConsoleAttached = TRUE;
}
}
if (bConsoleAttached) {
// -------------------------------------------
// Now convert from unicode for printf
// REF: http://stackoverflow.com/questions/10578522/conversion-of-cstring-to-char
// The number of characters in the string can be
// less than nMaxStrLen. Null terminating character added at end.
const size_t nMaxStrLen = 5000;
size_t nCharsConverted = 0;
char acMsg[nMaxStrLen];
wcstombs_s(&nCharsConverted, acMsg,
strMsg.GetLength()+1, strMsg,
_TRUNCATE);
// -------------------------------------------
// Output to console
printf("%s",acMsg);
}
}
// If it has been more than "nUpdateAutoDays" days since our
// last check for a recent update to the software, check the
// website for a newer version.
// - If a new version is available, the user is notified but
// no action or changes are made. The user needs to navigate
// to the website to download the latest version manually.
//
// INPUT:
// - bForceNow = Do we ignore day timer and force a check now?
//
void CJPEGsnoopApp::CheckUpdates(bool bForceNow)
{
CString strUpdateLastChk = m_pAppConfig->strUpdateLastChk;
unsigned nCheckYear,nCheckMon,nCheckDay;
if (strUpdateLastChk.GetLength()==8) {
nCheckYear = _tstoi(strUpdateLastChk.Mid(0,4));
nCheckMon = _tstoi(strUpdateLastChk.Mid(4,2));
nCheckDay = _tstoi(strUpdateLastChk.Mid(6,2));
} else {
nCheckYear = 1980;
nCheckMon = 1;
nCheckDay = 1;
}
CTime tmeUpdateLastChk(nCheckYear,nCheckMon,nCheckDay,0,0,0);
CTime tmeToday = CTime::GetCurrentTime();
CTimeSpan tmePeriod(m_pAppConfig->nUpdateAutoDays, 0, 0, 0);
CTimeSpan tmeDiff;
tmeDiff = tmeToday - tmeUpdateLastChk;
if ((bForceNow) || (tmeDiff >= tmePeriod)) {
CModelessDlg* pdlg;
pdlg = new CModelessDlg;
if (!pdlg) {
// Fatal error
exit(1);
}
pdlg->Create(IDD_MODELESSDLG,NULL);
CheckUpdatesWww();
pdlg->OnCancel();
// Update the timestamp of the last update check
CString strCurDate;
strCurDate = tmeToday.Format(_T("%Y%m%d"));
m_pAppConfig->strUpdateLastChk = strCurDate;
m_pAppConfig->Dirty();
}
}
// Scrape the header of the web page to determine if a newer version
// of the software is available.
// - No information is sent to the website other than the current version number
//
// RETURN:
// - Success if connection to web page was OK
//
bool CJPEGsnoopApp::CheckUpdatesWww()
{
CString strVerLatest = _T("");
CString strDateLatest = _T("");
CString strSubmitHost;
CString strSubmitPage;
strSubmitHost = IA_HOST;
strSubmitPage = IA_UPDATES_CHK_PAGE;
static LPTSTR acceptTypes[2]={_T("*/*"), NULL};
HINTERNET hINet, hConnection, hData;
unsigned nLen;
CString strFormat;
CString strFormData;
unsigned nFormDataLen;
CString strHeaders =
_T("Content-Type: application/x-www-form-urlencoded");
strFormat = _T("ver=%s");
//*** Need to sanitize data for URL submission!
// Search for "&", "?", "="
strFormData.Format(strFormat,VERSION_STR);
nFormDataLen = strFormData.GetLength();
CString strTmp;
CHAR pcBuffer[2048] ;
CString strContents ;
DWORD dwRead; //dwStatus;
hINet = InternetOpen(_T("JPEGsnoop/1.0"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
if ( !hINet )
{
AfxMessageBox(_T("InternetOpen Failed"));
return false;
}
try
{
hConnection = InternetConnect( hINet, (LPCTSTR)strSubmitHost, 80, NULL,NULL, INTERNET_SERVICE_HTTP, 0, 1 );
if ( !hConnection )
{
InternetCloseHandle(hINet);
return false;
}
hData = HttpOpenRequest( hConnection, _T("POST"), (LPCTSTR)strSubmitPage, NULL, NULL, NULL, 0, 1 );
if ( !hData )
{
InternetCloseHandle(hConnection);
InternetCloseHandle(hINet);
return false;
}
// GET HttpSendRequest( hData, NULL, 0, NULL, 0);
if (!HttpSendRequest( hData, (LPCTSTR)strHeaders, strHeaders.GetLength(), strFormData.GetBuffer(), strFormData.GetLength())) {
InternetCloseHandle(hConnection);
InternetCloseHandle(hINet);
AfxMessageBox(_T("ERROR: Couldn't SendRequest"));
return false;
}
// Only read the first 1KB of page
bool bScrapeDone = false;
unsigned nScrapeLen = 0;
unsigned nScrapeMax = 1024;
while (!bScrapeDone) {
if (!InternetReadFile( hData, pcBuffer, 255, &dwRead )) {
bScrapeDone = true;
} else {
if ( dwRead == 0 ) {
bScrapeDone = true;
break;
}
pcBuffer[dwRead] = 0;
strContents += pcBuffer;
nScrapeLen += dwRead;
if (nScrapeLen >= nScrapeMax) {
bScrapeDone = true;
}
}
}
// Parse the HTTP result and search for the latest
// version identification string
nLen = strContents.GetLength();
CString strData;
CString strParam;
CString strVal;
int nIndDataStart = -1;
int nIndDataEnd = -1;
unsigned nIndDataLen = 0;
bool bFoundRange = true;
nIndDataStart = strContents.Find(_T("***("))+4;
nIndDataEnd = strContents.Find(_T(")***"));
if ((nIndDataStart == -1) || (nIndDataEnd == -1)) {
// Couldn't find start or end
bFoundRange = false;
}
if (nIndDataStart > nIndDataEnd) {
// Start and End positions look wrong
bFoundRange = false;
}
if (bFoundRange) {
// Found start & end markers
nIndDataLen = nIndDataEnd-nIndDataStart;
strData = strContents.Mid(nIndDataStart,nIndDataLen);
bool bDone = false;
bool bTokDone;
CString strCh;