Merge pull request #3647 from BrzVlad/fix-sgen-internal-alloc
[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
163                         if (cts != null) {
164                                 cts.Dispose();
165                                 cts = null;
166                         }
167
168                         if (PingCompleted != null)
169                                 PingCompleted (this, e);
170                 }
171
172                 // Sync
173
174                 public PingReply Send (IPAddress address)
175                 {
176                         return Send (address, default_timeout);
177                 }
178
179                 public PingReply Send (IPAddress address, int timeout)
180                 {
181                         return Send (address, timeout, default_buffer);
182                 }
183
184                 public PingReply Send (IPAddress address, int timeout, byte [] buffer)
185                 {
186                         return Send (address, timeout, buffer, new PingOptions ());
187                 }
188
189                 public PingReply Send (string hostNameOrAddress)
190                 {
191                         return Send (hostNameOrAddress, default_timeout);
192                 }
193
194                 public PingReply Send (string hostNameOrAddress, int timeout)
195                 {
196                         return Send (hostNameOrAddress, timeout, default_buffer);
197                 }
198
199                 public PingReply Send (string hostNameOrAddress, int timeout, byte [] buffer)
200                 {
201                         return Send (hostNameOrAddress, timeout, buffer, new PingOptions ());
202                 }
203
204                 public PingReply Send (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options)
205                 {
206                         IPAddress [] addresses = Dns.GetHostAddresses (hostNameOrAddress);
207                         return Send (addresses [0], timeout, buffer, options);
208                 }
209
210                 static IPAddress GetNonLoopbackIP ()
211                 {
212                         foreach (IPAddress addr in Dns.GetHostByName (Dns.GetHostName ()).AddressList)
213                                 if (!IPAddress.IsLoopback (addr))
214                                         return addr;
215                         throw new InvalidOperationException ("Could not resolve non-loopback IP address for localhost");
216                 }
217
218                 public PingReply Send (IPAddress address, int timeout, byte [] buffer, PingOptions options)
219                 {
220                         if (address == null)
221                                 throw new ArgumentNullException ("address");
222                         if (timeout < 0)
223                                 throw new ArgumentOutOfRangeException ("timeout", "timeout must be non-negative integer");
224                         if (buffer == null)
225                                 throw new ArgumentNullException ("buffer");
226                         if (buffer.Length > 65500)
227                                 throw new ArgumentException ("buffer");
228                         // options can be null.
229
230 #if MONOTOUCH
231                         throw new InvalidOperationException ();
232 #else
233                         if (canSendPrivileged)
234                                 return SendPrivileged (address, timeout, buffer, options);
235                         return SendUnprivileged (address, timeout, buffer, options);
236 #endif
237                 }
238
239 #if !MONOTOUCH
240                 private PingReply SendPrivileged (IPAddress address, int timeout, byte [] buffer, PingOptions options)
241                 {
242                         IPEndPoint target = new IPEndPoint (address, 0);
243                         IPEndPoint client = new IPEndPoint (GetNonLoopbackIP (), 0);
244
245                         // FIXME: support IPv6
246                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp)) {
247                                 if (options != null) {
248                                         s.DontFragment = options.DontFragment;
249                                         s.Ttl = (short) options.Ttl;
250                                 }
251                                 s.SendTimeout = timeout;
252                                 s.ReceiveTimeout = timeout;
253                                 // not sure why Identifier = 0 is unacceptable ...
254                                 IcmpMessage send = new IcmpMessage (8, 0, identifier, 0, buffer);
255                                 byte [] bytes = send.GetBytes ();
256                                 s.SendBufferSize = bytes.Length;
257                                 s.SendTo (bytes, bytes.Length, SocketFlags.None, target);
258
259                                 DateTime sentTime = DateTime.Now;
260
261                                 // receive
262                                 bytes = new byte [100];
263                                 do {
264                                         EndPoint endpoint = client;
265                                         SocketError error = 0;
266                                         int rc = s.ReceiveFrom (bytes, 0, 100, SocketFlags.None,
267                                                         ref endpoint, out error);
268
269                                         if (error != SocketError.Success) {
270                                                 if (error == SocketError.TimedOut) {
271                                                         return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
272                                                 }
273                                                 throw new NotSupportedException (String.Format ("Unexpected socket error during ping request: {0}", error));
274                                         }
275                                         long rtt = (long) (DateTime.Now - sentTime).TotalMilliseconds;
276                                         int headerLength = (bytes [0] & 0xF) << 2;
277                                         int bodyLength = rc - headerLength;
278
279                                         // Ping reply to different request. discard it.
280                                         if (!((IPEndPoint) endpoint).Address.Equals (target.Address)) {
281                                                 long t = timeout - rtt;
282                                                 if (t <= 0)
283                                                         return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
284                                                 s.ReceiveTimeout = (int) t;
285                                                 continue;
286                                         }
287
288                                         IcmpMessage recv = new IcmpMessage (bytes, headerLength, bodyLength);
289
290                                         /* discard ping reply to different request or echo requests if running on same host. */
291                                         if (recv.Identifier != identifier || recv.Type == 8) {
292                                                 long t = timeout - rtt;
293                                                 if (t <= 0)
294                                                         return new PingReply (null, new byte [0], options, 0, IPStatus.TimedOut);
295                                                 s.ReceiveTimeout = (int) t;
296                                                 continue; 
297                                         }
298
299                                         return new PingReply (address, recv.Data, options, rtt, recv.IPStatus);
300                                 } while (true);
301                         }
302                 }
303
304                 private PingReply SendUnprivileged (IPAddress address, int timeout, byte [] buffer, PingOptions options)
305                 {
306 #if MONO_FEATURE_PROCESS_START
307                         DateTime sentTime = DateTime.UtcNow;
308
309                         Process ping = new Process ();
310                         string args = BuildPingArgs (address, timeout, options);
311                         long trip_time = 0;
312
313                         ping.StartInfo.FileName = PingBinPath;
314                         ping.StartInfo.Arguments = args;
315
316                         ping.StartInfo.CreateNoWindow = true;
317                         ping.StartInfo.UseShellExecute = false;
318
319                         ping.StartInfo.RedirectStandardOutput = true;
320                         ping.StartInfo.RedirectStandardError = true;
321
322                         IPStatus status = IPStatus.Unknown;
323                         try {
324                                 ping.Start ();
325
326 #pragma warning disable 219
327                                 string stdout = ping.StandardOutput.ReadToEnd ();
328                                 string stderr = ping.StandardError.ReadToEnd ();
329 #pragma warning restore 219
330                                 
331                                 trip_time = (long) (DateTime.UtcNow - sentTime).TotalMilliseconds;
332                                 if (!ping.WaitForExit (timeout) || (ping.HasExited && ping.ExitCode == 2))
333                                         status = IPStatus.TimedOut;
334                                 else if (ping.ExitCode == 0)
335                                         status = IPStatus.Success;
336                                 else if (ping.ExitCode == 1)
337                                         status = IPStatus.TtlExpired;
338                         } catch {
339                         } finally {
340                                 if (!ping.HasExited)
341                                         ping.Kill ();
342                                 ping.Dispose ();
343                         }
344
345                         return new PingReply (address, buffer, options, trip_time, status);
346 #else
347                         throw new PlatformNotSupportedException ("Ping is not supported on this platform.");
348 #endif // MONO_FEATURE_PROCESS_START
349                 }
350 #endif // !MONOTOUCH
351
352                 // Async
353
354                 public void SendAsync (IPAddress address, int timeout, byte [] buffer, object userToken)
355                 {
356                         SendAsync (address, default_timeout, default_buffer, new PingOptions (), userToken);
357                 }
358
359                 public void SendAsync (IPAddress address, int timeout, object userToken)
360                 {
361                         SendAsync (address, default_timeout, default_buffer, userToken);
362                 }
363
364                 public void SendAsync (IPAddress address, object userToken)
365                 {
366                         SendAsync (address, default_timeout, userToken);
367                 }
368
369                 public void SendAsync (string hostNameOrAddress, int timeout, byte [] buffer, object userToken)
370                 {
371                         SendAsync (hostNameOrAddress, timeout, buffer, new PingOptions (), userToken);
372                 }
373
374                 public void SendAsync (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options, object userToken)
375                 {
376                         IPAddress address = Dns.GetHostEntry (hostNameOrAddress).AddressList [0];
377                         SendAsync (address, timeout, buffer, options, userToken);
378                 }
379
380                 public void SendAsync (string hostNameOrAddress, int timeout, object userToken)
381                 {
382                         SendAsync (hostNameOrAddress, timeout, default_buffer, userToken);
383                 }
384
385                 public void SendAsync (string hostNameOrAddress, object userToken)
386                 {
387                         SendAsync (hostNameOrAddress, default_timeout, userToken);
388                 }
389
390                 public void SendAsync (IPAddress address, int timeout, byte [] buffer, PingOptions options, object userToken)
391                 {
392                         if ((worker != null) || (cts != null))
393                                 throw new InvalidOperationException ("Another SendAsync operation is in progress");
394
395                         worker = new BackgroundWorker ();
396                         worker.DoWork += delegate (object o, DoWorkEventArgs ea) {
397                                 try {
398                                         user_async_state = ea.Argument;
399                                         ea.Result = Send (address, timeout, buffer, options);
400                                 } catch (Exception ex) {
401                                         ea.Result = ex;
402                                 }
403                         };
404                         worker.WorkerSupportsCancellation = true;
405                         worker.RunWorkerCompleted += delegate (object o, RunWorkerCompletedEventArgs ea) {
406                                 // Note that RunWorkerCompletedEventArgs.UserState cannot be used (LAMESPEC)
407                                 OnPingCompleted (new PingCompletedEventArgs (ea.Error, ea.Cancelled, user_async_state, ea.Result as PingReply));
408                         };
409                         worker.RunWorkerAsync (userToken);
410                 }
411
412                 // SendAsyncCancel
413
414                 public void SendAsyncCancel ()
415                 {
416                         if (cts != null) {
417                                 cts.Cancel ();
418                                 return;
419                         }
420
421                         if (worker == null)
422                                 throw new InvalidOperationException ("SendAsync operation is not in progress");
423                         worker.CancelAsync ();
424                 }
425
426 #if !MONOTOUCH
427                 // ICMP message
428
429                 class IcmpMessage
430                 {
431                         byte [] bytes;
432
433                         // received
434                         public IcmpMessage (byte [] bytes, int offset, int size)
435                         {
436                                 this.bytes = new byte [size];
437                                 Buffer.BlockCopy (bytes, offset, this.bytes, 0, size);
438                         }
439
440                         // to be sent
441                         public IcmpMessage (byte type, byte code, ushort identifier, ushort sequence, byte [] data)
442                         {
443                                 bytes = new byte [data.Length + 8];
444                                 bytes [0] = type;
445                                 bytes [1] = code;
446                                 bytes [4] = (byte) (identifier & 0xFF);
447                                 bytes [5] = (byte) ((int) identifier >> 8);
448                                 bytes [6] = (byte) (sequence & 0xFF);
449                                 bytes [7] = (byte) ((int) sequence >> 8);
450                                 Buffer.BlockCopy (data, 0, bytes, 8, data.Length);
451
452                                 ushort checksum = ComputeChecksum (bytes);
453                                 bytes [2] = (byte) (checksum & 0xFF);
454                                 bytes [3] = (byte) ((int) checksum >> 8);
455                         }
456
457                         public byte Type {
458                                 get { return bytes [0]; }
459                         }
460
461                         public byte Code {
462                                 get { return bytes [1]; }
463                         }
464
465                         public ushort Identifier {
466                                 get { return (ushort) (bytes [4] + (bytes [5] << 8)); }
467                         }
468
469                         public ushort Sequence {
470                                 get { return (ushort) (bytes [6] + (bytes [7] << 8)); }
471                         }
472
473                         public byte [] Data {
474                                 get {
475                                         byte [] data = new byte [bytes.Length - 8];
476                                         Buffer.BlockCopy (bytes, 8, data, 0, data.Length);
477                                         return data;
478                                 }
479                         }
480
481                         public byte [] GetBytes ()
482                         {
483                                 return bytes;
484                         }
485
486                         static ushort ComputeChecksum (byte [] data)
487                         {
488                                 uint ret = 0;
489                                 for (int i = 0; i < data.Length; i += 2) {
490                                         ushort us = i + 1 < data.Length ? data [i + 1] : (byte) 0;
491                                         us <<= 8;
492                                         us += data [i];
493                                         ret += us;
494                                 }
495                                 ret = (ret >> 16) + (ret & 0xFFFF);
496                                 return (ushort) ~ ret;
497                         }
498
499                         public IPStatus IPStatus {
500                                 get {
501                                         switch (Type) {
502                                         case 0:
503                                                 return IPStatus.Success;
504                                         case 3: // destination unreacheable
505                                                 switch (Code) {
506                                                 case 0:
507                                                         return IPStatus.DestinationNetworkUnreachable;
508                                                 case 1:
509                                                         return IPStatus.DestinationHostUnreachable;
510                                                 case 2:
511                                                         return IPStatus.DestinationProtocolUnreachable;
512                                                 case 3:
513                                                         return IPStatus.DestinationPortUnreachable;
514                                                 case 4:
515                                                         return IPStatus.BadOption; // FIXME: likely wrong
516                                                 case 5:
517                                                         return IPStatus.BadRoute; // not sure if it is correct
518                                                 }
519                                                 break;
520                                         case 11:
521                                                 switch (Code) {
522                                                 case 0:
523                                                         return IPStatus.TimeExceeded;
524                                                 case 1:
525                                                         return IPStatus.TtlReassemblyTimeExceeded;
526                                                 }
527                                                 break;
528                                         case 12:
529                                                 return IPStatus.ParameterProblem;
530                                         case 4:
531                                                 return IPStatus.SourceQuench;
532                                         case 8:
533                                                 return IPStatus.Success;
534                                         }
535                                         return IPStatus.Unknown;
536                                         //throw new NotSupportedException (String.Format ("Unexpected pair of ICMP message type and code: type is {0} and code is {1}", Type, Code));
537                                 }
538                         }
539                 }
540
541                 private string BuildPingArgs (IPAddress address, int timeout, PingOptions options)
542                 {
543                         CultureInfo culture = CultureInfo.InvariantCulture;
544                         StringBuilder args = new StringBuilder ();
545                         uint t = Convert.ToUInt32 (Math.Floor ((timeout + 1000) / 1000.0));
546                         bool is_mac = Platform.IsMacOS;
547                         if (!is_mac)
548                                 args.AppendFormat (culture, "-q -n -c {0} -w {1} -t {2} -M ", DefaultCount, t, options.Ttl);
549                         else
550                                 args.AppendFormat (culture, "-q -n -c {0} -t {1} -o -m {2} ", DefaultCount, t, options.Ttl);
551                         if (!is_mac)
552                                 args.Append (options.DontFragment ? "do " : "dont ");
553                         else if (options.DontFragment)
554                                 args.Append ("-D ");
555
556                         args.Append (address.ToString ());
557
558                         return args.ToString ();
559                 }
560 #endif // !MONOTOUCH
561
562                 public Task<PingReply> SendPingAsync (IPAddress address, int timeout, byte [] buffer)
563                 {
564                         return SendPingAsync (address, default_timeout, default_buffer, new PingOptions ());
565                 }
566
567                 public Task<PingReply> SendPingAsync (IPAddress address, int timeout)
568                 {
569                         return SendPingAsync (address, default_timeout, default_buffer);
570                 }
571
572                 public Task<PingReply> SendPingAsync (IPAddress address)
573                 {
574                         return SendPingAsync (address, default_timeout);
575                 }
576
577                 public Task<PingReply> SendPingAsync (string hostNameOrAddress, int timeout, byte [] buffer)
578                 {
579                         return SendPingAsync (hostNameOrAddress, timeout, buffer, new PingOptions ());
580                 }
581
582                 public Task<PingReply> SendPingAsync (string hostNameOrAddress, int timeout, byte [] buffer, PingOptions options)
583                 {
584                         IPAddress address = Dns.GetHostEntry (hostNameOrAddress).AddressList [0];
585                         return SendPingAsync (address, timeout, buffer, options);
586                 }
587
588                 public Task<PingReply> SendPingAsync (string hostNameOrAddress, int timeout)
589                 {
590                         return SendPingAsync (hostNameOrAddress, timeout, default_buffer);
591                 }
592
593                 public Task<PingReply> SendPingAsync (string hostNameOrAddress)
594                 {
595                         return SendPingAsync (hostNameOrAddress, default_timeout);
596                 }
597
598                 public Task<PingReply> SendPingAsync (IPAddress address, int timeout, byte [] buffer, PingOptions options)
599                 {
600                         if ((worker != null) || (cts != null))
601                                 throw new InvalidOperationException ("Another SendAsync operation is in progress");
602
603                         cts = new CancellationTokenSource();
604
605                         var task = Task<PingReply>.Factory.StartNew (
606                                 () => Send (address, timeout, buffer, options), cts.Token);
607
608                         task.ContinueWith ((t) => {
609                                 if (t.IsCanceled)
610                                         OnPingCompleted (new PingCompletedEventArgs (null, true, null, null));
611                                 else if (t.IsFaulted)
612                                         OnPingCompleted (new PingCompletedEventArgs (t.Exception, false, null, null));
613                                 else
614                                         OnPingCompleted (new PingCompletedEventArgs (null, false, null, t.Result));
615                         });
616
617                         return task;
618                 }
619         }
620 }