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