-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathasync-ftp-client.c
1460 lines (1460 loc) · 41.1 KB
/
async-ftp-client.c
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
#include "winsock.h"
#include "winsockx.h"
#include "async-ftp-client.h"
#include "WSA_Xtra.h"
#include<windows.h>
#include<windowsx.h>
#include<stdio.h>
#include<dos.h>
#include<direct.h>
#include "resource.h"
#ifdef _WIN32
#include<io.h> /* Microsoft 32-bit FIND file structure */
#else
#include<direct.h> /* Microsoft 16-bit FIND file structure */
#endif
/* FTP command strings */
LPSTR aszFtpCmd[]={"","CWD","DELE","PASS","PORT","RETR","STOR","TYPE","USER","ABOR","LIST","PWD","QUIT"};
char szAppName[]="AC_FTP";
BOOL nAppState=NOT_CONNECTED; /*application state*/
BOOL bToNul=FALSE; /*get to NUL device file*/
BOOL bFromNul=FALSE; /*put from Nul device file*/
BOOL bIOBeep=FALSE; /*beep on FD_READ, FD_WRITE*/
BOOL bDebug=FALSE; /*debug output to WinDebug*/
BOOL bReAsync=TRUE; /*call WSAAsyncSelect after accept()*/
BOOL bLogFile=TRUE; /*write commands and replies to log file*/
SOCKET hCtrlSock=INVALID_SOCKET; /*Ftp control socket*/
SOCKET hLstnSock=INVALID_SOCKET; /*listening data socket*/
SOCKET hDataSock=INVALID_SOCKET; /*connected data socket*/
char szHost[MAXHOSTNAME]={0}; /*remote host name or address*/
char szUser[MAXUSERNAME]={0}; /*user id*/
char szPwrd[MAXPASSWORD]={0}; /*user password*/
SOCKADDR_IN stCLclName; /*control socket name(local client)*/
SOCKADDR_IN stCRmtName; /*control socket name(remote client)*/
SOCKADDR_IN stDLclName; /*data socket name(local client)*/
SOCKADDR_IN stDRmtName; /*data socket name(remote client)*/
char achInBuf[INPUT_SIZE]; /*network input data buffer*/
char achOutBuf[INPUT_SIZE]; /*network output buffer*/
char szFtpRply[RPLY_SIZE]={0}; /*FTP reply buffer*/
char szDataFile[MAXFILENAME]={0}; /*file name*/
char szFtpCmd[CMD_SIZE]={0}; /* FTP command buffer */
char achRplyBuf[BUF_SIZE]; /*reply display buffer*/
/* index=0 is waiting for a reply, whereas index=1 is next one to be sent (pending) */
FTPCMD astFtpCmd[MAX_CMDS]; /*FTP command queue*/
int nQLen; /*number of entries in FTP command queue*/
int nFtpRplyCode; /*FTP reply code from server*/
int iNextRply; /*index to next reply string*/
int iLastRply;
HFILE hDataFile=HFILE_ERROR; /*file handle for open data file*/
LONG lStartTime; /*start time for data transfer*/
LONG lByteCount;
char szLogFile[]="ac_ftp.log"; /*FTP command and reply log file*/
HFILE hLogFile=HFILE_ERROR;
/*---Function: WinMain()
Initialize and start message loop
*/
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int nCmdShow)
{
MSG msg;
int nRet;
lpszCmdLine=lpszCmdLine; /*avoid warning*/
hPrevInstance=hPrevInstance;
nCmdShow=nCmdShow;
hInst=hInstance; /*save instance handle*/
/*--Initialize WinSock DLL--*/
nRet=WSAStartup(WSA_VERSION,&stWSAData);
/* WSAStartup() returns error value if failed */
if(nRet!=0)
{
WSAperror(nRet,"WSAStartup()");
/*Don't ever dare to continue if we can't use a WinSock*/
}
else
{
DialogBox(hInst, MAKEINTRESOURCE(AC_FTP),NULL,Dlg_Main);
/*--release WinSock DLL --*/
nRet=WSACleanup();
if(nRet==SOCKET_ERROR)
WSAperror(WSAGetLastError(),"WSACleanup()");
}
return msg.wParam;
} /*end of WinMain() */
/*---Function: Dlg_Main()
Doing all the message procssing for the main dialog box
*/
BOOL CALLBACK Dlg_Main(HWND hDlg,UINT msg,UINT wParam,LPARAM lParam)
{
int nAddrSize=sizeof(SOCKADDR);
WORD WSAEvent, WSAErr;
SOCKET hSock;
BOOL bOK, bRet=FALSE;
int nRet;
LONG lRet;
switch(msg)
{
case WSA_ASYNC+1;
/*Data socket async notification message handlers*/
hSock=(SOCKET)wParam; /*socket*/
WSAEvent=WSAGETSELECTEVENT(lParam); /*extract event*/
WSAErr=WSAGETSELECTERROR(lParam); /*extract error*/
/*if there is error, then display it to the user, hoping that 'listen socket' shouldn't be one of those culprits, but some Winsocks have a tiny possibility
*/
if((WSAErr) && (hSock==hDataSock))
{
int i,j;
for(i=0;j=WSAEvent;j;i++;j>>=1); /*convert bit into index*/
WSAperror(WSAErr,aszWSAEvent[i]);
}
switch(WSAEvent)
{
case FD_READ:
if(bIOBeep)
MessageBeep(0XFFFF);
if(hDataSock!=INVALID_SOCKET)
{
/*receive file data or directory list*/
RecvData(hDataSock,hDataFile,achInBuf,INPUT_SIZE);
}
break;
case FD_ACCEPT:
if(hLstnSock!=INVALID_SOCKET)
{
/*accept the incoming data connection request*/
hDataSock=AcceptDataConn(hLstnSock,&stDRmtName);
nAppState |= DATACONNECTED;
/*close the listening socket*/
closesocket(hLstnSock);
hLstnSock=INVALID_SOCKET;
lStartTime=GetTickCount();
/*data transfer should begin with FD_WRITE or FD_READ */
}
case FD_WRITE:
/*send file data*/
if(astFtpCmd[0].nFtpCmd==STOR)
{
lRet=SendData(&hDataSock,hDataFile,MTU_SIZE);
}
break;
case FD_CLOSE: /*data connection closed*/
if(hSock==hDataSock)
{
/*read remaining data into buffer and close connection*/
CloseConn(&hDataSock,(astFtpCmd[0].nFtpCmd!=STOR) ? achInBuf : (LPSTR)0, INPUT_SIZE,hDlg);
EndData();
}
break;
default:
break;
} /*end of switch(WSAEvent) */
break;
case WSA_ASYNC:
/*control socket async notification message handlers*/
WSAEvent=WSAGETSELECTEVENT(lParam); /*extract event*/
WSAErr=WSAGETSELECTERROR(lParam); /*extract error*/
if(WSAErr)
{
/*if error, then display*/
int i,j;
for(i=0;j=WSAEVENT;j;i++;j>>=1); /*convert bit into index*/
WSAperror(WSAErr,aszWSAEvent[i]);
}
hSock=(SOCKET)wParam;
switch(WSAEvent)
{
case FD_READ:
if(!iNextRply)
{
/*receive reply from server*/
iLastRply=RecvFtpRply(hCtrlSock,szFtpRply,RPLY_SIZE);
}
if(iLastRply && (iLastRply!=SOCKET_ERROR))
{
/*display the reply message*/
GetDlgItemText(hWinMain,IDC_REPLY,achRplyBuf,RPLY_SIZE-strlen(szFtpRply));
wsprintf(achTempBuf,"%s%s",stFtpRply,achRplyBuf);
SetDlgItemText(hWinMain,IDC_REPLY,achTempBuf);
/*save index to next reply*/
nRet=strlen(szFtpRply);
if(iLastRply > nRet+2)
{
iNextRply=nRet+3;
if(szFtpRply[nRet+2])
iNextRply=nRet+2;
}
}
/*reply based on last command*/
ProcessFtpRply(szFtpRply,RPLY_SIZE);
break;
case FD_WRITE:
/*send command to server*/
if(aszFtpCmd[1].nFtpCmd)
SendFtpCmd();
break;
case FD_CONNECT:
/*control connected at TCP level*/
nAppState=CTRLCONNECTED;
wsprintf(achTempBuf,"Server: %s", szHost);
SetDlgItemText(hDlg,IDC_SERVER,achTempBuf);
SetDlgItemText(hDlg,IDC_STATUS,"Status: connected");
break;
case FD_CLOSE:
if(nAppState & CTRLCONNECTED)
{
nAppState=NOT_CONNECTED; /*reset app status*/
AbortFtpCmd();
if(hCtrlSock!=INVALID_SOCKET) /*close control socket*/
CloseConn(&hCtrlSock, (PSTR)0, 0, hDlg);
SetDlgItemText(hDlg,IDC_SERVER,"server: none");
SetDlgItemText(hDlg,IDC_STATUS,"Status: not connected");
}
break;
default:
break;
} /*end of switch(WSAEvent) */
break;
case WM_COMMAND:
switch(wParam)
{
case IDC_CONNECT:
/*if we already have a socket, then tell user to close it*/
if(nAppState & CTRLCONNECTED)
{
MessageBox(hDlg,"close the active connection first","unable to connect",MB_OK | MB_ICONASTERISK);
}
else
{
/*prompt user for server and login user information*/
bOk=DialogBox(hInst,MAKEINTRESOURCE(IDD_SERVER),hDlg,Dlg_Login);
if(bOk)
{
/*check destination address and resolve if necessary*/
stCRmtName.sin_addr.s_addr=GetAddr(szHost);
if(stCRmtName.sin_addr.s_addr==INADDR_ANY)
{
/*tell user to enter an host*/
wsprintf(achTempBuf,"Sorry. server %s is invalid. Try again!",szHost);
MessageBox(hDlg,achTempBuf,"unable to connect!", MB_OK | MB_ICONASTERISK);
}
else
{
/*initialize connect attempt to server*/
hCtrlSock=InitCtrlConn(&stCRmtName,hDlg,WSA_ASYNC);
}
}
}
break;
case IDC_CLOSE:
if(nAppState & CTRLCONNECTED)
{
/*set application state, so nothing else is processed.*/
nAppState=NOT_CONNECTED;
if(hLstn!=INVALID_SOCKET)
{
closesocket(hLstnSock);
hLstnSock=INVALID_SOCKET;
}
/*if there is data connection, then abort it*/
if(hDataSock!=INVALID_SOCKET)
QueueFtpCmd(ABOR,0);
/*quit the control connection*/
if(hCtrlSock!=INVALID_SOCKET)
QueueFtpCmd(QUIT,0);
SetDlgItemText(hDlg,IDC_SERVER,"Server: None");
SetDlgItemText(hDlg,IDC_STATUS,"Status: Not connected");
}
break;
case IDC_RETR:
/*prompt for name of remote file to get*/
if(nAppState & CTRLCONNECTED)
{
bOk=DialogBox(hInst,MAKEINTRESOURCE(IDD_FILENAME),hDlg,Dlg_File);
if(bOk && szDataFile[0])
{
if(!bToNul)
{
hDatafile=CreateLclFile(szDataFile);
}
if(hDataFile!=HFILE_ERROR || bToNul)
{
/*tell the server where to connect back*/
hLstnSock=InitDataConn(&stDLclName,hDlg,WSA_ASYNC + 1);
if(hLstnSock!=INVALID_SOCKET)
{
/*Queue port. type and Retr cmd */
if(QueueFtpCmd(PORT,0))
{
if(QueueFtpCmd(TYPE,"I"))
QueueFtpCmd(RETR,szDataFile);
}
}
}
}
}
else
not_connected();
break;
case IDC_STOR:
/*prompt for name of the local file to send*/
if(nAppState & CTRLCONNECTED)
{
bOk=DialogBox(hInst,MAKEINTRESOURCE(IDD_FILENAME),hDlg,Dlg_File);
if(bOk && szDataFile[0])
{
if(!bFromNul)
{
/*if user provided file name, try to open it*/
hDataFile= _lopen(szDataFile, 0);
if(hDataFile==HFILE_ERROR)
{
wsprintf(achTempBuf,"Unable to open file: %s",szDataFile);
MessageBox(hWinMain,(LPSTR)achTempBuf,"File error", MB_OK | MB_ICONASTERISK);
}
}
if(hDataFile!=HFILE_ERROR || bFromNul)
{
/*tell server where to connect back*/
hLstnSock=InitDataConn(&stDLclName,hDlg,WSA_ASYNC + 1);
if(hLstnSock!=INVALID_SOCKET)
{
/*queue port,type and STOR cmds*/
if(QueueFtpCmd(PORT,0))
{
if(QueueFtpCmd(TYPE,"I"))
QueueFtpCmd(STOR,szDataFile);
}
}
}
}
}
else
not_connected();
break;
case IDC_ABOR:
if(hCtrlSock!=INVALID_SOCKET)
/*abort the pending FTP command*/
QueueFtpCmd(ABOR,0);
break;
case IDC_LCWD:
/*prompt for directory and move to it on local system*/
bOk=DialogBox(hInst,MAKEINTRESOURCE(IDD_FILENAME),hDlg,Dlg_File);
if(bOk && aszDataFile[0])
{
if(!(_chdir(szDataFile)))
{
getcwd(szDataFile,MAXFILENAME-1);
SetDlgItemText(hDlg,IDC_LPWD,szDataFile);
}
}
break;
case IDC_LDEL:
/*prompt for file name and delete it from local system*/
bOk=DialogBox(hInst,MAKEINTRESOURCE(IDD_FILENAME),hDlg,Dlg_File);
if(bOk && szDataFile[0])
{
/*if user provided file name, then delete it*/
remove(szDataFile);
}
break;
case IDC_LDIR:
/*get local file directory and display in notepad*/
if(GetLclDir(szTempFile))
{
wsprintf(achTempBuf,"notepad %s",szTempFile);
WinExec(achTempBuf,SW_SHOW);
}
break;
case IDC_RCWD:
/*prompt for directory and move to it on remote system*/
if(nAppState & CTRLCONNECTED)
{
szDataFile[0]=0;
bOk=DialogBox(hInst,MAKEINTRESOURCE(IDD_FILENAME),hDlg,Dlg_File);
if(bOk && szDataFile[0])
{
QueueFtpCmd(CWD,szDataFile);
}
}
else
not_connected();
break;
case IDC_RDEL:
/*prompt for file name and delete it from remote system*/
if(nAppState & CTRLCONNECTED)
{
szDataFile[0]=0;
bOk=DialogBox(hInst,MAKEINTRESOURCE(IDD_FILENAME),hDlg,Dlg_File);
if(bOk && szDataFile[0])
{
/*if user provided file name, send command to delete*/
QueueFtpCmd(DELE,szDataFile);
}
}
else
not_connected();
break;
case IDC_RDIR:
/*get remote file directory and display in notepad*/
if(nAppState & CTRLCONNECTED)
{
hDataFile=CreateLclFile(szTempFile);
if(hDataFile!=HFILE_ERROR)
{
/*prepare to receive connection from server*/
hLstnSock=InitDataConn(&stDLclName,hDlg,WSA_ASYNC + 1);
if(QueueFtpCmd(PORT,0))
if(QueueFtpCmd(TYPE,"A"))
QueueFtpCmd(LIST,0);
}
}
}
else
not_connected;
break;
case IDC_OPTIONS:
DialogBox(hInst,MAKEINTRESOURCE(IDD_OPTIONS),hDlg,Dlg_Options);
break;
case IDABOUT:
DialogBox(hInst,MAKEINTRESOURCE(IDD_ABOUT),hDlg,hDlg_About);
break;
case WM_DESTROY:
case IDC_EXIT:
SendMessage(hDlg,WM_COMMAND. IDC_CLOSE, 0L);
if(hLogFile!=HFILE_ERROR)
_lclose(hLogFile);
EndDialog(hDlg,msg);
bRet=TRUE;
break;
default:
break;
} /*end of case WM_COMMAND */
break;
case WM_INITDIALOG:
hWinMain=hDlg; /*save main window handle*/
/*assign an icon to dialog box*/
#ifdef WIN32
SetClassLong(hDlg,GCL_HICON,(LONG) LoadIcon((HINSTANCE) GetWindowLong(hDlg, GWL_HINSTANCE), __TEXT("AC_FTP")));
#else
SetClassWord(hDlg,GCW_HICON,(WORD) LoadIcon(hInst,MAKEINTRESOURCE(AC_FTP)));
#endif
/*initialize FTP command structure*/
memset(astFtpCmd,0,(sizeof(struct stFtpCmd)) *MAX_CMDS);
/*display current working directory*/
getcwd(szDataFile,MAXFILENAME-1);
SetDlgItemSet(hDlg,IDC_LPWD,szDataFile);
/*open log file, if logging enabled*/
if(bLogFile)
{
hLogFile= _lcreat (szLogFile,0);
if(hLogFile==HFILE_ERROR)
{
MessageBox(hWinMain,"unable to open log file","file error",MB_OK | MB_ICONASTERISK);
bLogFile=FALSE;
}
}
/*center dialog box*/
CenterWnd(hDlg,NULL,TRUE);
break;
default:
break;
} /*end of switch(msg)*/
return(bRet);
} /*end of DlgMain()*/
/*Function: Dlg_Options()
Allow user to change a number of run-time parameters that affect the operation, to allow experimentation & debugging.
*/
BOOL CALLBACK Dlg_Options(HWND hDlg,UINT msg,UINT wParam,LPARAM lParam)
{
BOOL bRet=FALSE;
lParam=lParam; /*avoid warning*/
switch(msg)
{
case WM_INITDIALOG:
CheckDlgButton(hDlg,IDC_TO_NUL,bToNul);
CheckDlgButton(hDlg,IDC_FROM_NUL,bFromNul);
CheckDlgButton(hDlg,IDC_LOGFILE,bLogFile);
CheckDlgButton(hDlg,IDC_IOBEEP,bIOBeep);
CheckDlgButton(hDlg,IDC_REASYNC,bReAsync);
CenterWnd(hDlg,hWinMain,TRUE);
break;
case WM_COMMAND:
switch(wParam)
{
case IDC_TO_NUL:
bToNul=!bToNul;
break;
case IDC_FROM_NUL:
bFromNul=!bFromNul;
break;
case IDC_LOGFILE:
bLogFile=!bLogFile;
break;
case IDC_IOBEEP:
bIOBeep=!bIOBeep;
break;
case IDC_REASYNC:
bReAsync=!bReAsync;
break;
case IDOK:
if(bLogFile && hLogFile == HFILE_ERROR)
{
bLogFile=FALSE;
}
else if(!bLogFile && hLogFile == HFILE_ERROR)
{
hLogFile= _lcreat(szLogFile,0);
if(hLogFile==HFILE_ERROR)
{
MessageBox(hWinMain,"unable to open log file","file error",MB_OK | MB_ICONASTERISK);
bLogFile=FALSE;
}
}
EndDialog(hDlg,TRUE);
bRet=TRUE;
break;
}
}
return(bRet);
} /*end of Dlg_Options*/
/*Function:- not_connected()
tell the user that the client needs a connection
*/
void not_connected(void)
{
MessageBox(hDlgMain,"Requires connection to FTP server","not connected",MB_OK | MB_ICONASTERISK);
}
/* Function: InitCtrlConn()
Get a TCP socket, register for async notification and then, connect to FTP server*/
SOCKET InitCtrlConn(PSOCKADDR_IN pstName, HWND hDlg, u_int nAsyncMsg)
{
int nRet;
SOCKET hCtrlSock;
/*get TCP socket for control connection*/
hCtrlSock=socket(AF_INET,SOCK_STREAM,0);
if(hCtrlSock==INVALID_SOCKET)
{
WSAperror(WSAGetLastError(),"socket()");
}
else
{
/*request async notifications for most events*/
nRet=WSAAsyncSelect(hCtrlSock,hDlg,nAsyncMsg,(FD_CONNECT | FD_READ | FD_WRITE | FD_CLOSE));
if(nRet==SOCKET_ERROR)
{
WSAperror(WSAGetLastError(),"WSAAsyncSelect()");
closesocket(hCtrlSock);
hCtrlSock=INVALID_SOCKET;
}
else
{
/*initiate non-blocking connect to server*/
pstName->sin_family=PF_INET;
pstName->sin_port=htons(IPPORT_FTP);
nRet=connect(hCtrlSock,(LPSOCKADDR)pstName,SOCKADDR_LEN);
if(nRet==SOCKET_ERROR)
{
int WSAErr=WSAGetLastError();
if(WSAErr!=WSAEWOULDBLOCK)
{
/*report error and clean up*/
WSAperror(WSAErr,"connect()");
closesocket(hCtrlSock);
hCtrlSock=INVALID_SOCKET;
}
}
}
}
return(hCtrlSock);
} /*end of InitCtrlConn()*/
/*--Function:- SendFtpCmd()
Format and send a FTP command to the server */
int SendFtpCmd(void)
{
int nRet,nLen,nBytesSent=0;
int nFtpCmd=astFtpCmd[1].nFtpCmd;
/*create a command string*/
if(szFtpCmd[0]==0)
{
switch(nFtpCmd)
{
case PORT:
wsprintf(szFtpCmd,"PORT %d,%d,%d,%d,%d,%d \r\n",
stDlclName.sin_addr.S_un.S_un_b.s_b1,/*local addr*/
stDlclName.sin_addr.S_un.S_un_b.s_b2,
stDlclName.sin_addr.S_un.S_un_b.s_b3,
stDlclName.sin_addr.S_un.S_un_b.s_b4,
stDlclName.sin_port & 0XFF, /*local port*/
(stDlclName.sin_port & 0XFF00)>>8);
break;
case CWD:
case DELE:
case PASS:
case RETR:
case STOR:
case TYPE:
case USER:
/*FTP command and parameter*/
wsprintf(szFtpCmd,"%s%s\r\n",aszFtpCmd[nFtpCmd],&(astFtpCmd[1].szFtpParm));
break;
case ABOR:
case LIST:
case PWD:
case QUIT:
/*solitary FTP command string (no parameters)*/
wsprintf(szFtpCmd,"%s\r\n",aszFtpCmd[nFtpCmd]);
break;
default:
return(0);
}
}
nLen=strlen(szFtpCmd);
if(hCtrlSock!=INVALID_SOCKET)
{
/*send FTP command to control socket*/
while(nBytesSent < nLen)
{
nRet=send(hCtrlSock,(LPSTR)szFtpCmd,nLen-nBytesSent,0);
if(nRet==SOCKET_ERROR)
{
int WSAErr=WSAGetLastError();
if(WSAErr!=WSAEWOULDBLOCK)
WSAperror(WSAErr,"SendFtpCmd()");
break;
}
nBytesSent+=nRet;
}
}
if(nBytes==nLen)
{
int i;
if(nFtpCmd==PASS) /*hide password*/
memset(szFtpCmd+5,'x',10);
if(bLogFile) /*log command*/
_lwrite(hLogFile,szFtpCmd,strlen(szFtpCmd));
GetDlgItemText(hWinMain,IDC_REPLY,/*display command*/ achRplyBuf,"%s%s",szFtpCmd,achRplyBuf);
SetDlgItemText(hWinMain,IDC_REPLY,achTempBuf);
szFtpCmd[0]=0; /*disable FTP command string*/
/*move everything up in the command queue*/
for(i=0;i<nQLen;i++)
{
astFtpCmd[i].nFtpCmd=astFtpCmd[i+1].nFtpCmd;
astFtp[i+1].nFtpCmd=0; /*reset old command*/
if(*(astFtpCmd[i+1].szFtpParm))
{
memcpy(astFtpCmd[i].szFtpParm,astFtpCmd[i+1].szFtpParm,CMD_SIZE);
*(astFtpCmd[i+1].szFtpParm)=0; /*terminate old string*/
}
else
{
*(astFtpCmd[i].szFtpParm)=0; /*terminate unused string*/
}
}
nQLen--; /*decrement the queue length*/
switch(nFtpCmd)
{
case(USER):
SetDlgItemText(hWinMain,IDC_STATUS,"Status:connecting");
break;
case(STOR):
SetDlgItemText(hWinMain,IDC_STATUS,"Status:sending a file");
break;
case(RETR):
SetDlgItemText(hWinMain,IDC_STATUS,"Status:receiving a file");
break;
case(LIST):
SetDlgItemText(hWinMain,IDC_STATUS,"Status:Receiving directory");
break;
case(QUIT):
SetDlgItemText(hWinMain,IDC_STATUS,"Server:None");
SetDlgItemText(hWinMain,IDC_STATUS,"Status:Not connected");
break;
}
}
return(nBytesSent);
} /*end of SendFtpCmd()*/
/*---Function: QueueFtpCmd()
Put FTP command in command queue for sending after we receive responses to pending commands*/
BOOL QueueFtpCmd(int nFtpCmd,LPSTR szFtpParm)
{
if((nFtpCmd==ABOR) || (nFtpCmd==QUIT))
{
AbortFtpCmd();
if(hCtrlSock!=INVALID_SOCKET)
SetDlgItemText(hWinMain,IDC_STATUS:"Status:Connected");
}
else if(nQLen==MAX_CMDS)
{
/*notify users if they fit in the queue*/
MessageBox(hWinMain, "FTP queue is full, try again later", "unable to queue command", MB_OK | MB_ICONASTERISK);
return(FALSE); /*not queued*/
}
nQLen++; /*increment FTP command counter*/
/*save command*/
astFtpCmd[nQLen].nFtpCmd=nFtpCmd;
if(szFtpParm)
lstrcpy(astFtpCmd[nQLen].szFtpParm,szFtpParm);
if(!(astFtpCmd[0].nFtpCmd) && astFtpCmd[1].nFtpCmd)
{
SendFtpCmd();
}
return(TRUE); /*queued!*/
} /*end of QueueFtpCmd() */
/*--Function: AbortFtpCmd()
Clean up routine to abort a pending FTP command and clear the command queue*/
void AbortFtpCmd(void)
{
int i;
if(hLstnSock!=INVALID_SOCKET)
/*closing the listen socket*/
closesocket(hLstnSock);
hLstnSock=INVALID_SOCKET;
}
if(hDataSock!=INVALID_SOCKET)
/*closing data socket*/
CloseConn(&hDataSock,(astFtpCmd[0].nFtpCmd!=STOR) ? achInBuf : (PSTR)0, INPUT_SIZE, hWinMain);
EndData();
}
for(i=0;i<MAX_CMDS;i++)
{
/*clear command queue*/
astFtpCmd[i].nFtpCmd=0;
nQLen=0;
} /*end of AbortFtpCmd()*/
/*--Function: RecvFtpRply()
Read the FTP reply from the server */
int RecvFtpRply(SOCKET hCtrlSock, LPSTR szFtpRply, int nLen)
{
int nRet=0;
if(hCtrlSock!=INVALID_SOCKET)
{
memset(szFtpRply,0,nLen); /*init receive buffer*/
/*reading*/
nRet=recv(hCtrlSock,(LPSTR)szFtpRply,nLen,0);
if(nRet==SOCKET_ERROR)
{
int WSAErr=WSAGetLastError();
if(WSAErr!=WSAEWOULDBLOCK)
{
WSAperror(WSAErr,"RecvFtpRply()");
}
}
else if(bLogFile) /*log reply*/
_lwrite(hLogFile,szFtpRply,nRet);
}
return(nRet);
} /*end of RecvFtpRply()*/
/*--Function: ProcessFtpRply()
Figuring out what happened and what to do next
*/
void ProcessFtpRply(LPSTR szRply, int nBufLen)
{
LPSTR szFtpRply;
int nPendingFtpCmd, i;
szFtpRply=szRply;
while((*(szFtpRply+3)=='-')||((*(szFtpRply)==' ')&&(*(szFtpRply+1)==' ')&&(*(szFtpRply+2)==' ')))
{
/*find end of reply line*/
for(i=0;*szFtpRply!=0X0a && *szFtpRply && i<nBufLen-3;szFtpRply++,i++);
szFtpRply++; /*goto beginning of next reply*/
if(!(*szFtpRply)) /*quit if end of string*/
return;
}
*szFtpCmd=0; /*disable old command string*/
nPendingFtpCmd=astFtpCmd[0].nFtpCmd; /*save last FTP command*/
if((*szFtpRply!='1')&&(nPendingFtpCmd!=LIST)&&(nPendingFtpCmd!=STOR)&&(nPendingFtpCmd!=RETR))
/*for any starter reply, clear old commands*/
astFtpCmd[0].nFtpCmd=0;
/*first digit in 3-digit FTP reply code is the most significant*/
switch(*szFtpRply)
{
case('1'): /*positive preliminary reply*/
break;
case('2'): /*positive completion reply*/
switch(nPendingFtpCmd)
{
case 0:
/*check if service ready for user*/
if((*(szFtpRply+1)=='2') && (*(szFtpRply+2)=='0'))
QueueFtpCmd(USER, szUser);
break;
case CWD:
case USER:
case PASS:
/*Duh-uh! We are logged in now fellas. Get remote working directory */
QueueFtpCmd(PWD,0);
break;
case PWD:
/*display remote working directory*/
SetDlgItemText(hWinMain,IDC_RPWD,&szFtpRply[4]);
break;
case TYPE:
case PORT:
/*send next command if it's already queued*/
SendFtpCmd();
break;
case ABOR:
/*close the data socket*/
if(hDataSock!=INVALID_SOCKET)
CloseConn(&hDataSock,(PSTR)0,0,hWinMain);
break;
case QUIT:
/*close the control socket*/
if(hCtrlSock!=INVALID_SOCKET)
CloseConn(&hCtrlSock,(PSTR)0,0,hWinMain);
break;
default:
break;
}
break;
case ('3'): /*positive intermediate reply*/
if(nPendingFtpCmd==USER)
QueueFtpCmd(PASS, szPwrd);
break;
case ('4'): /*transient negative completion reply*/
case ('5'): /*permanent negative completion reply*/
/*if port failed, forget about queued commands*/
if(nPendingFtpCmd!=ABOR)
QueueFtpCmd(ABOR,0);
break;
}
} /*end of ProcessFtpRply()*/
/*--Function: InitDataConn()
Setup a listening socket for data connection */
SOCKET InitDataConn(PSOCKADDR_IN lpstName,HWND hDlg,u_int nAsyncMsg)
{
int nRet;
SOCKET hLstnSock;
int nLen=SOCKADDR_LEN;
/*get a TCP socket to use for data connection listen*/
hLstnSock=socket(AF_INET,SOCK_STREAM,0);
if(hLstnSock==INVALID_SOCKET)
{
WSAperror(WSAGetLastError(),"socket()");
}
else
{
/*request async notification for most events*/
nRet=WSAAsyncSelect(hLstnSock,hDlg,nAsyncMsg,(FD_ACCEPT | FD_READ | FD_WRITE | FD_CLOSE));
if(nRet==SOCKET_ERROR)
{
WSAperror(WSAGetLastError(),"WSAAsyncSelect()");
}
else
{
/*name the local socket with bind()*/
lpstName->sin_family=PF_INET;
lpstName->sin_port=0;
nRet=bind(hLstnSock,(LPSOCKADDR)lpstName,SOCKADDR_LEN);
if(nRet==SOCKET_ERROR)
{
WSAperror(WSAGetLastError(),"bind()");
}
else
{
/*get local port number assigned by bind()*/
nRet=getsockname(hLstnSock,(LPSOCKADDR)lpstName,(int FAR *)&nLen);
if(nRet==SOCKET_ERROR)
{
WSAperror(WSAGetLastError(),"getsockname()");
}
else
{
/*listen for incoming connection requests*/
nRet=listen(hLstnSock,5);
if(nRet==SOCKET_ERROR)
{
WSAperror(WSAGetLastError(),"listen()");
}
}
}
}
/*if we haven't had error, also don't know local IP address, then we gotta try before we return*/
if(!lpstName->sin_addr.s_addr)
{
lpstName->sin_addr.s_addr=GetHostID( );
if(!lpstName->sin_addr.s_addr)
{
MessageBox(hDlg,"unable to get local IP address","InitConn( ) Failed", MB_OK | MB_ICONASTERISK);
nRet=SOCKET_ERROR;
}
}
/*if we get error and yet don't know our IP address, we are in deep shit. Clean up! */
if(nRet==SOCKET_ERROR)
{
closesocket(hLstnSock);
hLstnSock=INVALID_SOCKET;
}
}
return(hLstnSock);
} /*end of InitDataConn()*/
/*Sample libraries added:
1. CenterWnd() - Moves window to center of parent window
2. CloseConn() - standard TCP close/shutdown
3. CreateLclFile() - create a file on local system
4. Dlg_About() - displays contents
5. GetAddr() - returns address value for host name or address string
6. GetBuf() - Gets the largest possible send or receive buffer upto a limit
7. GetHostID() - Gets local IP address
8. GetLclDir() - Gets the file directory
9. GetPort() - Gets Port number
10. WSAErrStr() - Copies short error description for WinSock into a buffer
11. WSAperror() - Displays Winsock error value
*/
/*Function: CenterWnd()
Center window relative to the parent window */
void CenterWnd(HWND hWnd, HWND hParentWnd, BOOL bPaint)
{
RECT rc2, rc1;
RECT FAR, *lprc;
int nWidth, nHeight, cxCenter, cyCenter;
if(!hParentWnd) /*if we've no parent, then use desktop*/
hParentWnd=GetDesktopWindow();
GetWindowRect(hParentWnd,&rc2);
lprc=(RECT FAR *)&rc2;
cXCenter=lprc->left+((lprc->right-lprc->left)/2);
cyCenter=lprc->top+((lprc->bottom-lprc->top)/2);
MoveWindow(hWnd, cXCenter-(nWidtth/2), cyCenter-(nHeight/2), nWidth, nHeight, bPaint);
return;
} /*end of CenterWnd() */
/*Function: CloseConn()
Closing TCP connection, ensuring that no data loss can occur on WInSocks that post FD_CLOSE when data is still available to read
*/
int CloseConn(SOCKET hSock, LPSTR achInBuf, int len, HWND hWnd)
{
int nRet;
char achDiscard(BUF_SIZE);
int cbBytesToDo=len, cbBytesDone=0;
if(hSock!=INVALID_SOCKET)
{
/*disable asynchronous notification if window handle is provided*/
if(hWnd)
{
nRet=WSAAsyncSelect(hSock, hWnd, 0, 0);
if(nRet==SOCKET_ERROR)
WSAperror(WSAGetLastError(),"CloseConn() WSAAsyncSelect()");
}
/*half-closing the connecting*/
nRet=shutdown(hSock,l);
/*read remaining data*/
for(nRet=1;(nRet && (nRet!=SOCKET_ERROR));)
{
if(achInBuf)
{
nRet=recv(hSock,&achInBuf[cbBytesDone],cbBytesToDo,0);
if(nRet && (nRet!=SOCKET_ERROR))
{
cbBytesToDo-=nRet;
cbBytesDone+=nRet;
}
}
else
{
/*no buffer provided, so discard any data*/
nRet=recv(hSock,achDiscard,BUF_SIZE,0);
}
}
/*closing the socket*/
closesocket(hSock);
}
return(nRet);
} /*end of CloseConn()*/
/*Function: CreateLclFile()
Try to create a file on local system and notify user if fails and then prompt for new file name*/
HFILE CreateLclFile(LPSTR szFileName)
{
HFILE hFile;
char szRmtFile(MAXFILENAME);
hFile= _lcreat (szFileName, 0); /*creating the file*/
strcpy(szRmtFile,szFileName); /*save remote file name*/
while(hFile==HFILE_ERROR)
{
wsprintf(achTempBuf,"Unable to create the file %s, Change the file name", szFileName);
MessageBox(hWinMain,achTempBuf,"File Error",MB_OK | MB_ICONASTERISK);
if(!DialogBox(hInst,MAKEINTRESOURCE(IDD_FILENAME),hWinMain,Dlg_File))
{
/*no new file name is provided, so quit*/
break;
}
else
{
/*try creating a new file*/
hFile= _lcreat(szFileName, 0);
}
}
strcpy(szFileName,szRmtFile); /*replace remote filename*/
return hFile;
} /*end of CreateLclFile() */
/*Function: Dlg_About()
Displays and WinSock DLL info */
BOOL CALLBACK Dlg_About
{
HWND hDlg;
UINT msg;
UINT wParam;
LPARAM lParam;
{
char achDataBuf[WSADESCRIPTION_LEN+1];
lParam=lParam; /*avoid warning*/
switch(msg)
{
case WM_INITDIALOG:
wsprintf(achDataBuf,"(Compiled: %s, %s) \n",(LPSTR)__DATE__,(LPSTR)__Time__);