- Introduce a significant design decision.
[wine/dcerpc.git] / dlls / icmp / icmp_main.c
blob0e1f468f43099100f0ee3aaef6ecd6aa5e883994
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.
8 */
10 /* Future work:
11 * - Systems like FreeBSD don't seem to support the IP_TTL option and maybe others.
12 * But using IP_HDRINCL and building the IP header by hand might work.
13 * - Not all IP options are supported.
14 * - Are ICMP handles real handles, i.e. inheritable and all? There might be some
15 * more work to do here, including server side stuff with synchronization.
16 * - Is it correct to use malloc for the internal buffer, for allocating the
17 * handle's structure?
18 * - This API should probably be thread safe. Is it really?
19 * - Using the winsock functions has not been tested.
22 #include "config.h"
24 #include <sys/types.h>
25 #ifdef HAVE_SYS_SOCKET_H
26 # include <sys/socket.h>
27 #endif
28 #ifdef HAVE_NETDB_H
29 # include <netdb.h>
30 #endif
31 #ifdef HAVE_NETINET_IN_SYSTM_H
32 # include <netinet/in_systm.h>
33 #endif
34 #ifdef HAVE_NETINET_IN_H
35 # include <netinet/in.h>
36 #endif
38 #include <sys/time.h>
39 #include <string.h>
40 #include <errno.h>
41 #include <unistd.h>
42 #ifdef HAVE_ARPA_INET_H
43 # include <arpa/inet.h>
44 #endif
46 #include "windef.h"
47 #include "winbase.h"
48 #ifdef ICMP_WIN
49 #include "winsock2.h"
50 #endif
52 #include "winerror.h"
53 #include "wine/ipexport.h"
54 #include "wine/icmpapi.h"
55 #include "debugtools.h"
57 /* Set up endiannes macros for the ip and ip_icmp BSD headers */
58 #ifndef BIG_ENDIAN
59 #define BIG_ENDIAN 4321
60 #endif
61 #ifndef LITTLE_ENDIAN
62 #define LITTLE_ENDIAN 1234
63 #endif
64 #ifndef BYTE_ORDER
65 #ifdef WORDS_BIGENDIAN
66 #define BYTE_ORDER BIG_ENDIAN
67 #else
68 #define BYTE_ORDER LITTLE_ENDIAN
69 #endif
70 #endif /* BYTE_ORDER */
72 #define u_int16_t WORD
73 #define u_int32_t DWORD
75 /* These are BSD headers. We use these here because they are needed on
76 * libc5 Linux systems. On other platforms they are usually simply more
77 * complete than the native stuff, and cause less portability problems
78 * so we use them anyway.
80 #include "ip.h"
81 #include "ip_icmp.h"
84 DEFAULT_DEBUG_CHANNEL(icmp);
86 /* Define the following macro to use the winsock functions */
87 /*#define ICMP_WIN*/
89 #ifdef ICMP_WIN
90 /* FIXME: should we include winsock.h ???*/
91 SOCKET WINAPI WINSOCK_socket(INT af, INT type, INT protocol);
92 INT WINAPI WINSOCK_sendto(SOCKET s, char *buf, INT len, INT flags, struct sockaddr *to, INT tolen);
93 INT WINAPI WINSOCK_recvfrom(SOCKET s, char *buf,INT len, INT flags, struct sockaddr *from, INT *fromlen32);
94 INT WINAPI WINSOCK_shutdown(SOCKET s, INT how);
95 #endif
98 #ifdef ICMP_WIN
99 #define ISOCK_SOCKET SOCKET
100 #define ISOCK_ISVALID(a) ((a)!=INVALID_SOCKET)
101 #define ISOCK_getsockopt(a,b,c,d,e) WINSOCK_getsockopt(a,b,c,d,e)
102 #define ISOCK_recvfrom(a,b,c,d,e,f) WINSOCK_recvfrom(a,b,c,d,e,f)
103 #define ISOCK_select(a,b,c,d,e) WINSOCK_select(a,b,c,d,e)
104 #define ISOCK_sendto(a,b,c,d,e,f) WINSOCK_sendto(a,b,c,d,e,f)
105 #define ISOCK_setsockopt(a,b,c,d,e) WINSOCK_setsockopt(a,b,c,d,e)
106 #define ISOCK_shutdown(a,b) WINSOCK_shutdown(a,b)
107 #define ISOCK_socket(a,b,c) WINSOCK_socket(a,b,c)
108 #else
109 #define ISOCK_SOCKET int
110 #define ISOCK_ISVALID(a) ((a)>=0)
111 #define ISOCK_getsockopt(a,b,c,d,e) getsockopt(a,b,c,d,e)
112 #define ISOCK_recvfrom(a,b,c,d,e,f) recvfrom(a,b,c,d,e,f)
113 #define ISOCK_select(a,b,c,d,e) select(a,b,c,d,e)
114 #define ISOCK_setsockopt(a,b,c,d,e) setsockopt(a,b,c,d,e)
115 #define ISOCK_sendto(a,b,c,d,e,f) sendto(a,b,c,d,e,f)
116 #define ISOCK_shutdown(a,b) shutdown(a,b)
117 #define ISOCK_socket(a,b,c) socket(a,b,c)
118 #endif
120 typedef struct {
121 ISOCK_SOCKET sid;
122 IP_OPTION_INFORMATION default_opts;
123 } icmp_t;
125 #define IP_OPTS_UNKNOWN 0
126 #define IP_OPTS_DEFAULT 1
127 #define IP_OPTS_CUSTOM 2
129 /* The sequence number is unique process wide, so that all threads
130 * have a distinct sequence number.
132 static LONG icmp_sequence=0;
134 static int in_cksum(u_short *addr, int len)
136 int nleft=len;
137 u_short *w = addr;
138 int sum = 0;
139 u_short answer = 0;
141 while (nleft > 1) {
142 sum += *w++;
143 nleft -= 2;
146 if (nleft == 1) {
147 *(u_char *)(&answer) = *(u_char *)w;
148 sum += answer;
151 sum = (sum >> 16) + (sum & 0xffff);
152 sum += (sum >> 16);
153 answer = ~sum;
154 return(answer);
160 * Exported Routines.
163 /***********************************************************************
164 * IcmpCreateFile (ICMP.@)
166 HANDLE WINAPI IcmpCreateFile(VOID)
168 icmp_t* icp;
170 ISOCK_SOCKET sid=ISOCK_socket(AF_INET,SOCK_RAW,IPPROTO_ICMP);
171 if (!ISOCK_ISVALID(sid)) {
172 MESSAGE("WARNING: Trying to use ICMP will fail unless running as root\n");
173 SetLastError(ERROR_ACCESS_DENIED);
174 return INVALID_HANDLE_VALUE;
177 icp=HeapAlloc(GetProcessHeap(), 0, sizeof(*icp));
178 if (icp==NULL) {
179 SetLastError(IP_NO_RESOURCES);
180 return INVALID_HANDLE_VALUE;
182 icp->sid=sid;
183 icp->default_opts.OptionsSize=IP_OPTS_UNKNOWN;
184 return (HANDLE)icp;
188 /***********************************************************************
189 * IcmpCloseHandle (ICMP.@)
191 BOOL WINAPI IcmpCloseHandle(HANDLE IcmpHandle)
193 icmp_t* icp=(icmp_t*)IcmpHandle;
194 if (IcmpHandle==INVALID_HANDLE_VALUE) {
195 /* FIXME: in fact win98 seems to ignore the handle value !!! */
196 SetLastError(ERROR_INVALID_HANDLE);
197 return FALSE;
200 ISOCK_shutdown(icp->sid,2);
201 HeapFree(GetProcessHeap (), 0, icp);
202 return TRUE;
206 /***********************************************************************
207 * IcmpSendEcho (ICMP.@)
209 DWORD WINAPI IcmpSendEcho(
210 HANDLE IcmpHandle,
211 IPAddr DestinationAddress,
212 LPVOID RequestData,
213 WORD RequestSize,
214 PIP_OPTION_INFORMATION RequestOptions,
215 LPVOID ReplyBuffer,
216 DWORD ReplySize,
217 DWORD Timeout
220 icmp_t* icp=(icmp_t*)IcmpHandle;
221 unsigned char* reqbuf;
222 int reqsize;
224 struct icmp_echo_reply* ier;
225 struct ip* ip_header;
226 struct icmp* icmp_header;
227 char* endbuf;
228 int ip_header_len;
229 int maxlen;
230 fd_set fdr;
231 struct timeval timeout,send_time,recv_time;
232 struct sockaddr_in addr;
233 int addrlen;
234 unsigned short id,seq,cksum;
235 int res;
237 if (IcmpHandle==INVALID_HANDLE_VALUE) {
238 /* FIXME: in fact win98 seems to ignore the handle value !!! */
239 SetLastError(ERROR_INVALID_HANDLE);
240 return 0;
243 if (ReplySize<sizeof(ICMP_ECHO_REPLY)+ICMP_MINLEN) {
244 SetLastError(IP_BUF_TOO_SMALL);
245 return 0;
247 /* check the request size against SO_MAX_MSG_SIZE using getsockopt */
249 /* Prepare the request */
250 id=getpid() & 0xFFFF;
251 seq=InterlockedIncrement(&icmp_sequence) & 0xFFFF;
253 reqsize=ICMP_MINLEN+RequestSize;
254 reqbuf=HeapAlloc(GetProcessHeap(), 0, reqsize);
255 if (reqbuf==NULL) {
256 SetLastError(ERROR_OUTOFMEMORY);
257 return 0;
260 icmp_header=(struct icmp*)reqbuf;
261 icmp_header->icmp_type=ICMP_ECHO;
262 icmp_header->icmp_code=0;
263 icmp_header->icmp_cksum=0;
264 icmp_header->icmp_id=id;
265 icmp_header->icmp_seq=seq;
266 memcpy(reqbuf+ICMP_MINLEN, RequestData, RequestSize);
267 icmp_header->icmp_cksum=cksum=in_cksum((u_short*)reqbuf,reqsize);
269 addr.sin_family=AF_INET;
270 addr.sin_addr.s_addr=DestinationAddress;
271 addr.sin_port=0;
273 if (RequestOptions!=NULL) {
274 int val;
275 if (icp->default_opts.OptionsSize==IP_OPTS_UNKNOWN) {
276 int len;
277 /* Before we mess with the options, get the default values */
278 len=sizeof(val);
279 ISOCK_getsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,&len);
280 icp->default_opts.Ttl=val;
282 len=sizeof(val);
283 ISOCK_getsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,&len);
284 icp->default_opts.Tos=val;
285 /* FIXME: missing: handling of IP 'flags', and all the other options */
288 val=RequestOptions->Ttl;
289 ISOCK_setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
290 val=RequestOptions->Tos;
291 ISOCK_setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
292 /* FIXME: missing: handling of IP 'flags', and all the other options */
294 icp->default_opts.OptionsSize=IP_OPTS_CUSTOM;
295 } else if (icp->default_opts.OptionsSize==IP_OPTS_CUSTOM) {
296 int val;
298 /* Restore the default options */
299 val=icp->default_opts.Ttl;
300 ISOCK_setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
301 val=icp->default_opts.Tos;
302 ISOCK_setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
303 /* FIXME: missing: handling of IP 'flags', and all the other options */
305 icp->default_opts.OptionsSize=IP_OPTS_DEFAULT;
308 /* Get ready for receiving the reply
309 * Do it before we send the request to minimize the risk of introducing delays
311 FD_ZERO(&fdr);
312 FD_SET(icp->sid,&fdr);
313 timeout.tv_sec=Timeout/1000;
314 timeout.tv_usec=(Timeout % 1000)*1000;
315 addrlen=sizeof(addr);
316 ier=ReplyBuffer;
317 ip_header=(struct ip *) ((char *) ReplyBuffer+sizeof(ICMP_ECHO_REPLY));
318 endbuf=(char *) ReplyBuffer+ReplySize;
319 maxlen=ReplySize-sizeof(ICMP_ECHO_REPLY);
321 /* Send the packet */
322 TRACE("Sending %d bytes (RequestSize=%d) to %s\n", reqsize, RequestSize, inet_ntoa(addr.sin_addr));
323 #if 0
324 if (TRACE_ON(icmp)){
325 unsigned char* buf=(unsigned char*)reqbuf;
326 int i;
327 printf("Output buffer:\n");
328 for (i=0;i<reqsize;i++)
329 printf("%2x,", buf[i]);
330 printf("\n");
332 #endif
334 gettimeofday(&send_time,NULL);
335 res=ISOCK_sendto(icp->sid, reqbuf, reqsize, 0, (struct sockaddr*)&addr, sizeof(addr));
336 HeapFree(GetProcessHeap (), 0, reqbuf);
337 if (res<0) {
338 if (errno==EMSGSIZE)
339 SetLastError(IP_PACKET_TOO_BIG);
340 else {
341 switch (errno) {
342 case ENETUNREACH:
343 SetLastError(IP_DEST_NET_UNREACHABLE);
344 break;
345 case EHOSTUNREACH:
346 SetLastError(IP_DEST_NET_UNREACHABLE);
347 break;
348 default:
349 TRACE("unknown error: errno=%d\n",errno);
350 SetLastError(ERROR_UNKNOWN);
353 return 0;
356 /* Get the reply */
357 ip_header_len=0; /* because gcc was complaining */
358 while ((res=ISOCK_select(icp->sid+1,&fdr,NULL,NULL,&timeout))>0) {
359 gettimeofday(&recv_time,NULL);
360 res=ISOCK_recvfrom(icp->sid, (char*)ip_header, maxlen, 0, (struct sockaddr*)&addr,&addrlen);
361 TRACE("received %d bytes from %s\n",res, inet_ntoa(addr.sin_addr));
362 ier->Status=IP_REQ_TIMED_OUT;
364 /* Check whether we should ignore this packet */
365 if ((ip_header->ip_p==IPPROTO_ICMP) && (res>=sizeof(struct ip)+ICMP_MINLEN)) {
366 ip_header_len=ip_header->ip_hl << 2;
367 icmp_header=(struct icmp*)(((char*)ip_header)+ip_header_len);
368 TRACE("received an ICMP packet of type,code=%d,%d\n",icmp_header->icmp_type,icmp_header->icmp_code);
369 if (icmp_header->icmp_type==ICMP_ECHOREPLY) {
370 if ((icmp_header->icmp_id==id) && (icmp_header->icmp_seq==seq))
371 ier->Status=IP_SUCCESS;
372 } else {
373 switch (icmp_header->icmp_type) {
374 case ICMP_UNREACH:
375 switch (icmp_header->icmp_code) {
376 case ICMP_UNREACH_HOST:
377 #ifdef ICMP_UNREACH_HOST_UNKNOWN
378 case ICMP_UNREACH_HOST_UNKNOWN:
379 #endif
380 #ifdef ICMP_UNREACH_ISOLATED
381 case ICMP_UNREACH_ISOLATED:
382 #endif
383 #ifdef ICMP_UNREACH_HOST_PROHIB
384 case ICMP_UNREACH_HOST_PROHIB:
385 #endif
386 #ifdef ICMP_UNREACH_TOSHOST
387 case ICMP_UNREACH_TOSHOST:
388 #endif
389 ier->Status=IP_DEST_HOST_UNREACHABLE;
390 break;
391 case ICMP_UNREACH_PORT:
392 ier->Status=IP_DEST_PORT_UNREACHABLE;
393 break;
394 case ICMP_UNREACH_PROTOCOL:
395 ier->Status=IP_DEST_PROT_UNREACHABLE;
396 break;
397 case ICMP_UNREACH_SRCFAIL:
398 ier->Status=IP_BAD_ROUTE;
399 break;
400 default:
401 ier->Status=IP_DEST_NET_UNREACHABLE;
403 break;
404 case ICMP_TIMXCEED:
405 if (icmp_header->icmp_code==ICMP_TIMXCEED_REASS)
406 ier->Status=IP_TTL_EXPIRED_REASSEM;
407 else
408 ier->Status=IP_TTL_EXPIRED_TRANSIT;
409 break;
410 case ICMP_PARAMPROB:
411 ier->Status=IP_PARAM_PROBLEM;
412 break;
413 case ICMP_SOURCEQUENCH:
414 ier->Status=IP_SOURCE_QUENCH;
415 break;
417 if (ier->Status!=IP_REQ_TIMED_OUT) {
418 struct ip* rep_ip_header;
419 struct icmp* rep_icmp_header;
420 /* The ICMP header size of all the packets we accept is the same */
421 rep_ip_header=(struct ip*)(((char*)icmp_header)+ICMP_MINLEN);
422 rep_icmp_header=(struct icmp*)(((char*)rep_ip_header)+(rep_ip_header->ip_hl << 2));
424 /* Make sure that this is really a reply to our packet */
425 if (ip_header_len+ICMP_MINLEN+(rep_ip_header->ip_hl << 2)+ICMP_MINLEN>ip_header->ip_len) {
426 ier->Status=IP_REQ_TIMED_OUT;
427 } else if ((rep_icmp_header->icmp_type!=ICMP_ECHO) ||
428 (rep_icmp_header->icmp_code!=0) ||
429 (rep_icmp_header->icmp_id!=id) ||
430 /* windows doesn't check this checksum, else tracert */
431 /* behind a Linux 2.2 masquerading firewall would fail*/
432 /* (rep_icmp_header->icmp_cksum!=cksum) || */
433 (rep_icmp_header->icmp_seq!=seq)) {
434 /* This was not a reply to one of our packets after all */
435 TRACE("skipping type,code=%d,%d id,seq=%d,%d cksum=%d\n",
436 rep_icmp_header->icmp_type,rep_icmp_header->icmp_code,
437 rep_icmp_header->icmp_id,rep_icmp_header->icmp_seq,
438 rep_icmp_header->icmp_cksum);
439 TRACE("expected type,code=8,0 id,seq=%d,%d cksum=%d\n",
440 id,seq,
441 cksum);
442 ier->Status=IP_REQ_TIMED_OUT;
448 if (ier->Status==IP_REQ_TIMED_OUT) {
449 /* This packet was not for us.
450 * Decrease the timeout so that we don't enter an endless loop even
451 * if we get flooded with ICMP packets that are not for us.
453 timeout.tv_sec=Timeout/1000-(recv_time.tv_sec-send_time.tv_sec);
454 timeout.tv_usec=(Timeout % 1000)*1000+send_time.tv_usec-(recv_time.tv_usec-send_time.tv_usec);
455 if (timeout.tv_usec<0) {
456 timeout.tv_usec+=1000000;
457 timeout.tv_sec--;
459 continue;
460 } else {
461 /* This is a reply to our packet */
462 memcpy(&ier->Address,&ip_header->ip_src,sizeof(IPAddr));
463 /* Status is already set */
464 ier->RoundTripTime=(recv_time.tv_sec-send_time.tv_sec)*1000+(recv_time.tv_usec-send_time.tv_usec)/1000;
465 ier->DataSize=res-ip_header_len-ICMP_MINLEN;
466 ier->Reserved=0;
467 ier->Data=endbuf-ier->DataSize;
468 memmove(ier->Data,((char*)ip_header)+ip_header_len+ICMP_MINLEN,ier->DataSize);
469 ier->Options.Ttl=ip_header->ip_ttl;
470 ier->Options.Tos=ip_header->ip_tos;
471 ier->Options.Flags=ip_header->ip_off >> 13;
472 ier->Options.OptionsSize=ip_header_len-sizeof(struct ip);
473 if (ier->Options.OptionsSize!=0) {
474 ier->Options.OptionsData=(unsigned char *) ier->Data-ier->Options.OptionsSize;
475 /* FIXME: We are supposed to rearrange the option's 'source route' data */
476 memmove(ier->Options.OptionsData,((char*)ip_header)+ip_header_len,ier->Options.OptionsSize);
477 endbuf=ier->Options.OptionsData;
478 } else {
479 ier->Options.OptionsData=NULL;
480 endbuf=ier->Data;
483 /* Prepare for the next packet */
484 ier++;
485 ip_header=(struct ip*)(((char*)ip_header)+sizeof(ICMP_ECHO_REPLY));
486 maxlen=endbuf-(char*)ip_header;
488 /* Check out whether there is more but don't wait this time */
489 timeout.tv_sec=0;
490 timeout.tv_usec=0;
492 FD_ZERO(&fdr);
493 FD_SET(icp->sid,&fdr);
495 res=ier-(ICMP_ECHO_REPLY*)ReplyBuffer;
496 if (res==0)
497 SetLastError(IP_REQ_TIMED_OUT);
498 TRACE("received %d replies\n",res);
499 return res;
503 * Copyright (c) 1989 The Regents of the University of California.
504 * All rights reserved.
506 * This code is derived from software contributed to Berkeley by
507 * Mike Muuss.
509 * Redistribution and use in source and binary forms, with or without
510 * modification, are permitted provided that the following conditions
511 * are met:
512 * 1. Redistributions of source code must retain the above copyright
513 * notice, this list of conditions and the following disclaimer.
514 * 2. Redistributions in binary form must reproduce the above copyright
515 * notice, this list of conditions and the following disclaimer in the
516 * documentation and/or other materials provided with the distribution.
517 * 3. All advertising materials mentioning features or use of this software
518 * must display the following acknowledgement:
519 * This product includes software developed by the University of
520 * California, Berkeley and its contributors.
521 * 4. Neither the name of the University nor the names of its contributors
522 * may be used to endorse or promote products derived from this software
523 * without specific prior written permission.
525 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
526 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
527 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
528 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
529 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
530 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
531 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
532 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
533 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
534 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
535 * SUCH DAMAGE.