-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathftpsync.cpp
More file actions
861 lines (823 loc) · 30.3 KB
/
ftpsync.cpp
File metadata and controls
861 lines (823 loc) · 30.3 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
/* ========================================================================= */
/* ######## ######## ######## ######## ## .. ## ######## ######## ......FILE */
/* ## ........ ## .. ## .. ## ## ..... ## .. ## ## .. ## ## .. ## ..TRANSFER */
/* ######## .. ## .. ######## ######## ######## ## .. ## ## ........PROTOCOL */
/* ## ........ ## .. ## ........... ## ..... ## ## .. ## ## .. ## ...SYNCHRO */
/* ## ........ ## .. ## ..... ######## ######## ## .. ## ######## ...UTILITY */
/* ========================================================================= */
#include <assert.h> // Assertation functions.
#include <conio.h> // Console functions.
#include <direct.h> // Directory functions.
#include <errno.h> // Error functions.
#include <fcntl.h> // File control functions.
#include <io.h> // I/o functions.
#include <stdio.h> // Standard functions.
#include <string.h> // String functions.
#include <sys/stat.h> // Stat functions.
#include <sys/utime.h> // File time functions.
#include <time.h> // Time functions.
#include <windows.h> // Windows api functions.
#include <winsock.h> // Windows sockets api.
#include "zlib/zlib.h" // Zlib compression library.
/* ========================================================================= */
#pragma comment(lib, "WSock32.Lib") // Want Windows sockets library.
/* ========================================================================= */
#define RECV_BUF (4096L) // Receive buffer size
/* ========================================================================= */
struct { int iMajor, iMinor, iComp, iBits; const char *cpComp, *cpSrc; }
vData = { 1, 0, _MSC_VER, sizeof(void*)<<3, __TIMESTAMP__, __FILE__ };
/* ------------------------------------------------------------------------- */
typedef bool (*PDBFUNC)(SOCKET sSocket, SOCKET sPSocket, void *vpParam);
/* ------------------------------------------------------------------------- */
#pragma pack(push, 1)
typedef struct { uLong ulSize, ulCrc, ulCompSize; Bytef baData[1]; }
ZPACKET, *PZPACKET;
typedef struct { uLong ulMagic, ulMajor, ulMinor, ulFiles, ulUsage; }
PACKET, *PPACKET;
#pragma pack(pop)
/* ------------------------------------------------------------------------- */
uLong ulMagic = 'BDSF';
/* ------------------------------------------------------------------------- */
typedef struct _FILERECORD
{
struct _wfinddata_t fdData;
struct _FILERECORD *frpNext;
}
FILERECORD, *PFILERECORD;
/* ------------------------------------------------------------------------- */
PFILERECORD frpFirst, frpLast;
/* ========================================================================= */
void buildpathstructure(wchar_t *wcpName)
{
wchar_t wcaDrive[_MAX_DRIVE], wcaDir[_MAX_DIR], wcaFile[_MAX_FNAME], wcaExt[_MAX_EXT], wcaPath[_MAX_PATH];
memset(wcaPath, 0, sizeof(wcaPath));
_wsplitpath_s(wcpName, wcaDrive, wcaDir, wcaFile, wcaExt);
if(!*wcaDir) return;
const wchar_t *wcpSep = L"\\/";
wchar_t *wcpPtr, *wcpPid;
for(wcpPtr = wcstok_s(wcaDir, wcpSep, &wcpPid); wcpPtr; wcpPtr = wcstok_s(NULL, wcpSep, &wcpPid))
{
if(*wcaPath) wcscat_s(wcaPath, _MAX_PATH, L"/");
wcscat_s(wcaPath, _MAX_PATH, wcpPtr);
_wmkdir(wcaPath);
}
}
/* ========================================================================= */
void Recurse(wchar_t *wcpPath, int iLevel, int *iFiles, int *iUsage)
{
wchar_t wcaPath[_MAX_PATH], wcaFile[_MAX_PATH];
struct _wfinddata_t fdData;
PFILERECORD frpPtr;
intptr_t hFile = 0;
wcscpy_s(wcaPath, _MAX_PATH, wcpPath);
hFile = _wfindfirst(L"*.*", &fdData);
if(hFile == NULL)
return;
while(_wfindnext(hFile, &fdData) == 0)
{
if(!wcscmp(fdData.name, L".") || !wcscmp(fdData.name, L".."))
continue;
if(*wcaPath != '\0')
swprintf_s(wcaFile, _MAX_PATH, L"%s\\%s", wcaPath, fdData.name);
else
wcscpy_s(wcaFile, _MAX_PATH, fdData.name);
if(fdData.attrib & _A_SUBDIR)
{
if(_wchdir(fdData.name) != -1)
{
Recurse(wcaFile, iLevel+1, iFiles, iUsage);
_wchdir(L"..");
}
}
else
{
memset(fdData.name, '\0', sizeof(fdData.name));
wcscpy_s(fdData.name, _MAX_PATH, wcaFile);
frpPtr = new FILERECORD;
memcpy(&frpPtr->fdData, &fdData, sizeof(_wfinddata_t));
frpPtr->frpNext = NULL;
if(frpFirst == NULL)
frpFirst = frpLast = frpPtr;
else
frpLast->frpNext = frpPtr, frpLast = frpPtr;
++*iFiles;
*iUsage += fdData.size;
}
}
_findclose(hFile);
}
/* ========================================================================= */
int sendf(SOCKET sSocket, const char *cpFormat, ...)
{
int iBytes = _vscprintf(cpFormat, (va_list)(&cpFormat + 1));
if(iBytes <= 0) return -1;
iBytes += 2;
char *cpFormatBuffer = new char[iBytes+1];
_vsnprintf_s(cpFormatBuffer, iBytes+1, iBytes, cpFormat, (va_list)(&cpFormat+1));
wprintf(L"--> %S\n", cpFormatBuffer);
strcat_s(cpFormatBuffer, iBytes+1, "\r\n");
int iResult = send(sSocket, cpFormatBuffer, iBytes, 0);
delete []cpFormatBuffer;
return iResult;
}
/* ========================================================================= */
int sendfhidden(SOCKET sSocket, const char *cpFormat, ...)
{
int iBytes = _vscprintf(cpFormat, (va_list)(&cpFormat + 1));
if(iBytes <= 0) return -1;
iBytes += 2;
char *cpFormatBuffer = new char[iBytes+1];
_vsnprintf_s(cpFormatBuffer, iBytes+1, iBytes, cpFormat, (va_list)(&cpFormat+1));
char *cpPtr;
char *cpStr = _strdup(cpFormatBuffer);
for(cpPtr = cpStr; *cpPtr != '\0'; ++cpPtr)
if(*cpPtr == ' ') { *cpPtr = '\0'; break; }
wprintf(L"--> %S\n", cpStr);
free(cpStr);
strcat_s(cpFormatBuffer, iBytes+1, "\r\n");
int iResult = send(sSocket, cpFormatBuffer, iBytes, 0);
memset(cpFormatBuffer, '\0', iBytes);
delete []cpFormatBuffer;
return iResult;
}
/* ========================================================================= */
uLong recvbuf(SOCKET sSocket, Bytef *bpBuffer, uLong ulSize)
{
uLong ulTotal = 0, ulBytes;
int iBytes;
while(ulTotal < ulSize)
{
ulBytes = ulSize-ulTotal;
if(ulBytes > RECV_BUF)
ulBytes = RECV_BUF;
iBytes = recv(sSocket, (char *)bpBuffer+ulTotal, ulBytes, 0);
if(iBytes <= 0)
{
wprintf(L"recv failed; r%i %u/%u/%ub e%u.\n", iBytes, ulBytes, ulTotal, ulSize, WSAGetLastError());
break;
}
ulTotal += iBytes;
}
if(ulTotal != ulSize)
*bpBuffer = '\0';
return ulTotal;
}
/* ========================================================================= */
Bytef *recvinflate(uLong *ulpSize, uLong *ulpCrc, SOCKET sSocket)
{
PZPACKET pzPacket = (PZPACKET)malloc(sizeof(ZPACKET));
Bytef *cpData = NULL;
if(pzPacket != NULL)
{
if(recvbuf(sSocket, (Bytef*)pzPacket, sizeof(ZPACKET)-1) == sizeof(ZPACKET)-1)
{
pzPacket = (PZPACKET)realloc(pzPacket, (sizeof(ZPACKET)-1)+pzPacket->ulCompSize);
if(pzPacket != NULL)
{
if(recvbuf(sSocket, (Bytef*)pzPacket+(sizeof(ZPACKET)-1), pzPacket->ulCompSize) == pzPacket->ulCompSize)
{
cpData = (Bytef*)malloc(pzPacket->ulSize);
if(cpData != NULL)
{
bool bSuccess = false;
if(uncompress(cpData, &pzPacket->ulSize, pzPacket->baData, pzPacket->ulCompSize) == Z_OK)
{
uLong ulEndCrc = crc32(0, cpData, pzPacket->ulSize);
if(ulEndCrc == pzPacket->ulCrc)
{
bSuccess = true;
*ulpSize = pzPacket->ulSize;
if(ulpCrc != NULL)
*ulpCrc = ulEndCrc;
}
else
{
wprintf(L"crc error.\n");
if(ulpCrc != NULL)
*ulpCrc = 0;
}
}
else wprintf(L"inflate error.\n");
if(bSuccess == false)
{
free(cpData);
cpData = NULL;
*ulpSize = 0xFFFFFFFF;
}
}
else wprintf(L"decompbuf malloc(%d) error.\n", pzPacket->ulSize);
}
else wprintf(L"recv data buf not filled.\n");
}
else wprintf(L"zpacket realloc(%lld) error.\n", (sizeof(ZPACKET)-1)+pzPacket->ulCompSize);
}
else wprintf(L"recv hdr buf not filled.\n");
if(pzPacket != NULL)
free(pzPacket);
}
else wprintf(L"zpacket malloc(%zd) error.\n", sizeof(ZPACKET));
return cpData;
}
/* ========================================================================= */
uLongf senddeflate(Bytef *bpBuffer, uLong *ulpSize, SOCKET sSocket)
{
PZPACKET spData;
uLong ulSizeExtra = 12+(uLong)(*ulpSize*0.001);
uLong ulBufferSize = (sizeof(ZPACKET)-1)+*ulpSize+ulSizeExtra;
spData = (PZPACKET)malloc(ulBufferSize);
assert(spData != NULL);
spData->ulSize = *ulpSize;
spData->ulCrc = crc32(0, bpBuffer, *ulpSize);
spData->ulCompSize = ulBufferSize;
int iResult = compress2(spData->baData, &spData->ulCompSize, bpBuffer, *ulpSize, Z_BEST_COMPRESSION);
if(iResult != Z_OK)
{
*ulpSize = 0xFFFFFFFF;
return 0;
}
*ulpSize = spData->ulCompSize;
iResult = send(sSocket, (char*)spData, (sizeof(ZPACKET)-1)+spData->ulCompSize, 0);
free(spData);
return iResult;
}
/* ========================================================================= */
int InitWinSock(WORD wVersion)
{
wprintf(L"* Initialising WinSock with %x... ", wVersion);
WSADATA wsaData;
if(WSAStartup(wVersion, &wsaData) != 0)
{
wprintf(L"WinSock Init Failed.\n");
return -1;
}
if(wsaData.wVersion != wVersion)
{
wprintf(L"WinSock Version Mismatch, %x != %x.\n", wsaData.wVersion, wVersion);
return -2;
}
wprintf(L"Done!\n");
return 0;
}
/* ========================================================================= */
bool CloseSocket(SOCKET sSocket)
{
if(closesocket(sSocket) == SOCKET_ERROR)
{
wprintf(L"Error %u closing socket %llu:%p!\n", WSAGetLastError(), sSocket, &sSocket);
return false;
}
return true;
}
/* ========================================================================= */
SOCKET CreateSocket(void)
{
SOCKET sSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sSocket == INVALID_SOCKET)
wprintf(L"Error %u creating socket!\n", WSAGetLastError());
return sSocket;
}
/* ========================================================================= */
int MakeConnection(SOCKET sSocket, LPSOCKADDR_IN saAddr)
{
wprintf(L"* Connecting to %S:%d... ", inet_ntoa(saAddr->sin_addr), htons(saAddr->sin_port));
if(connect(sSocket, (LPSOCKADDR)saAddr, sizeof(SOCKADDR_IN)) == SOCKET_ERROR)
{
wprintf(L"failed %d.\n", WSAGetLastError());
return -1;
}
wprintf(L"Connected!\n");
return 0;
}
/* ========================================================================= */
int Resolve(char *cpAddr, LPSOCKADDR_IN saAddr)
{
saAddr->sin_family = AF_INET;
saAddr->sin_addr.s_addr = cpAddr == NULL ? INADDR_ANY : inet_addr(cpAddr);
if(saAddr->sin_addr.s_addr == INADDR_NONE)
{
wprintf(L"* Resolving %S... ", cpAddr);
HOSTENT *heAddr = gethostbyname(cpAddr);
if(heAddr == NULL)
{
wprintf(L"Could not resolve '%hs'! Error %u.\n", cpAddr,
WSAGetLastError());
return -1;
}
saAddr->sin_addr = *((LPIN_ADDR)*heAddr->h_addr_list);
wprintf(L"%S!\n", inet_ntoa(saAddr->sin_addr));
}
return 0;
}
/* ========================================================================= */
bool DoDownload(SOCKET, SOCKET sPSocket, void *vpPtr)
{
unsigned char bCommand = vpPtr != NULL ? *(unsigned char*)vpPtr : 'U';
PACKET pHeader;
int iBytes = recv(sPSocket, (char*)&pHeader, sizeof(PACKET), 0);
if(iBytes != sizeof(PACKET))
{
wprintf(L"Error %u downloading %i byte header.\n", WSAGetLastError(), iBytes);
return false;
}
if(pHeader.ulMagic != ulMagic)
{
wprintf(L"Not a valid archive file, %x != %x.\n", pHeader.ulMagic, ulMagic);
return false;
}
wprintf(L"* Archive has %i files of %i bytes.\n", pHeader.ulFiles, pHeader.ulUsage);
uLong ulIndex, ulBytes, ulUpdated = 0;
struct _wfinddata_t *fdpData;
intptr_t hFile = 0;
for(ulIndex = 0; ulIndex < pHeader.ulFiles; ++ulIndex)
{
fdpData = (struct _wfinddata_t*)recvinflate(&ulBytes, NULL, sPSocket);
if(fdpData == NULL)
{
ulIndex = 0xFFFFFFFF;
break;
}
bool bDoWriteFile = false;
FILE *fpFile;
char *cpData = NULL;
wprintf(L"# %c %u/%u +%s %u ", bCommand, ulIndex+1, pHeader.ulFiles, fdpData->name, fdpData->size);
if(bCommand == 'R' || bCommand == 'V')
{
cpData = (char *)recvinflate(&ulBytes, NULL, sPSocket);
if(cpData == NULL)
break;
bDoWriteFile = bCommand == 'R';
}
else if(_wfopen_s(&fpFile, fdpData->name, L"rb") == 0)
{
uLong ulCompCrc = 0;
cpData = (char *)recvinflate(&ulBytes, &ulCompCrc, sPSocket);
if(cpData == NULL)
break;
uLong ulCrc = 0;
Bytef caData[32768];
while(!feof(fpFile))
{
iBytes = (int)fread(caData, 1, sizeof(caData), fpFile);
ulCrc = crc32(ulCrc, caData, iBytes);
}
if(ulCrc != ulCompCrc)
bDoWriteFile = true;
_findclose(hFile);
}
else if(errno == ENOENT)
{
wprintf(L"FNF ");
cpData = (char *)recvinflate(&ulBytes, NULL, sPSocket);
if(cpData == NULL)
break;
bDoWriteFile = true;
}
if(bDoWriteFile == true)
{
wchar_t wcaTemp[_MAX_PATH];
_snwprintf_s(wcaTemp, _MAX_PATH, L"%s.tmp", fdpData->name);
buildpathstructure(wcaTemp);
if(_wfopen_s(&fpFile, wcaTemp, L"wb") == 0)
{
if(fwrite(cpData, 1, ulBytes, fpFile) != ulBytes)
wprintf(L"Can't write %s (%u).\n", fdpData->name, errno);
else
{
struct _utimbuf utData = { fdpData->time_write, fdpData->time_write };
if(_futime(_fileno(fpFile), &utData) != 0)
wprintf(L"Can't futime %s (%u).\n", fdpData->name, errno);
}
if(fclose(fpFile) == 0)
{
if(_wunlink(fdpData->name) != -1 || errno == ENOENT)
{
if(_wrename(wcaTemp, fdpData->name) != -1)
++ulUpdated;
else wprintf(L"Rename %s to %s failed (%u).\n", wcaTemp, fdpData->name, errno);
}
else wprintf(L"Unlink %s failed (%u).\n", fdpData->name, errno);
}
else wprintf(L"Can't close %s (%u).\n", fdpData->name, errno);
free(cpData);
wprintf(L"UPDATED!\n");
}
else
{
wprintf(L"Can't create %s (%u).\n", fdpData->name, errno);
break;
}
}
else wprintf(L"SAME!\n");
free(fdpData);
wprintf(L"%6.2f%%\b\b\b\b\b\b\b", (float)ulIndex / pHeader.ulFiles * 100);
}
wprintf(L"%d files updated.\n", ulUpdated);
return true;
}
/* ========================================================================= */
bool DoRefresh(SOCKET, SOCKET sPSocket, void *)
{
unsigned char bCommand = 'R';
return DoDownload(NULL, sPSocket, (void*)&bCommand);
}
/* ========================================================================= */
bool DoVerify(SOCKET, SOCKET sPSocket, void *)
{
unsigned char bCommand = 'V';
return DoDownload(NULL, sPSocket, (void*)&bCommand);
}
/* ========================================================================= */
bool DownloadRequest(SOCKET sSocket, SOCKET, void *vpParam)
{
if(sendf(sSocket, "RETR %s", (char *)vpParam) > 0)
return true;
return false;
}
/* ========================================================================= */
bool DoUpload(SOCKET sSocket, SOCKET sPSocket, void *)
{
bool bSuccess = false;
PFILERECORD frpPtr;
int iFiles, iUsage;
iFiles = iUsage = 0;
wchar_t wcaPath[_MAX_PATH];
memset(wcaPath, '\0', sizeof(wcaPath));
Recurse(wcaPath, 0, &iFiles, &iUsage);
wprintf(L"* Scan result... %i files of %i bytes\n", iFiles, iUsage);
if(iFiles > 0)
{
PACKET sData = { (uLong)ulMagic, (uLong)vData.iMajor, (uLong)vData.iMinor, (uLong)iFiles, (uLong)iUsage };
int iBytes = send(sPSocket, (char*)&sData, sizeof(PACKET), 0);
if(iBytes == sizeof(PACKET))
{
char *cpData;
FILE *fpFile;
uLong ulBytes;
int iNum = 0;
for(iNum = 0, frpPtr = frpFirst; frpPtr != NULL; frpPtr = frpPtr->frpNext, ++iNum)
{
wprintf(L"# U %u/%u +%s %u->", iNum+1, iFiles, frpPtr->fdData.name, frpPtr->fdData.size);
ulBytes = sizeof(struct _wfinddata_t);
iBytes = senddeflate((Bytef*)&frpPtr->fdData, &ulBytes, sPSocket);
if(iBytes == 0 || iBytes == SOCKET_ERROR)
{
wprintf(L"SENDHDRFAIL %u!\n", WSAGetLastError());
iNum = -1;
break;
}
if(_wfopen_s(&fpFile, frpPtr->fdData.name, L"rb") == 0)
{
cpData = new char[frpPtr->fdData.size];
fread(cpData, 1, frpPtr->fdData.size, fpFile);
ulBytes = frpPtr->fdData.size;
iBytes = senddeflate((Bytef*)cpData, &ulBytes, sPSocket);
if(iBytes == 0 || iBytes == SOCKET_ERROR)
{
wprintf(L"SENDDATAFAIL %u!\n", WSAGetLastError());
iNum = -1;
break;
}
delete []cpData;
fclose(fpFile);
wprintf(L"%u DONE!\n", ulBytes);
}
else
{
wprintf(L"FILEOPENERR %u!\n", errno);
sendf(sSocket, "ABOR");
break;
}
}
if(iNum > 0)
{
wprintf(L"* Archive updated.\n");
bSuccess = true;
}
}
else wprintf(L"Send archive header error, aborting transfer.\n");
}
else wprintf(L"No files to archive, aborting transfer.\n");
for(frpPtr = frpFirst; frpPtr != NULL; frpPtr = frpFirst)
{
frpFirst = frpPtr->frpNext;
delete frpPtr;
}
return bSuccess;
}
/* ========================================================================= */
bool UploadRequest(SOCKET sSocket, SOCKET, void *vpParam)
{
if(sendf(sSocket, "STOR %s", (char *)vpParam) > 0)
return true;
return false;
}
/* ========================================================================= */
bool DoDelete(SOCKET sSocket, SOCKET, void *vpParam)
{
if(sendf(sSocket, "DELE %s", (char *)vpParam) > 0)
return true;
return false;
}
/* ========================================================================= */
bool SetPassiveMode(SOCKET sSocket, SOCKET, void *)
{
if(sendf(sSocket, "PASV") > 0)
return true;
return false;
}
/* ========================================================================= */
bool DoQuit(SOCKET sSocket, SOCKET, void *)
{
if(sendf(sSocket, "QUIT") > 0)
return true;
return false;
}
/* ========================================================================= */
unsigned char GetPassword(char *cpBuffer, unsigned char bMaxSize)
{
unsigned char bChar = 0xFF;
unsigned char bLength = 0;
unsigned char bIndex;
while(bChar != 0)
{
for(bIndex = 0; bIndex < bLength; ++bIndex)
wprintf(L"*");
wprintf(L" ");
for(bIndex = 0; bIndex < bLength+1; ++bIndex)
wprintf(L"\b");
bChar = (unsigned char)_getch();
while(_kbhit() != 0) _getch();
switch(bChar)
{
case 27:
memset(cpBuffer, '\0', bMaxSize);
case '\r':
case '\n':
bChar = 0;
break;
case '\b':
if(bLength > 0)
cpBuffer[bLength--] = '\0';
else Beep(800,250);
break;
default:
if(isalnum(bChar))
if(bLength < bMaxSize)
*(unsigned short*)&cpBuffer[bLength++] = MAKEWORD(bChar, 0);
else Beep(800,250);
else Beep(800,250);
break;
}
}
wprintf(L"\n");
return bLength;
}
/* ========================================================================= */
int ProcessDB(char *cpDb, char *cpAddr, short wPort, char *cpUser, char *cpPassword, char *cpDirectory, PDBFUNC fFileCmd, PDBFUNC fFileGoCmd, PDBFUNC fFirstOkFunc, PDBFUNC fSecondOkFunc)
{
if(InitWinSock(MAKEWORD(1,1)) >= 0)
{
SOCKADDR_IN saAddr;
saAddr.sin_port = htons(wPort);
if(Resolve(cpAddr, &saAddr) >= 0)
{
SOCKET sSocket = CreateSocket();
if(sSocket != INVALID_SOCKET)
{
if(MakeConnection(sSocket, &saAddr) >= 0)
{
int iBytes, iNumeric;
char caBuffer[RECV_BUF];
char *cpPid, *cpRest;
SOCKET sPSocket = 0;
SOCKADDR_IN saPAddr;
for(;;)
{
memset(caBuffer, '\0', sizeof(caBuffer));
iBytes = recv(sSocket, caBuffer, sizeof(caBuffer), 0);
if(iBytes == SOCKET_ERROR || iBytes <= 0)
{
wprintf(L"* Receive error %u! disconnecting...\n", WSAGetLastError());
break;
}
if(strtok_s(caBuffer, " \r\n", &cpPid) == NULL)
{
wprintf(L"* Received invalid response (1) from server! Disconnecting...\n");
break;
}
cpRest = strtok_s(NULL, "\r\n", &cpPid);
if(cpRest == NULL)
{
wprintf(L"* Received invalid response (2) from server! Disconnecting...\n");
break;
}
wprintf(L"<-- %S %S\n", caBuffer, cpRest);
iNumeric = atoi(caBuffer);
if(iNumeric <= 0)
{
wprintf(L"* Received invalid numeric from server! Disconnecting...\n");
break;
}
else if(iNumeric == 150)
{
if(fFileGoCmd != NULL && fFileGoCmd(sSocket, sPSocket, NULL) == false)
sendf(sSocket, "ABOR");
CloseSocket(sPSocket);
}
else if(iNumeric == 200)
sendf(sSocket, "CWD %s", cpDirectory);
else if(iNumeric == 220)
sendf(sSocket, "USER %s", cpUser);
else if(iNumeric == 221)
break;
else if(iNumeric == 226)
{
if(DoQuit(sSocket, NULL, NULL) == false)
break;
}
else if(iNumeric == 227)
{
sPSocket = CreateSocket();
if(sPSocket < 0)
break;
memcpy(&saPAddr, &saAddr, sizeof(SOCKADDR_IN));
char *cpData = strtok_s(cpRest, "(", &cpPid);
cpData = strtok_s(NULL, ",", &cpPid);
cpData = strtok_s(NULL, ",", &cpPid);
cpData = strtok_s(NULL, ",", &cpPid);
cpData = strtok_s(NULL, ",", &cpPid);
cpData = strtok_s(NULL, ",", &cpPid);
char bByte1 = (char)atoi(cpData);
cpData = strtok_s(NULL, ")", &cpPid);
char bByte2 = (char)atoi(cpData);
short sPPort = MAKEWORD(bByte2,bByte1);
saPAddr.sin_port = htons(sPPort);
if(MakeConnection(sPSocket, &saPAddr) < 0)
break;
if(fFileCmd != NULL && fFileCmd(sSocket, sPSocket, (void*)cpDb) == false)
{
CloseSocket(sPSocket);
sendf(sSocket, "ABOR");
}
}
else if(iNumeric == 230)
sendf(sSocket, "TYPE I");
else if(iNumeric == 250)
{
if(fFirstOkFunc != NULL)
{
bool bBreak = false;
if(fFirstOkFunc(sSocket, sPSocket, (void*)cpDb) == false)
bBreak = true;
fFirstOkFunc = NULL;
if(bBreak == true)
break;
}
else if(fSecondOkFunc != NULL)
{
bool bBreak = false;
if(fSecondOkFunc(sSocket, sPSocket, (void*)cpDb) == false)
bBreak = true;
fSecondOkFunc = NULL;
if(bBreak == true)
break;
}
}
else if(iNumeric == 331)
{
char caPassword[60];
memset(caPassword, '\0', sizeof(caPassword));
if(*cpPassword == '@')
{
wprintf(L"* Enter password: ");
GetPassword(caPassword, sizeof(caPassword));
}
else strcpy_s(caPassword, sizeof(caPassword), cpPassword);
sendfhidden(sSocket, "PASS %s", caPassword);
memset(caPassword, '\0', sizeof(caPassword));
}
else if(iNumeric >= 400)
sendf(sSocket, "QUIT");
}
wprintf(L"* Disconnected from server.\n");
}
CloseSocket(sSocket);
}
}
WSACleanup();
}
return 0;
}
/* ========================================================================= */
int isvalidpath(char *cpAddr)
{
char *cpAddrPtr;
int iCount;
for(cpAddrPtr = cpAddr, iCount = 0; *cpAddrPtr != '\0'; ++cpAddrPtr, ++iCount)
switch(*cpAddrPtr)
{
case '/' : break;
case '.' : break;
case '_' : break;
case '-' : break;
default : if(!isalnum(*cpAddrPtr)) return -1; break;
}
if(iCount > _MAX_PATH)
return -2;
return 0;
}
/* ========================================================================= */
int isvalidhost(char *cpAddr)
{
char *cpAddrPtr;
int iCount;
for(cpAddrPtr = cpAddr, iCount = 0; *cpAddrPtr != '\0'; ++cpAddrPtr, ++iCount)
switch(*cpAddrPtr)
{
case '.' : break;
case '_' : break;
case '-' : break;
default : if(!isalnum(*cpAddrPtr)) return -1; break;
}
if(iCount > _MAX_PATH)
return -2;
return 0;
}
/* ========================================================================= */
char *mystrlwr(char *cpString)
{
char *cpPtr;
for(cpPtr = cpString; *cpPtr != '\0'; ++cpPtr)
*cpPtr = (char)tolower(*cpPtr);
return cpString;
}
/* ========================================================================= */
char *mystrupr(char *cpString)
{
char *cpPtr;
for(cpPtr = cpString; *cpPtr != '\0'; ++cpPtr)
*cpPtr = (char)toupper(*cpPtr);
return cpString;
}
/* ========================================================================= */
int _cdecl main(int argc, char **argv)
{
wprintf(L"FtpSync(tm) %d.%d-%d-%d compiled %S by Mhatxotic Design.\n\n",
vData.iMajor, vData.iMinor, vData.iComp, vData.iBits, vData.cpComp);
if(argc == 1 || !*argv[1])
wprintf(L"Usage: FTPSYNC [command] [file] [addr] [port] [user] [pass|@] [root]\n"
L"\n"
L"[command] = Command you want the application to perform...\n"
L" CREATE Create a new archive on the FTP server.\n"
L" DELETE Delete the archive on the FTP server.\n"
L" REFRESH Download archive and overwrite all files on disk.\n"
L" UPDATE Download archive and overwrite changed files on disk.\n"
L" VERIFY Download archive and make no changes to files on disk.\n"
L"[file] = Filename of the archive to use.\n"
L"[addr] = Hostname or IP address of the FTP server to connect to.\n"
L"[port] = Port number to connect to (usually 21).\n"
L"[user] = Username account on the FTP server.\n"
L"[pass] = Password to the user's account on the FTP server (@=prompt).\n"
L"[root] = Directory to upload the archive to.\n");
else if(argc == 2 || !*argv[2])
wprintf(L"archive not specified. Type FTPSYNC without parameters for usage.\n");
else if(argc == 3 || !*argv[3])
wprintf(L"Address not specified. Type FTPSYNC without parameters for usage.\n");
else if(argc == 4 || !*argv[4])
wprintf(L"Port not specified. Type FTPSYNC without parameters for usage.\n");
else if(argc == 5 || !*argv[5])
wprintf(L"Username not specified. Type FTPSYNC without parameters for usage.\n");
else if(argc == 6 || !*argv[6])
wprintf(L"Password not specified. Type FTPSYNC without parameters for usage.\n");
else if(argc == 7 || !*argv[7])
wprintf(L"Directory not specified. Type FTPSYNC without parameters for usage.\n");
else if(argc > 8)
wprintf(L"Too many parameters. Type FTPSYNC without parameters for usage.\n");
else if(isvalidhost(mystrlwr(argv[2])) < 0)
wprintf(L"The archive specified is invalid or too long.\n");
else if(isvalidhost(argv[3]) < 0)
wprintf(L"The address specified is invalid or too long.\n");
else if(atoi(argv[4]) < 1 || atoi(argv[4]) > 65535)
wprintf(L"The port specified is invalid or out of range.\n");
else if(isvalidhost(argv[5]) < 0)
wprintf(L"The username specified is invalid or too long.\n");
else if(isvalidhost(argv[6]) < 0 && *argv[6] != '@')
wprintf(L"The password specified is invalid or too long.\n");
else if(isvalidpath(argv[7]) < 0)
wprintf(L"The root path specified is invalid or too long.\n");
else if(strcmp(mystrupr(argv[1]), "CREATE") == 0)
ProcessDB(argv[2], argv[3], (short)atoi(argv[4]), argv[5], argv[6], argv[7], UploadRequest, DoUpload, SetPassiveMode, NULL);
else if(strcmp(argv[1], "DELETE") == 0)
ProcessDB(argv[2], argv[3], (short)atoi(argv[4]), argv[5], argv[6], argv[7], NULL, NULL, DoDelete, DoQuit);
else if(strcmp(argv[1], "UPDATE") == 0)
ProcessDB(argv[2], argv[3], (short)atoi(argv[4]), argv[5], argv[6], argv[7], DownloadRequest, DoDownload, SetPassiveMode, NULL);
else if(strcmp(argv[1], "REFRESH") == 0)
ProcessDB(argv[2], argv[3], (short)atoi(argv[4]), argv[5], argv[6], argv[7], DownloadRequest, DoRefresh, SetPassiveMode, NULL);
else if(strcmp(argv[1], "VERIFY") == 0)
ProcessDB(argv[2], argv[3], (short)atoi(argv[4]), argv[5], argv[6], argv[7], DownloadRequest, DoVerify, SetPassiveMode, NULL);
else
wprintf(L"Unknown command -- %S. Type FTPSYNC without parameters for usage.\n", argv[1]);
wprintf(L"\nProgram finished.\n");
return 1;
}
/* ========================================================================= */