ntdll: Use PAGE_EXECUTE_READWRITE protection when allocating stubs.
[wine.git] / dlls / iphlpapi / icmp.c
blob78b91c6fb262f4960b73716f2d9e4ef2b14d474f
1 /*
2 * ICMP
4 * Francois Gouget, 1999, based on the work of
5 * RW Hall, 1999, based on public domain code PING.C by Mike Muus (1983)
6 * and later works (c) 1989 Regents of Univ. of California - see copyright
7 * notice at end of source-code.
9 * This library is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * This library is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with this library; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 /* Future work:
25 * - Systems like FreeBSD don't seem to support the IP_TTL option and maybe others.
26 * But using IP_HDRINCL and building the IP header by hand might work.
27 * - Not all IP options are supported.
28 * - Are ICMP handles real handles, i.e. inheritable and all? There might be some
29 * more work to do here, including server side stuff with synchronization.
30 * - This API should probably be thread safe. Is it really?
31 * - Using the winsock functions has not been tested.
34 #include "config.h"
36 #include <sys/types.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 # include <sys/socket.h>
39 #endif
40 #ifdef HAVE_NETDB_H
41 # include <netdb.h>
42 #endif
43 #ifdef HAVE_NETINET_IN_SYSTM_H
44 # include <netinet/in_systm.h>
45 #endif
46 #ifdef HAVE_NETINET_IN_H
47 # include <netinet/in.h>
48 #endif
50 #ifdef HAVE_SYS_TIME_H
51 # include <sys/time.h>
52 #endif
53 #include <stdarg.h>
54 #include <string.h>
55 #include <errno.h>
56 #ifdef HAVE_UNISTD_H
57 # include <unistd.h>
58 #endif
59 #ifdef HAVE_ARPA_INET_H
60 # include <arpa/inet.h>
61 #endif
62 #ifdef HAVE_SYS_POLL_H
63 # include <sys/poll.h>
64 #endif
66 #include "windef.h"
67 #include "winbase.h"
68 #include "winerror.h"
69 #include "winternl.h"
70 #include "ipexport.h"
71 #include "icmpapi.h"
72 #include "wine/debug.h"
74 /* Set up endianness macros for the ip and ip_icmp BSD headers */
75 #ifndef BIG_ENDIAN
76 #define BIG_ENDIAN 4321
77 #endif
78 #ifndef LITTLE_ENDIAN
79 #define LITTLE_ENDIAN 1234
80 #endif
81 #ifndef BYTE_ORDER
82 #ifdef WORDS_BIGENDIAN
83 #define BYTE_ORDER BIG_ENDIAN
84 #else
85 #define BYTE_ORDER LITTLE_ENDIAN
86 #endif
87 #endif /* BYTE_ORDER */
89 #define u_int16_t WORD
90 #define u_int32_t DWORD
92 /* These are BSD headers. We use these here because they are needed on
93 * libc5 Linux systems. On other platforms they are usually simply more
94 * complete than the native stuff, and cause less portability problems
95 * so we use them anyway.
97 #include "ip.h"
98 #include "ip_icmp.h"
101 WINE_DEFAULT_DEBUG_CHANNEL(icmp);
102 WINE_DECLARE_DEBUG_CHANNEL(winediag);
105 typedef struct {
106 int sid;
107 IP_OPTION_INFORMATION default_opts;
108 } icmp_t;
110 #define IP_OPTS_UNKNOWN 0
111 #define IP_OPTS_DEFAULT 1
112 #define IP_OPTS_CUSTOM 2
114 /* The sequence number is unique process wide, so that all threads
115 * have a distinct sequence number.
117 static LONG icmp_sequence=0;
119 static int in_cksum(u_short *addr, int len)
121 int nleft=len;
122 u_short *w = addr;
123 int sum = 0;
124 u_short answer = 0;
126 while (nleft > 1) {
127 sum += *w++;
128 nleft -= 2;
131 if (nleft == 1) {
132 *(u_char *)(&answer) = *(u_char *)w;
133 sum += answer;
136 sum = (sum >> 16) + (sum & 0xffff);
137 sum += (sum >> 16);
138 answer = ~sum;
139 return(answer);
145 * Exported Routines.
148 /***********************************************************************
149 * IcmpCreateFile (IPHLPAPI.@)
151 HANDLE WINAPI IcmpCreateFile(VOID)
153 icmp_t* icp;
155 int sid=socket(AF_INET,SOCK_RAW,IPPROTO_ICMP);
156 if (sid < 0)
158 /* Mac OS X supports non-privileged ICMP via SOCK_DGRAM type. */
159 sid=socket(AF_INET,SOCK_DGRAM,IPPROTO_ICMP);
161 if (sid < 0) {
162 ERR_(winediag)("Failed to use ICMP (network ping), this requires special permissions.\n");
163 SetLastError(ERROR_ACCESS_DENIED);
164 return INVALID_HANDLE_VALUE;
167 icp=HeapAlloc(GetProcessHeap(), 0, sizeof(*icp));
168 if (icp==NULL) {
169 SetLastError(IP_NO_RESOURCES);
170 return INVALID_HANDLE_VALUE;
172 icp->sid=sid;
173 icp->default_opts.OptionsSize=IP_OPTS_UNKNOWN;
174 return (HANDLE)icp;
178 /***********************************************************************
179 * IcmpCloseHandle (IPHLPAPI.@)
181 BOOL WINAPI IcmpCloseHandle(HANDLE IcmpHandle)
183 icmp_t* icp=(icmp_t*)IcmpHandle;
184 if (IcmpHandle==INVALID_HANDLE_VALUE) {
185 /* FIXME: in fact win98 seems to ignore the handle value !!! */
186 SetLastError(ERROR_INVALID_HANDLE);
187 return FALSE;
190 close( icp->sid );
191 HeapFree(GetProcessHeap (), 0, icp);
192 return TRUE;
196 /***********************************************************************
197 * IcmpSendEcho (IPHLPAPI.@)
199 DWORD WINAPI IcmpSendEcho(
200 HANDLE IcmpHandle,
201 IPAddr DestinationAddress,
202 LPVOID RequestData,
203 WORD RequestSize,
204 PIP_OPTION_INFORMATION RequestOptions,
205 LPVOID ReplyBuffer,
206 DWORD ReplySize,
207 DWORD Timeout
210 icmp_t* icp=(icmp_t*)IcmpHandle;
211 unsigned char* reqbuf;
212 int reqsize;
214 struct icmp_echo_reply* ier;
215 struct ip* ip_header;
216 struct icmp* icmp_header;
217 char* endbuf;
218 int ip_header_len;
219 int maxlen;
220 struct pollfd fdr;
221 DWORD send_time,recv_time;
222 struct sockaddr_in addr;
223 unsigned int addrlen;
224 unsigned short id,seq,cksum;
225 int res;
227 if (IcmpHandle==INVALID_HANDLE_VALUE) {
228 /* FIXME: in fact win98 seems to ignore the handle value !!! */
229 SetLastError(ERROR_INVALID_HANDLE);
230 return 0;
233 if (ReplySize<sizeof(ICMP_ECHO_REPLY)+ICMP_MINLEN) {
234 SetLastError(IP_BUF_TOO_SMALL);
235 return 0;
237 /* check the request size against SO_MAX_MSG_SIZE using getsockopt */
239 /* Prepare the request */
240 id=getpid() & 0xFFFF;
241 seq=InterlockedIncrement(&icmp_sequence) & 0xFFFF;
243 reqsize=ICMP_MINLEN+RequestSize;
244 reqbuf=HeapAlloc(GetProcessHeap(), 0, reqsize);
245 if (reqbuf==NULL) {
246 SetLastError(ERROR_OUTOFMEMORY);
247 return 0;
250 icmp_header=(struct icmp*)reqbuf;
251 icmp_header->icmp_type=ICMP_ECHO;
252 icmp_header->icmp_code=0;
253 icmp_header->icmp_cksum=0;
254 icmp_header->icmp_id=id;
255 icmp_header->icmp_seq=seq;
256 memcpy(reqbuf+ICMP_MINLEN, RequestData, RequestSize);
257 icmp_header->icmp_cksum=cksum=in_cksum((u_short*)reqbuf,reqsize);
259 addr.sin_family=AF_INET;
260 addr.sin_addr.s_addr=DestinationAddress;
261 addr.sin_port=0;
263 if (RequestOptions!=NULL) {
264 int val;
265 if (icp->default_opts.OptionsSize==IP_OPTS_UNKNOWN) {
266 unsigned int len;
267 /* Before we mess with the options, get the default values */
268 len=sizeof(val);
269 getsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,&len);
270 icp->default_opts.Ttl=val;
272 len=sizeof(val);
273 getsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,&len);
274 icp->default_opts.Tos=val;
275 /* FIXME: missing: handling of IP 'flags', and all the other options */
278 val=RequestOptions->Ttl;
279 setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
280 val=RequestOptions->Tos;
281 setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
282 /* FIXME: missing: handling of IP 'flags', and all the other options */
284 icp->default_opts.OptionsSize=IP_OPTS_CUSTOM;
285 } else if (icp->default_opts.OptionsSize==IP_OPTS_CUSTOM) {
286 int val;
288 /* Restore the default options */
289 val=icp->default_opts.Ttl;
290 setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
291 val=icp->default_opts.Tos;
292 setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
293 /* FIXME: missing: handling of IP 'flags', and all the other options */
295 icp->default_opts.OptionsSize=IP_OPTS_DEFAULT;
298 /* Get ready for receiving the reply
299 * Do it before we send the request to minimize the risk of introducing delays
301 fdr.fd = icp->sid;
302 fdr.events = POLLIN;
303 addrlen=sizeof(addr);
304 ier=ReplyBuffer;
305 ip_header=(struct ip *) ((char *) ReplyBuffer+sizeof(ICMP_ECHO_REPLY));
306 endbuf=(char *) ReplyBuffer+ReplySize;
307 maxlen=ReplySize-sizeof(ICMP_ECHO_REPLY);
309 /* Send the packet */
310 TRACE("Sending %d bytes (RequestSize=%d) to %s\n", reqsize, RequestSize, inet_ntoa(addr.sin_addr));
311 #if 0
312 if (TRACE_ON(icmp)){
313 unsigned char* buf=(unsigned char*)reqbuf;
314 int i;
315 printf("Output buffer:\n");
316 for (i=0;i<reqsize;i++)
317 printf("%2x,", buf[i]);
318 printf("\n");
320 #endif
322 send_time = GetTickCount();
323 res=sendto(icp->sid, reqbuf, reqsize, 0, (struct sockaddr*)&addr, sizeof(addr));
324 HeapFree(GetProcessHeap (), 0, reqbuf);
325 if (res<0) {
326 if (errno==EMSGSIZE)
327 SetLastError(IP_PACKET_TOO_BIG);
328 else {
329 switch (errno) {
330 case ENETUNREACH:
331 SetLastError(IP_DEST_NET_UNREACHABLE);
332 break;
333 case EHOSTUNREACH:
334 SetLastError(IP_DEST_HOST_UNREACHABLE);
335 break;
336 default:
337 TRACE("unknown error: errno=%d\n",errno);
338 SetLastError(IP_GENERAL_FAILURE);
341 return 0;
344 /* Get the reply */
345 ip_header_len=0; /* because gcc was complaining */
346 while (poll(&fdr,1,Timeout)>0) {
347 recv_time = GetTickCount();
348 res=recvfrom(icp->sid, (char*)ip_header, maxlen, 0, (struct sockaddr*)&addr,&addrlen);
349 TRACE("received %d bytes from %s\n",res, inet_ntoa(addr.sin_addr));
350 ier->Status=IP_REQ_TIMED_OUT;
352 /* Check whether we should ignore this packet */
353 if ((ip_header->ip_p==IPPROTO_ICMP) && (res>=sizeof(struct ip)+ICMP_MINLEN)) {
354 ip_header_len=ip_header->ip_hl << 2;
355 icmp_header=(struct icmp*)(((char*)ip_header)+ip_header_len);
356 TRACE("received an ICMP packet of type,code=%d,%d\n",icmp_header->icmp_type,icmp_header->icmp_code);
357 if (icmp_header->icmp_type==ICMP_ECHOREPLY) {
358 if ((icmp_header->icmp_id==id) && (icmp_header->icmp_seq==seq))
359 ier->Status=IP_SUCCESS;
360 } else {
361 switch (icmp_header->icmp_type) {
362 case ICMP_UNREACH:
363 switch (icmp_header->icmp_code) {
364 case ICMP_UNREACH_HOST:
365 #ifdef ICMP_UNREACH_HOST_UNKNOWN
366 case ICMP_UNREACH_HOST_UNKNOWN:
367 #endif
368 #ifdef ICMP_UNREACH_ISOLATED
369 case ICMP_UNREACH_ISOLATED:
370 #endif
371 #ifdef ICMP_UNREACH_HOST_PROHIB
372 case ICMP_UNREACH_HOST_PROHIB:
373 #endif
374 #ifdef ICMP_UNREACH_TOSHOST
375 case ICMP_UNREACH_TOSHOST:
376 #endif
377 ier->Status=IP_DEST_HOST_UNREACHABLE;
378 break;
379 case ICMP_UNREACH_PORT:
380 ier->Status=IP_DEST_PORT_UNREACHABLE;
381 break;
382 case ICMP_UNREACH_PROTOCOL:
383 ier->Status=IP_DEST_PROT_UNREACHABLE;
384 break;
385 case ICMP_UNREACH_SRCFAIL:
386 ier->Status=IP_BAD_ROUTE;
387 break;
388 default:
389 ier->Status=IP_DEST_NET_UNREACHABLE;
391 break;
392 case ICMP_TIMXCEED:
393 if (icmp_header->icmp_code==ICMP_TIMXCEED_REASS)
394 ier->Status=IP_TTL_EXPIRED_REASSEM;
395 else
396 ier->Status=IP_TTL_EXPIRED_TRANSIT;
397 break;
398 case ICMP_PARAMPROB:
399 ier->Status=IP_PARAM_PROBLEM;
400 break;
401 case ICMP_SOURCEQUENCH:
402 ier->Status=IP_SOURCE_QUENCH;
403 break;
405 if (ier->Status!=IP_REQ_TIMED_OUT) {
406 struct ip* rep_ip_header;
407 struct icmp* rep_icmp_header;
408 /* The ICMP header size of all the packets we accept is the same */
409 rep_ip_header=(struct ip*)(((char*)icmp_header)+ICMP_MINLEN);
410 rep_icmp_header=(struct icmp*)(((char*)rep_ip_header)+(rep_ip_header->ip_hl << 2));
412 /* Make sure that this is really a reply to our packet */
413 if (ip_header_len+ICMP_MINLEN+(rep_ip_header->ip_hl << 2)+ICMP_MINLEN>ip_header->ip_len) {
414 ier->Status=IP_REQ_TIMED_OUT;
415 } else if ((rep_icmp_header->icmp_type!=ICMP_ECHO) ||
416 (rep_icmp_header->icmp_code!=0) ||
417 (rep_icmp_header->icmp_id!=id) ||
418 /* windows doesn't check this checksum, else tracert */
419 /* behind a Linux 2.2 masquerading firewall would fail*/
420 /* (rep_icmp_header->icmp_cksum!=cksum) || */
421 (rep_icmp_header->icmp_seq!=seq)) {
422 /* This was not a reply to one of our packets after all */
423 TRACE("skipping type,code=%d,%d id,seq=%d,%d cksum=%d\n",
424 rep_icmp_header->icmp_type,rep_icmp_header->icmp_code,
425 rep_icmp_header->icmp_id,rep_icmp_header->icmp_seq,
426 rep_icmp_header->icmp_cksum);
427 TRACE("expected type,code=8,0 id,seq=%d,%d cksum=%d\n",
428 id,seq,
429 cksum);
430 ier->Status=IP_REQ_TIMED_OUT;
436 if (ier->Status==IP_REQ_TIMED_OUT) {
437 /* This packet was not for us.
438 * Decrease the timeout so that we don't enter an endless loop even
439 * if we get flooded with ICMP packets that are not for us.
441 DWORD t = (recv_time - send_time);
442 if (Timeout > t) Timeout -= t;
443 else Timeout = 0;
444 continue;
445 } else {
446 /* This is a reply to our packet */
447 memcpy(&ier->Address,&ip_header->ip_src,sizeof(IPAddr));
448 /* Status is already set */
449 ier->RoundTripTime= recv_time - send_time;
450 ier->DataSize=res-ip_header_len-ICMP_MINLEN;
451 ier->Reserved=0;
452 ier->Data=endbuf-ier->DataSize;
453 memmove(ier->Data,((char*)ip_header)+ip_header_len+ICMP_MINLEN,ier->DataSize);
454 ier->Options.Ttl=ip_header->ip_ttl;
455 ier->Options.Tos=ip_header->ip_tos;
456 ier->Options.Flags=ip_header->ip_off >> 13;
457 ier->Options.OptionsSize=ip_header_len-sizeof(struct ip);
458 if (ier->Options.OptionsSize!=0) {
459 ier->Options.OptionsData=(unsigned char *) ier->Data-ier->Options.OptionsSize;
460 /* FIXME: We are supposed to rearrange the option's 'source route' data */
461 memmove(ier->Options.OptionsData,((char*)ip_header)+ip_header_len,ier->Options.OptionsSize);
462 endbuf=(char*)ier->Options.OptionsData;
463 } else {
464 ier->Options.OptionsData=NULL;
465 endbuf=ier->Data;
468 /* Prepare for the next packet */
469 ier++;
470 ip_header=(struct ip*)(((char*)ip_header)+sizeof(ICMP_ECHO_REPLY));
471 maxlen=endbuf-(char*)ip_header;
473 /* Check out whether there is more but don't wait this time */
474 Timeout=0;
477 res=ier-(ICMP_ECHO_REPLY*)ReplyBuffer;
478 if (res==0)
479 SetLastError(IP_REQ_TIMED_OUT);
480 TRACE("received %d replies\n",res);
481 return res;
484 /***********************************************************************
485 * IcmpSendEcho2 (IPHLPAPI.@)
487 DWORD WINAPI IcmpSendEcho2(
488 HANDLE IcmpHandle,
489 HANDLE Event,
490 PIO_APC_ROUTINE ApcRoutine,
491 PVOID ApcContext,
492 IPAddr DestinationAddress,
493 LPVOID RequestData,
494 WORD RequestSize,
495 PIP_OPTION_INFORMATION RequestOptions,
496 LPVOID ReplyBuffer,
497 DWORD ReplySize,
498 DWORD Timeout
501 TRACE("(%p, %p, %p, %p, %08x, %p, %d, %p, %p, %d, %d): stub\n", IcmpHandle,
502 Event, ApcRoutine, ApcContext, DestinationAddress, RequestData,
503 RequestSize, RequestOptions, ReplyBuffer, ReplySize, Timeout);
505 if (Event)
507 FIXME("unsupported for events\n");
508 return 0;
510 if (ApcRoutine)
512 FIXME("unsupported for APCs\n");
513 return 0;
515 return IcmpSendEcho(IcmpHandle, DestinationAddress, RequestData,
516 RequestSize, RequestOptions, ReplyBuffer, ReplySize, Timeout);
519 /***********************************************************************
520 * IcmpSendEcho2Ex (IPHLPAPI.@)
522 DWORD WINAPI IcmpSendEcho2Ex(
523 HANDLE IcmpHandle,
524 HANDLE Event,
525 PIO_APC_ROUTINE ApcRoutine,
526 PVOID ApcContext,
527 IPAddr SourceAddress,
528 IPAddr DestinationAddress,
529 LPVOID RequestData,
530 WORD RequestSize,
531 PIP_OPTION_INFORMATION RequestOptions,
532 LPVOID ReplyBuffer,
533 DWORD ReplySize,
534 DWORD Timeout
537 TRACE("(%p, %p, %p, %p, %08x, %08x, %p, %d, %p, %p, %d, %d): stub\n", IcmpHandle,
538 Event, ApcRoutine, ApcContext, SourceAddress, DestinationAddress, RequestData,
539 RequestSize, RequestOptions, ReplyBuffer, ReplySize, Timeout);
541 if (Event)
543 FIXME("unsupported for events\n");
544 return 0;
546 if (ApcRoutine)
548 FIXME("unsupported for APCs\n");
549 return 0;
551 if (SourceAddress)
553 FIXME("unsupported for source addresses\n");
554 return 0;
557 return IcmpSendEcho(IcmpHandle, DestinationAddress, RequestData,
558 RequestSize, RequestOptions, ReplyBuffer, ReplySize, Timeout);
562 * Copyright (c) 1989 The Regents of the University of California.
563 * All rights reserved.
565 * This code is derived from software contributed to Berkeley by
566 * Mike Muuss.
568 * Redistribution and use in source and binary forms, with or without
569 * modification, are permitted provided that the following conditions
570 * are met:
571 * 1. Redistributions of source code must retain the above copyright
572 * notice, this list of conditions and the following disclaimer.
573 * 2. Redistributions in binary form must reproduce the above copyright
574 * notice, this list of conditions and the following disclaimer in the
575 * documentation and/or other materials provided with the distribution.
576 * 3. Neither the name of the University nor the names of its contributors
577 * may be used to endorse or promote products derived from this software
578 * without specific prior written permission.
580 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
581 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
582 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
583 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
584 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
585 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
586 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
587 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
588 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
589 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
590 * SUCH DAMAGE.