summaryrefslogtreecommitdiff
path: root/Noddybox.WindowsPhone.FTP/FTPClient.cs
blob: 1ae13cec98ee74d7f32ebf40a9f1eecf1aab2046 (plain)
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
// This file is part of the Noddybox.WindowsPhone C# suite.
//
// Noddybox.Emulation 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 3 of the License, or
// (at your option) any later version.
//
// Noddybox.Emulation 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 Noddybox.Emulation.  If not, see <http://www.gnu.org/licenses/>.
//
// Copyright (c) 2012 Ian Cowburn
//
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;

namespace Noddybox.WindowsPhone.Net
{
	/// <summary>
	/// Provides a simple FTP client interface.  Currently only supports IP4.
	/// </summary>
	public class FTPClient
	{
		// -------------------------------------------------
		// - PUBLIC MEMBERS                                -
		// -------------------------------------------------
		
		/// <summary>
		/// Transfer type
		/// </summary>
		public enum TransferType
		{
			/// <summary>
			/// ASCII Data
			/// </summary>
			ASCII,

			/// <summary>
			/// Binary (image) Data
			/// </summary>
			Binary
		};

		/// <summary>
		/// Default constructor
		/// </summary>
		public FTPClient(string server_address)
		{
			passive = false;
			connected = true;
			welcome = "";
			system = "unknown";
			type = TransferType.Binary;
			
			passiveAddress = IPAddress.Loopback;
			
			lastCode=-1;
			
			try
			{
				encode = new ASCIIEncoding();
				
				server = new ServerDialog();

				ServerDialog.Reply r;
				
				commandClient = new TcpClient(server_address,21);
				command = commandClient.GetStream();
				
				r = BareResult();
				
				if (r.Code != 220)
				{
					connected=false;
					commandClient=null;
					command=null;
				}
			}
			catch (SocketException e)
			{
				connected=false;
			}
		}

		/// <summary>
		/// Sets timeouts for the command connection
		/// </summary>		
		public void SetTimeouts(int recv_timeout,
		                        int send_timeout)
		{
			recvTimeout=recv_timeout;
			sendTimeout=send_timeout;
			
			if (connected)
			{
				commandClient.ReceiveTimeout=recv_timeout;
				commandClient.SendTimeout=send_timeout;
			}
		}
		
		/// <summary>
		/// Set/get whether to use passive mode
		/// </summary>
		public bool Passive
		{
			get {return passive;}
			
			set
			{
				passive=value;
			}
		}
		
		/// <summary>
		/// Set/get the IP address to offer in non-passive mode
		/// </summary>
		public IPAddress NonPassiveIP
		{
			get {return passiveAddress;}
			
			set
			{
				passiveAddress=value;
			}
		}
		
		/// <summary>
		/// Logon to the FTP server
		/// </summary>
		public bool Logon(string username,string password)
		{
			ServerDialog.Reply r;
			
			r=SendCommand("USER "+username);
				
			if (r.Code==331)
			{
				r=SendCommand("PASS "+password);
			}
				
			if (r.Code==230)
			{
				SendCommand("SYST");
			}
			else
			{
				return false;
			}
			
			return true;
		}
		
		/// <summary>
		/// Whether connected to the FTP server
		/// </summary>
		public bool Connected
		{
			get {return connected;}
		}
		
		/// <summary>
		/// The welcome text after logging on
		/// </summary>
		public string Welcome
		{
			get {return welcome;}
		}
		
		/// <summary>
		/// The system type.  Note the entire system response is
		/// returned.  If you want just the first word, string.split()
		/// it.
		/// </summary>
		public string System
		{
			get {return system;}
		}
		
		/// <summary>
		/// The transfer type
		/// </summary>
		public TransferType Type
		{
			get
			{
				return type;
			}
			
			set
			{
				type=value;

				switch(type)
				{
					case TransferType.ASCII:
						SendCommand("TYPE A");				
						break;
					
					case TransferType.Binary:
						SendCommand("TYPE I");
						break;
				}
			}
		}
		
		/// <summary>
		/// Get the current working directory
		/// </summary>
		public string Pwd
		{
			get
			{
				string pwd="";
				
				ServerDialog.Reply r=SendCommand("PWD");
					
				if (r.Code==257)
				{
					pwd=ParseQuote(r.Text);
				}
				
				return pwd;
			}
		}
		
		/// <summary>
		/// Change directory to the parent directory
		/// </summary>
		public bool CDUp()
		{
			return SendCommand("CDUP").Code==250;
		}
		
		/// <summary>
		/// Change directory
		/// </summary>
		public bool CD(string dir)
		{
			return SendCommand("CWD "+dir).Code==250;
		}
		
		/// <summary>
		/// Get a list of the filenames in the current directory
		/// </summary>
		public StringCollection Dir()
		{
			StringCollection l=new StringCollection();
			ServerDialog.Reply r;
			TransferType old_type=type;
			
			PrepareData();
			
			Type=TransferType.ASCII;
			
			r=SendCommand("NLST");
			
			if (r.Code==150 || r.Code==125)
			{
				OpenData();
				
				string s=GetDataString();
				string fn="";
				
				foreach (char c in s)
				{
					if (c=='\n')
					{
						l.Add(fn.TrimEnd(null));
						fn="";
					}
					else
					{
						fn+=c;
					}
				}

				CloseData();
			}
			
			BareResult();
			
			Type=old_type;
			
			return l;
		}
		
		/// <summary>
		/// Get a detailed list of the filenames in the current directory.
		/// The list returned is made up of FTPFile classes.
		/// </summary>
		public FTPFileCollection DirEx()
		{
			StringCollection l=Dir();
			FTPFileCollection al=new FTPFileCollection();
			
			foreach(string s in l)
			{
				FTPFile.FileType type=FTPFile.FileType.File;
				ulong size;
				
				// See if it's a directory by seeing if CD works
				//
				if (CD(s))
				{
					type=FTPFile.FileType.Dir;
					size=0;
					CDUp();
				}
				else
				{
					ServerDialog.Reply r;

					// Get the file size
					//
					r=SendCommand("SIZE "+s);
					
					if (r.Code==213)
					{
						size=Convert.ToUInt64(r.Text);
					}
					else
					{
						size=UInt64.MaxValue;
					}
				}
				
				al.Add(new FTPFile(s,type,size));
			}
			
			al.Sort();

			return al;
		}
		
		/// <summary>
		/// Delete a specified file
		/// </summary>
		public bool Delete(string name)
		{
			return SendCommand("DELE "+name).Code==250;
		}
		
		/// <summary>
		/// Delete a specified directory
		/// </summary>
		public bool Rmdir(string name)
		{
			return SendCommand("RMD "+name).Code==250;
		}
		
		/// <summary>
		/// Create a specified directory
		/// </summary>
		public bool Mkdir(string name)
		{
			return SendCommand("MKD "+name).Code==257;
		}
		
		/// <summary>
		/// Rename a specified file
		/// </summary>
		public bool Rename(string old_name, string new_name)
		{
			ServerDialog.Reply r;
			
			r=SendCommand("RNFR "+old_name);
			
			if (r.Code!=350)
			{
				return false;
			}
			
			r=SendCommand("RNTO "+new_name);
			
			if (r.Code!=250)
			{
				return false;
			}

			return true;
		}
		
		/// <summary>
		/// Gets a file as a byte array
		/// </summary>
		public byte[] Get(string name)
		{
			ArrayList al=new ArrayList();

			PrepareData();
			
			ServerDialog.Reply r=SendCommand("RETR "+name);
			
			if (r.Code==150 || r.Code==125)
			{
				OpenData();
				GetData(al);
				CloseData();
			}
			else
			{
				return null;
			}
			
			BareResult();
			
			// Surely there must be a better way...
			//
			int count=al.Count;
			byte[] file=new byte[count];
			
			for(int f=0;f<count;f++)
			{
				file[f]=(byte)al[f];
			}
			
			return file;
		}
		
		/// <summary>
		/// Gets a file and stores it in a local file
		/// </summary>
		public bool Get(string name, string local_name)
		{
			byte[] data=Get(name);
			
			if (data==null)
			{
				return false;
			}
			
			FileStream file=new FileStream(local_name,FileMode.Create);
			BinaryWriter bin=new BinaryWriter(file);
			
			bin.Write(data);
			
			bin.Close();
			
			return true;
		}
		
		/// <summary>
		/// Puts a file as a byte array
		/// </summary>
		public bool Put(string name, byte[] data)
		{
			PrepareData();
			
			ServerDialog.Reply r=SendCommand("STOR "+name);
			
			if (r.Code==150 || r.Code==125)
			{
				OpenData();
				PutData(data);
				CloseData();
			}
			else
			{
				return false;
			}
			
			r=BareResult();
			
			return r.Code==226;
		}
		
		/// <summary>
		/// Puts a file and from a local file
		/// </summary>
		public bool Put(string name, string local_name)
		{
			if (!File.Exists(local_name))
			{
				return false;
			}
			
			FileInfo info=new FileInfo(local_name);
			
			FileStream file=new FileStream(local_name,FileMode.Open,FileAccess.Read);
			BinaryReader bin=new BinaryReader(file);
			
			byte[] data=bin.ReadBytes((int)info.Length);
			bin.Close();
			
			return Put(name,data);
		}
		
		/// <summary>
		/// The last code returned by the server (see RFC 959)
		/// </summary>
		public int LastCode
		{
			get {return lastCode;}
		}
		
		/// <summary>
		/// Quit and disconnect from the server.
		/// </summary>
		public void Quit()
		{
			if (connected)
			{
				SendCommand("QUIT");
				command.Close();
			}
		}
		
		// -------------------------------------------------
		// - PRIVATE MEMBERS                               -
		// -------------------------------------------------

		private bool			connected;
		private TcpClient		commandClient;
		private Socket			data;
		private Socket			nonPassive;
		private IPEndPoint		dataAddr;
		private NetworkStream	command;
		private string			welcome;
		private string			system;
		private int				lastCode;
		private ServerDialog	server;
		private int				recvTimeout;
		private int				sendTimeout;
		private ASCIIEncoding	encode;
		private bool			passive;
		private TransferType	type;
		private IPAddress		passiveAddress;
		
		private string ParseQuote(string s)
		{
			string r="";
			bool in_quote=false;
			
			foreach (char c in s)
			{
				if (c=='\"')
				{
					in_quote=!in_quote;
				}
				else
				{
					if (in_quote)
					{
						r+=c;
					}
				}
			}
			
			return r;
		}
		
		private IPEndPoint ParseAddress(string s)
		{
			string r="";
			bool in_quote=false;
			
			foreach (char c in s)
			{
				if (c=='(' || c==')')
				{
					in_quote=!in_quote;
				}
				else
				{
					if (in_quote)
					{
						r+=c;
					}
				}
			}
			
			char[] sep=new char[1] {','};
			string[] arg=r.Split(sep);
			
			if (arg.Length!=6)
			{
				throw new NetException(NetException.Type.FTP_BadReplyAddress);
			}
			
			int port=Convert.ToInt32(arg[4])*256+Convert.ToInt32(arg[5]);
			
			IPEndPoint ip=new IPEndPoint(IPAddress.Parse(arg[0] + "." +
														 arg[1] + "." +
														 arg[2] + "." +
														 arg[3]),
										 port);
			
			return ip;
		}
		
		private void PrepareData()
		{
			if (passive)
			{
				ServerDialog.Reply r=SendCommand("PASV");
				
				if (r.Code!=227)
				{
					throw new NetException(NetException.Type.FTP_NoPassive);
				}
				
				dataAddr=ParseAddress(r.Text);
				
				DebugOut("PASV told to use " + dataAddr.ToString());
				
				data=new Socket(AddressFamily.InterNetwork,
				                  SocketType.Stream,
				                  ProtocolType.Tcp);
				
				data.Connect(dataAddr);
			}
			else
			{
				if (nonPassive==null)
				{
					try
					{
						nonPassive=new Socket(AddressFamily.InterNetwork,
								                SocketType.Stream,
								                ProtocolType.Tcp);
					
						if (passiveAddress==IPAddress.None)
						{
							IPAddress[] host=Dns.Resolve(Dns.GetHostName()).AddressList;
							
							if (host.Length==0)
							{
								throw new NetException(NetException.Type.ALL_NoLocalIP);
							}

							passiveAddress=host[0];
						}
						
						IPEndPoint ep=new IPEndPoint(passiveAddress,0);

						nonPassive.Bind(ep);
						
						ep=(IPEndPoint)nonPassive.LocalEndPoint;
						
						byte[] a=ep.Address.GetAddressBytes();
						int p=ep.Port;
						
						int p1=p>>8;
						int p2=p&0xff;
						
						string portCmd="PORT " +
										a[0].ToString() + "," +
										a[1].ToString() + "," +
										a[2].ToString() + "," +
										a[3].ToString() + "," +
										p1.ToString() + "," +
										p2.ToString();
						
						ServerDialog.Reply r=SendCommand(portCmd);
						
						if (r.Code!=200)
						{
							nonPassive.Close();
							nonPassive=null;
							throw new NetException
									(NetException.Type.FTP_NonPassiveProblem);
						}
						
						nonPassive.Listen(5);
					}
					catch (SocketException e)
					{
						nonPassive=null;
						throw e;
					}
				}
			}
		}
		
		private void OpenData()
		{
			if (passive)
			{
				// Connection already created by PrepareData()
			}
			else
			{
				// TODO : This could actually block indefinitely
				//
				data=nonPassive.Accept();
				
				if (data==null)
				{
					throw new NetException
									(NetException.Type.FTP_NonPassiveProblem);
				}
			}
		}
		
		private void CloseData()
		{
			DebugOut("Closing data connection");

			data.Shutdown(SocketShutdown.Both);
			data.Close();
			data=null;
			
			if (!passive)
			{
				DebugOut("Closing non-passive listener");

				nonPassive.Close();
				nonPassive=null;
			}
		}
		
		private string GetDataString()
		{
			byte[] buff=new byte[1024];
			string result="";
			
			while(true)
			{
				int len=data.Receive(buff,buff.Length,SocketFlags.None);
				
				DebugOut("Read " + len.ToString() + " bytes from data connection");
				
				if (len==0)
				{
					break;
				}
				
				result+=encode.GetString(buff,0,len);
			}
			
			DebugOut("Read string '" + result + "' data connection");
				
			return result;
		}
		
		private void GetData(ArrayList al)
		{
			byte[] buff=new byte[1024];

			while(true)
			{
				int len=data.Receive(buff,buff.Length,SocketFlags.None);
				
				DebugOut("Read " + len.ToString() + " bytes from data connection");
				
				if (len==0)
				{
					break;
				}

				// This whole idea needs sorting - this will be painful
				//
				for(int f=0;f<len;f++)
				{
					al.Add(buff[f]);
				}
			}
		}
		
		private void PutData(byte[] data)
		{
			int len=0;
			
			while(len<data.Length)
			{
				len+=data.Send(data,len,data.Length-len,SocketFlags.None);
			}
		}
		
		private ServerDialog.Reply SendCommand(string command)
		{
			ServerDialog.Reply r=new ServerDialog.Reply();
			
			command+="\r\n";
			
			if (connected)
			{
				r=server.Send(command,command);
				StoreResult(r);
			}

			return r;
		}
		
		private ServerDialog.Reply BareResult()
		{
			ServerDialog.Reply r=new ServerDialog.Reply();
			
			if (connected)
			{
				r=server.Send(command,null);
				StoreResult(r);
			}

			return r;
		}
		
		private void StoreResult(ServerDialog.Reply r)
		{
			if (r.Code>-1)
			{
				lastCode=r.Code;
			}
			
			switch(r.Code)
			{
				case 215:
					system = r.Text;
					break;
				
				case 230:
					welcome = r.Text;
					break;
				
				default:
					break;
			}
		}
	}
}