694f89ba053a572d8d16f961bd58df79e8363968
[mono.git] / mcs / class / System / System.Net.NetworkInformation / Ping.cs
1 //
2 // System.Net.NetworkInformation.Ping
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@novell.com)
6 //      Atsushi Enomoto (atsushi@ximian.com)
7 //
8 // Copyright (c) 2006-2007 Novell, Inc. (http://www.novell.com)
9 // Copyright 2015 Xamarin Inc.
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System;
32 using System.IO;
33 using System.Text;
34 using System.Diagnostics;
35 using System.Globalization;
36 using System.ComponentModel;
37 using System.Net.Sockets;
38 using System.Security.Principal;
39 using System.Security.Cryptography;
40 using System.Runtime.InteropServices;
41 using System.Threading;
42 using System.Threading.Tasks;
43
44 namespace System.Net.NetworkInformation {
45         [MonoTODO ("IPv6 support is missing")]
46         public class Ping : Component, IDisposable
47         {
48 #if !MONOTOUCH
49                 [StructLayout(LayoutKind.Sequential)]
50                 struct cap_user_header_t
51                 {
52                         public UInt32 version;
53                         public Int32 pid;
54                 };
55
56                 [StructLayout(LayoutKind.Sequential)]
57                 struct cap_user_data_t
58                 {
59                         public UInt32 effective;
60                         public UInt32 permitted;
61                         public UInt32 inheritable;
62                 }
63                 
64                 const int DefaultCount = 1;
65                 static readonly string [] PingBinPaths = new string [] {
66                         "/bin/ping",
67                         "/sbin/ping",
68                         "/usr/sbin/ping",
69 #if MONODROID
70                         "/system/bin/ping"
71 #endif
72                 };
73                 static readonly string PingBinPath;
74 #endif
75                 const int default_timeout = 4000; // 4 sec.
76                 ushort identifier;
77
78                 // This value is correct as of Linux kernel version 2.6.25.9
79                 // See /usr/include/linux/capability.h
80                 const UInt32 linux_cap_version = 0x20071026;
81                 
82                 static readonly byte [] default_buffer = new byte [0];
83                 static bool canSendPrivileged;
84                 
85
86                 BackgroundWorker worker;
87                 object user_async_state;
88                 CancellationTokenSource cts;
89                 
90                 public event PingCompletedEventHandler PingCompleted;
91
92 #if !MONOTOUCH
93                 static Ping ()
94                 {
95                         if (Environment.OSVersion.Platform == PlatformID.Unix) {
96                                 CheckLinuxCapabilities ();
97                                 if (!canSendPrivileged && WindowsIdentity.GetCurrent ().Name == "root")
98                                         canSendPrivileged = true;
99                         
100                                 // Since different Unix systems can have different path to bin, we try some
101                                 // of the known ones.
102                                 foreach (string ping_path in PingBinPaths)
103                                         if (File.Exists (ping_path)) {
104                                                 PingBinPath = ping_path;
105                                                 break;
106                                         }
107                         }
108                         else
109                                 canSendPrivileged = true;
110
111                         if (PingBinPath == null)
112                                 PingBinPath = "/bin/ping"; // default, fallback value
113                 }
114 #endif
115                 
116                 public Ping ()
117                 {
118                         // Generate a new random 16 bit identifier for every ping
119                         RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider ();
120                         byte [] randomIdentifier = new byte [2];
121                         rng.GetBytes (randomIdentifier);
122                         identifier = (ushort)(randomIdentifier [0] + (randomIdentifier [1] << 8));
123                 }
124
125 #if !MONOTOUCH
126                 [DllImport ("libc", EntryPoint="capget")]
127                 static extern int capget (ref cap_user_header_t header, ref cap_user_data_t data);
128
129                 static void CheckLinuxCapabilities ()
130                 {
131                         try {
132                                 cap_user_header_t header = new cap_user_header_t ();
133                                 cap_user_data_t data = new cap_user_data_t ();
134
135                                 header.version = linux_cap_version;
136
137                                 int ret = -1;
138
139                                 try {
140                                         ret = capget (ref header, ref data);
141                                 } catch (Exception) {
142                                 }
143
144                                 if (ret == -1)
145                                         return;
146
147                                 canSendPrivileged = (data.effective & (1 << 13)) != 0;
148                         } catch {
149                                 canSendPrivileged = false;
150                         }
151                 }
152 #endif
153                 
154                 void IDisposable.Dispose ()
155                 {
156                 }
157
158                 protected void OnPingCompleted (PingCompletedEventArgs e)
159                 {
160                         user_async_state = null;
161                         worker = null;
162                         cts = null;
163
164                         if (PingCompleted != null)
165                                 PingCompleted (this, e);
166                 }
167
168                 // Sync
169
170                 public PingReply Send (IPAddress address)
171                 {
172                         return Send (address, default_timeout);
173                 }
174
175                 public PingReply Send (IPAddress address, int timeout)
176                 {
177                         return Send (address, timeout, default_buffer);
178                 }
179
180                 public PingReply Send (IPAddress address, int timeout, byte [] buffer)
181                 {
182                         return Send (address, timeout, buffer, new PingOptions ());
183                 }
184
185                 public PingReply Send (string hostNameOrAddress)
186                 {
187                         return Send (hostNameOrAddress, default_timeout);
188                 }
189
190                 public PingReply Send (string hostNameOrAddress, int timeout)
191                 {
192                         return Send (hostNameOrAddress, timeout, default_buffer);
193                 }
194
195                 public PingReply Send (string hostNameOrAddress, int timeout, byte [] buffer)
196                 {
197                         return Send (hostNameOrAddress, timeout, buffer, new PingOptions ());
198                 }
199
200                 public PingReply Send (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options)
201                 {
202                         IPAddress [] addresses = Dns.GetHostAddresses (hostNameOrAddress);
203                         return Send (addresses [0], timeout, buffer, options);
204                 }
205
206                 static IPAddress GetNonLoopbackIP ()
207                 {
208                         foreach (IPAddress addr in Dns.GetHostByName (Dns.GetHostName ()).AddressList)
209                                 if (!IPAddress.IsLoopback (addr))
210                                         return addr;
211                         throw new InvalidOperationException ("Could not resolve non-loopback IP address for localhost");
212                 }
213
214                 public PingReply Send (IPAddress address, int timeout, byte [] buffer, PingOptions options)
215                 {
216                         if (address == null)
217                                 throw new ArgumentNullException ("address");
218                         if (timeout < 0)
219                                 throw new ArgumentOutOfRangeException ("timeout", "timeout must be non-negative integer");
220                         if (buffer == null)
221                                 throw new ArgumentNullException ("buffer");
222                         if (buffer.Length > 65500)
223                                 throw new ArgumentException ("buffer");
224                         // options can be null.
225
226 #if MONOTOUCH
227                         throw new InvalidOperationException ();
228 #else
229                         if (canSendPrivileged)
230                                 return SendPrivileged (address, timeout, buffer, options);
231                         return SendUnprivileged (address, timeout, buffer, options);
232 #endif
233                 }
234
235 #if !MONOTOUCH
236                 private PingReply SendPrivileged (IPAddress address, int timeout, byte [] buffer, PingOptions options)
237                 {
238                         IPEndPoint target = new IPEndPoint (address, 0);
239                         IPEndPoint client = new IPEndPoint (GetNonLoopbackIP (), 0);
240
241                         // FIXME: support IPv6
242                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp)) {
243                                 if (options != null) {
244                                         s.DontFragment = options.DontFragment;
245                                         s.Ttl = (short) options.Ttl;
246                                 }
247                                 s.SendTimeout = timeout;
248                                 s.ReceiveTimeout = timeout;
249                                 // not sure why Identifier = 0 is unacceptable ...
250                                 IcmpMessage send = new IcmpMessage (8, 0, identifier, 0, buffer);
251                                 byte [] bytes = send.GetBytes ();
252                                 s.SendBufferSize = bytes.Length;
253                                 s.SendTo (bytes, bytes.Length, SocketFlags.None, target);
254
255                                 DateTime sentTime = DateTime.Now;
256
257                                 // receive
258                                 bytes = new byte [100];
259                                 do {
260                                         EndPoint endpoint = client;
261                                         int error = 0;
262                                         int rc = s.ReceiveFrom_nochecks_exc (bytes, 0, 100, SocketFlags.None,
263                                                         ref endpoint, false, out error);
264
265                                         if (error != 0) {
266                                                 if (error == (int) SocketError.TimedOut) {
267                                                         return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
268                                                 }
269                                                 throw new NotSupportedException (String.Format ("Unexpected socket error during ping request: {0}", error));
270                                         }
271                                         long rtt = (long) (DateTime.Now - sentTime).TotalMilliseconds;
272                                         int headerLength = (bytes [0] & 0xF) << 2;
273                                         int bodyLength = rc - headerLength;
274
275                                         // Ping reply to different request. discard it.
276                                         if (!((IPEndPoint) endpoint).Address.Equals (target.Address)) {
277                                                 long t = timeout - rtt;
278                                                 if (t <= 0)
279                                                         return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
280                                                 s.ReceiveTimeout = (int) t;
281                                                 continue;
282                                         }
283
284                                         IcmpMessage recv = new IcmpMessage (bytes, headerLength, bodyLength);
285
286                                         /* discard ping reply to different request or echo requests if running on same host. */
287                                         if (recv.Identifier != identifier || recv.Type == 8) {
288                                                 long t = timeout - rtt;
289                                                 if (t <= 0)
290                                                         return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
291                                                 s.ReceiveTimeout = (int) t;
292                                                 continue; 
293                                         }
294
295                                         return new PingReply (address, recv.Data, options, rtt, recv.IPStatus);
296                                 } while (true);
297                         }
298                 }
299
300                 private PingReply SendUnprivileged (IPAddress address, int timeout, byte [] buffer, PingOptions options)
301                 {
302 #if MONO_FEATURE_PROCESS_START
303                         DateTime sentTime = DateTime.UtcNow;
304
305                         Process ping = new Process ();
306                         string args = BuildPingArgs (address, timeout, options);
307                         long trip_time = 0;
308
309                         ping.StartInfo.FileName = PingBinPath;
310                         ping.StartInfo.Arguments = args;
311
312                         ping.StartInfo.CreateNoWindow = true;
313                         ping.StartInfo.UseShellExecute = false;
314
315                         ping.StartInfo.RedirectStandardOutput = true;
316                         ping.StartInfo.RedirectStandardError = true;
317
318                         IPStatus status = IPStatus.Unknown;
319                         try {
320                                 ping.Start ();
321
322 #pragma warning disable 219
323                                 string stdout = ping.StandardOutput.ReadToEnd ();
324                                 string stderr = ping.StandardError.ReadToEnd ();
325 #pragma warning restore 219
326                                 
327                                 trip_time = (long) (DateTime.UtcNow - sentTime).TotalMilliseconds;
328                                 if (!ping.WaitForExit (timeout) || (ping.HasExited && ping.ExitCode == 2))
329                                         status = IPStatus.TimedOut;
330                                 else if (ping.ExitCode == 0)
331                                         status = IPStatus.Success;
332                                 else if (ping.ExitCode == 1)
333                                         status = IPStatus.TtlExpired;
334                         } catch {
335                         } finally {
336                                 if (!ping.HasExited)
337                                         ping.Kill ();
338                                 ping.Dispose ();
339                         }
340
341                         return new PingReply (address, buffer, options, trip_time, status);
342 #else
343                         throw new NotSupportedException ("Ping is not supported on this platform.");
344 #endif // MONO_FEATURE_PROCESS_START
345                 }
346 #endif // !MONOTOUCH
347
348                 // Async
349
350                 public void SendAsync (IPAddress address, int timeout, byte [] buffer, object userToken)
351                 {
352                         SendAsync (address, default_timeout, default_buffer, new PingOptions (), userToken);
353                 }
354
355                 public void SendAsync (IPAddress address, int timeout, object userToken)
356                 {
357                         SendAsync (address, default_timeout, default_buffer, userToken);
358                 }
359
360                 public void SendAsync (IPAddress address, object userToken)
361                 {
362                         SendAsync (address, default_timeout, userToken);
363                 }
364
365                 public void SendAsync (string hostNameOrAddress, int timeout, byte [] buffer, object userToken)
366                 {
367                         SendAsync (hostNameOrAddress, timeout, buffer, new PingOptions (), userToken);
368                 }
369
370                 public void SendAsync (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options, object userToken)
371                 {
372                         IPAddress address = Dns.GetHostEntry (hostNameOrAddress).AddressList [0];
373                         SendAsync (address, timeout, buffer, options, userToken);
374                 }
375
376                 public void SendAsync (string hostNameOrAddress, int timeout, object userToken)
377                 {
378                         SendAsync (hostNameOrAddress, timeout, default_buffer, userToken);
379                 }
380
381                 public void SendAsync (string hostNameOrAddress, object userToken)
382                 {
383                         SendAsync (hostNameOrAddress, default_timeout, userToken);
384                 }
385
386                 public void SendAsync (IPAddress address, int timeout, byte [] buffer, PingOptions options, object userToken)
387                 {
388                         if ((worker != null) || (cts != null))
389                                 throw new InvalidOperationException ("Another SendAsync operation is in progress");
390
391                         worker = new BackgroundWorker ();
392                         worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
393                                 try {
394                                         user_async_state = ea.Argument;
395                                         ea.Result = Send (address, timeout, buffer, options);
396                                 } catch (Exception ex) {
397                                         ea.Result = ex;
398                                 }
399                         };
400                         worker.WorkerSupportsCancellation = true;
401                         worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
402                                 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
403                                 OnPingCompleted (new PingCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state, ea.Result as PingReply));
404                         };
405                         worker.RunWorkerAsync (userToken);
406                 }
407
408                 // SendAsyncCancel
409
410                 public void SendAsyncCancel ()
411                 {
412                         if (cts != null) {
413                                 cts.Cancel ();
414                                 return;
415                         }
416
417                         if (worker == null)
418                                 throw new InvalidOperationException ("SendAsync operation is not in progress");
419                         worker.CancelAsync ();
420                 }
421
422 #if !MONOTOUCH
423                 // ICMP message
424
425                 class IcmpMessage
426                 {
427                         byte [] bytes;
428
429                         // received
430                         public IcmpMessage (byte [] bytes, int offset, int size)
431                         {
432                                 this.bytes = new byte [size];
433                                 Buffer.BlockCopy (bytes, offset, this.bytes, 0, size);
434                         }
435
436                         // to be sent
437                         public IcmpMessage (byte type, byte code, ushort identifier, ushort sequence, byte [] data)
438                         {
439                                 bytes = new byte [data.Length + 8];
440                                 bytes [0] = type;
441                                 bytes [1] = code;
442                                 bytes [4] = (byte) (identifier & 0xFF);
443                                 bytes [5] = (byte) ((int) identifier >> 8);
444                                 bytes [6] = (byte) (sequence & 0xFF);
445                                 bytes [7] = (byte) ((int) sequence >> 8);
446                                 Buffer.BlockCopy (data, 0, bytes, 8, data.Length);
447
448                                 ushort checksum = ComputeChecksum (bytes);
449                                 bytes [2] = (byte) (checksum & 0xFF);
450                                 bytes [3] = (byte) ((int) checksum >> 8);
451                         }
452
453                         public byte Type {
454                                 get { return bytes [0]; }
455                         }
456
457                         public byte Code {
458                                 get { return bytes [1]; }
459                         }
460
461                         public ushort Identifier {
462                                 get { return (ushort) (bytes [4] + (bytes [5] << 8)); }
463                         }
464
465                         public ushort Sequence {
466                                 get { return (ushort) (bytes [6] + (bytes [7] << 8)); }
467                         }
468
469                         public byte [] Data {
470                                 get {
471                                         byte [] data = new byte [bytes.Length - 8];
472                                         Buffer.BlockCopy (bytes, 8, data, 0, data.Length);
473                                         return data;
474                                 }
475                         }
476
477                         public byte [] GetBytes ()
478                         {
479                                 return bytes;
480                         }
481
482                         static ushort ComputeChecksum (byte [] data)
483                         {
484                                 uint ret = 0;
485                                 for (int i = 0; i < data.Length; i += 2) {
486                                         ushort us = i + 1 < data.Length ? data [i + 1] : (byte) 0;
487                                         us <<= 8;
488                                         us += data [i];
489                                         ret += us;
490                                 }
491                                 ret = (ret >> 16) + (ret & 0xFFFF);
492                                 return (ushort) ~ ret;
493                         }
494
495                         public IPStatus IPStatus {
496                                 get {
497                                         switch (Type) {
498                                         case 0:
499                                                 return IPStatus.Success;
500                                         case 3: // destination unreacheable
501                                                 switch (Code) {
502                                                 case 0:
503                                                         return IPStatus.DestinationNetworkUnreachable;
504                                                 case 1:
505                                                         return IPStatus.DestinationHostUnreachable;
506                                                 case 2:
507                                                         return IPStatus.DestinationProtocolUnreachable;
508                                                 case 3:
509                                                         return IPStatus.DestinationPortUnreachable;
510                                                 case 4:
511                                                         return IPStatus.BadOption; // FIXME: likely wrong
512                                                 case 5:
513                                                         return IPStatus.BadRoute; // not sure if it is correct
514                                                 }
515                                                 break;
516                                         case 11:
517                                                 switch (Code) {
518                                                 case 0:
519                                                         return IPStatus.TimeExceeded;
520                                                 case 1:
521                                                         return IPStatus.TtlReassemblyTimeExceeded;
522                                                 }
523                                                 break;
524                                         case 12:
525                                                 return IPStatus.ParameterProblem;
526                                         case 4:
527                                                 return IPStatus.SourceQuench;
528                                         case 8:
529                                                 return IPStatus.Success;
530                                         }
531                                         return IPStatus.Unknown;
532                                         //throw new NotSupportedException (String.Format ("Unexpected pair of ICMP message type and code: type is {0} and code is {1}", Type, Code));
533                                 }
534                         }
535                 }
536
537                 private string BuildPingArgs (IPAddress address, int timeout, PingOptions options)
538                 {
539                         CultureInfo culture = CultureInfo.InvariantCulture;
540                         StringBuilder args = new StringBuilder ();
541                         uint t = Convert.ToUInt32 (Math.Floor ((timeout + 1000) / 1000.0));
542                         bool is_mac = Platform.IsMacOS;
543                         if (!is_mac)
544                                 args.AppendFormat (culture, "-q -n -c {0} -w {1} -t {2} -M ", DefaultCount, t, options.Ttl);
545                         else
546                                 args.AppendFormat (culture, "-q -n -c {0} -t {1} -o -m {2} ", DefaultCount, t, options.Ttl);
547                         if (!is_mac)
548                                 args.Append (options.DontFragment ? "do " : "dont ");
549                         else if (options.DontFragment)
550                                 args.Append ("-D ");
551
552                         args.Append (address.ToString ());
553
554                         return args.ToString ();
555                 }
556 #endif // !MONOTOUCH
557
558                 public Task<PingReply> SendPingAsync (IPAddress address, int timeout, byte [] buffer)
559                 {
560                         return SendPingAsync (address, default_timeout, default_buffer, new PingOptions ());
561                 }
562
563                 public Task<PingReply> SendPingAsync (IPAddress address, int timeout)
564                 {
565                         return SendPingAsync (address, default_timeout, default_buffer);
566                 }
567
568                 public Task<PingReply> SendPingAsync (IPAddress address)
569                 {
570                         return SendPingAsync (address, default_timeout);
571                 }
572
573                 public Task<PingReply> SendPingAsync (string hostNameOrAddress, int timeout, byte [] buffer)
574                 {
575                         return SendPingAsync (hostNameOrAddress, timeout, buffer, new PingOptions ());
576                 }
577
578                 public Task<PingReply> SendPingAsync (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options)
579                 {
580                         IPAddress address = Dns.GetHostEntry (hostNameOrAddress).AddressList [0];
581                         return SendPingAsync (address, timeout, buffer, options);
582                 }
583
584                 public Task<PingReply> SendPingAsync (string hostNameOrAddress, int timeout)
585                 {
586                         return SendPingAsync (hostNameOrAddress, timeout, default_buffer);
587                 }
588
589                 public Task<PingReply> SendPingAsync (string hostNameOrAddress)
590                 {
591                         return SendPingAsync (hostNameOrAddress, default_timeout);
592                 }
593
594                 public Task<PingReply> SendPingAsync (IPAddress address, int timeout, byte [] buffer, PingOptions options)
595                 {
596                         if ((worker != null) || (cts != null))
597                                 throw new InvalidOperationException ("Another SendAsync operation is in progress");
598
599                         var task = Task<PingReply>.Factory.StartNew (
600                                 () => Send (address, timeout, buffer, options), cts.Token);
601
602                         task.ContinueWith ((t) => {
603                                 if (t.IsCanceled)
604                                         OnPingCompleted (new PingCompletedEventArgs (null, true, null, null));
605                                 else if (t.IsFaulted)
606                                         OnPingCompleted (new PingCompletedEventArgs (t.Exception, false, null, null));
607                                 else
608                                         OnPingCompleted (new PingCompletedEventArgs (null, false, null, t.Result));
609                         });
610
611                         return task;
612                 }
613         }
614 }