wintrust: Use path in WIN_TRUST_SUBJECT_FILE structure rather than assuming a path...
[wine] / dlls / icmp / icmp_main.c
1 /*
2  * ICMP
3  *
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  *
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.
13  *
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.
18  *
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
22  */
23
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  * - Is it correct to use malloc for the internal buffer, for allocating the
31  *   handle's structure?
32  * - This API should probably be thread safe. Is it really?
33  * - Using the winsock functions has not been tested.
34  */
35
36 #include "config.h"
37
38 #include <sys/types.h>
39 #ifdef HAVE_SYS_SOCKET_H
40 # include <sys/socket.h>
41 #endif
42 #ifdef HAVE_NETDB_H
43 # include <netdb.h>
44 #endif
45 #ifdef HAVE_NETINET_IN_SYSTM_H
46 # include <netinet/in_systm.h>
47 #endif
48 #ifdef HAVE_NETINET_IN_H
49 # include <netinet/in.h>
50 #endif
51
52 #ifdef HAVE_SYS_TIME_H
53 # include <sys/time.h>
54 #endif
55 #include <stdarg.h>
56 #include <string.h>
57 #include <errno.h>
58 #ifdef HAVE_UNISTD_H
59 # include <unistd.h>
60 #endif
61 #ifdef HAVE_ARPA_INET_H
62 # include <arpa/inet.h>
63 #endif
64 #ifdef HAVE_SYS_POLL_H
65 # include <sys/poll.h>
66 #endif
67
68 #include "windef.h"
69 #include "winbase.h"
70 #include "winerror.h"
71 #include "ipexport.h"
72 #include "icmpapi.h"
73 #include "wine/debug.h"
74
75 /* Set up endianness macros for the ip and ip_icmp BSD headers */
76 #ifndef BIG_ENDIAN
77 #define BIG_ENDIAN       4321
78 #endif
79 #ifndef LITTLE_ENDIAN
80 #define LITTLE_ENDIAN    1234
81 #endif
82 #ifndef BYTE_ORDER
83 #ifdef WORDS_BIGENDIAN
84 #define BYTE_ORDER       BIG_ENDIAN
85 #else
86 #define BYTE_ORDER       LITTLE_ENDIAN
87 #endif
88 #endif /* BYTE_ORDER */
89
90 #define u_int16_t  WORD
91 #define u_int32_t  DWORD
92
93 /* These are BSD headers. We use these here because they are needed on
94  * libc5 Linux systems. On other platforms they are usually simply more
95  * complete than the native stuff, and cause less portability problems
96  * so we use them anyway.
97  */
98 #include "ip.h"
99 #include "ip_icmp.h"
100
101
102 WINE_DEFAULT_DEBUG_CHANNEL(icmp);
103
104
105 typedef struct {
106     int sid;
107     IP_OPTION_INFORMATION default_opts;
108 } icmp_t;
109
110 #define IP_OPTS_UNKNOWN     0
111 #define IP_OPTS_DEFAULT     1
112 #define IP_OPTS_CUSTOM      2
113
114 /* The sequence number is unique process wide, so that all threads
115  * have a distinct sequence number.
116  */
117 static LONG icmp_sequence=0;
118
119 static int in_cksum(u_short *addr, int len)
120 {
121     int nleft=len;
122     u_short *w = addr;
123     int sum = 0;
124     u_short answer = 0;
125
126     while (nleft > 1) {
127         sum += *w++;
128         nleft -= 2;
129     }
130
131     if (nleft == 1) {
132         *(u_char *)(&answer) = *(u_char *)w;
133         sum += answer;
134     }
135
136     sum = (sum >> 16) + (sum & 0xffff);
137     sum  += (sum >> 16);
138     answer = ~sum;
139     return(answer);
140 }
141
142
143
144 /*
145  * Exported Routines.
146  */
147
148 /***********************************************************************
149  *              IcmpCreateFile (ICMP.@)
150  */
151 HANDLE WINAPI IcmpCreateFile(VOID)
152 {
153     icmp_t* icp;
154
155     int sid=socket(AF_INET,SOCK_RAW,IPPROTO_ICMP);
156     if (sid < 0) {
157         MESSAGE("WARNING: Trying to use ICMP (network ping) will fail unless running as root\n");
158         SetLastError(ERROR_ACCESS_DENIED);
159         return INVALID_HANDLE_VALUE;
160     }
161
162     icp=HeapAlloc(GetProcessHeap(), 0, sizeof(*icp));
163     if (icp==NULL) {
164         SetLastError(IP_NO_RESOURCES);
165         return INVALID_HANDLE_VALUE;
166     }
167     icp->sid=sid;
168     icp->default_opts.OptionsSize=IP_OPTS_UNKNOWN;
169     return (HANDLE)icp;
170 }
171
172
173 /***********************************************************************
174  *              IcmpCloseHandle (ICMP.@)
175  */
176 BOOL WINAPI IcmpCloseHandle(HANDLE  IcmpHandle)
177 {
178     icmp_t* icp=(icmp_t*)IcmpHandle;
179     if (IcmpHandle==INVALID_HANDLE_VALUE) {
180         /* FIXME: in fact win98 seems to ignore the handle value !!! */
181         SetLastError(ERROR_INVALID_HANDLE);
182         return FALSE;
183     }
184
185     shutdown(icp->sid,2);
186     HeapFree(GetProcessHeap (), 0, icp);
187     return TRUE;
188 }
189
190
191 /***********************************************************************
192  *              IcmpSendEcho (ICMP.@)
193  */
194 DWORD WINAPI IcmpSendEcho(
195     HANDLE                   IcmpHandle,
196     IPAddr                   DestinationAddress,
197     LPVOID                   RequestData,
198     WORD                     RequestSize,
199     PIP_OPTION_INFORMATION   RequestOptions,
200     LPVOID                   ReplyBuffer,
201     DWORD                    ReplySize,
202     DWORD                    Timeout
203     )
204 {
205     icmp_t* icp=(icmp_t*)IcmpHandle;
206     unsigned char* reqbuf;
207     int reqsize;
208
209     struct icmp_echo_reply* ier;
210     struct ip* ip_header;
211     struct icmp* icmp_header;
212     char* endbuf;
213     int ip_header_len;
214     int maxlen;
215     struct pollfd fdr;
216     DWORD send_time,recv_time;
217     struct sockaddr_in addr;
218     unsigned int addrlen;
219     unsigned short id,seq,cksum;
220     int res;
221
222     if (IcmpHandle==INVALID_HANDLE_VALUE) {
223         /* FIXME: in fact win98 seems to ignore the handle value !!! */
224         SetLastError(ERROR_INVALID_HANDLE);
225         return 0;
226     }
227
228     if (ReplySize<sizeof(ICMP_ECHO_REPLY)+ICMP_MINLEN) {
229         SetLastError(IP_BUF_TOO_SMALL);
230         return 0;
231     }
232     /* check the request size against SO_MAX_MSG_SIZE using getsockopt */
233
234     /* Prepare the request */
235     id=getpid() & 0xFFFF;
236     seq=InterlockedIncrement(&icmp_sequence) & 0xFFFF;
237
238     reqsize=ICMP_MINLEN+RequestSize;
239     reqbuf=HeapAlloc(GetProcessHeap(), 0, reqsize);
240     if (reqbuf==NULL) {
241         SetLastError(ERROR_OUTOFMEMORY);
242         return 0;
243     }
244
245     icmp_header=(struct icmp*)reqbuf;
246     icmp_header->icmp_type=ICMP_ECHO;
247     icmp_header->icmp_code=0;
248     icmp_header->icmp_cksum=0;
249     icmp_header->icmp_id=id;
250     icmp_header->icmp_seq=seq;
251     memcpy(reqbuf+ICMP_MINLEN, RequestData, RequestSize);
252     icmp_header->icmp_cksum=cksum=in_cksum((u_short*)reqbuf,reqsize);
253
254     addr.sin_family=AF_INET;
255     addr.sin_addr.s_addr=DestinationAddress;
256     addr.sin_port=0;
257
258     if (RequestOptions!=NULL) {
259         int val;
260         if (icp->default_opts.OptionsSize==IP_OPTS_UNKNOWN) {
261             unsigned int len;
262             /* Before we mess with the options, get the default values */
263             len=sizeof(val);
264             getsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,&len);
265             icp->default_opts.Ttl=val;
266
267             len=sizeof(val);
268             getsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,&len);
269             icp->default_opts.Tos=val;
270             /* FIXME: missing: handling of IP 'flags', and all the other options */
271         }
272
273         val=RequestOptions->Ttl;
274         setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
275         val=RequestOptions->Tos;
276         setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
277         /* FIXME:  missing: handling of IP 'flags', and all the other options */
278
279         icp->default_opts.OptionsSize=IP_OPTS_CUSTOM;
280     } else if (icp->default_opts.OptionsSize==IP_OPTS_CUSTOM) {
281         int val;
282
283         /* Restore the default options */
284         val=icp->default_opts.Ttl;
285         setsockopt(icp->sid,IPPROTO_IP,IP_TTL,(char *)&val,sizeof(val));
286         val=icp->default_opts.Tos;
287         setsockopt(icp->sid,IPPROTO_IP,IP_TOS,(char *)&val,sizeof(val));
288         /* FIXME: missing: handling of IP 'flags', and all the other options */
289
290         icp->default_opts.OptionsSize=IP_OPTS_DEFAULT;
291     }
292
293     /* Get ready for receiving the reply
294      * Do it before we send the request to minimize the risk of introducing delays
295      */
296     fdr.fd = icp->sid;
297     fdr.events = POLLIN;
298     addrlen=sizeof(addr);
299     ier=ReplyBuffer;
300     ip_header=(struct ip *) ((char *) ReplyBuffer+sizeof(ICMP_ECHO_REPLY));
301     endbuf=(char *) ReplyBuffer+ReplySize;
302     maxlen=ReplySize-sizeof(ICMP_ECHO_REPLY);
303
304     /* Send the packet */
305     TRACE("Sending %d bytes (RequestSize=%d) to %s\n", reqsize, RequestSize, inet_ntoa(addr.sin_addr));
306 #if 0
307     if (TRACE_ON(icmp)){
308         unsigned char* buf=(unsigned char*)reqbuf;
309         int i;
310         printf("Output buffer:\n");
311         for (i=0;i<reqsize;i++)
312             printf("%2x,", buf[i]);
313         printf("\n");
314     }
315 #endif
316
317     send_time = GetTickCount();
318     res=sendto(icp->sid, reqbuf, reqsize, 0, (struct sockaddr*)&addr, sizeof(addr));
319     HeapFree(GetProcessHeap (), 0, reqbuf);
320     if (res<0) {
321         if (errno==EMSGSIZE)
322             SetLastError(IP_PACKET_TOO_BIG);
323         else {
324             switch (errno) {
325             case ENETUNREACH:
326                 SetLastError(IP_DEST_NET_UNREACHABLE);
327                 break;
328             case EHOSTUNREACH:
329                 SetLastError(IP_DEST_HOST_UNREACHABLE);
330                 break;
331             default:
332                 TRACE("unknown error: errno=%d\n",errno);
333                 SetLastError(IP_GENERAL_FAILURE);
334             }
335         }
336         return 0;
337     }
338
339     /* Get the reply */
340     ip_header_len=0; /* because gcc was complaining */
341     while ((res=poll(&fdr,1,Timeout))>0) {
342         recv_time = GetTickCount();
343         res=recvfrom(icp->sid, (char*)ip_header, maxlen, 0, (struct sockaddr*)&addr,&addrlen);
344         TRACE("received %d bytes from %s\n",res, inet_ntoa(addr.sin_addr));
345         ier->Status=IP_REQ_TIMED_OUT;
346
347         /* Check whether we should ignore this packet */
348         if ((ip_header->ip_p==IPPROTO_ICMP) && (res>=sizeof(struct ip)+ICMP_MINLEN)) {
349             ip_header_len=ip_header->ip_hl << 2;
350             icmp_header=(struct icmp*)(((char*)ip_header)+ip_header_len);
351             TRACE("received an ICMP packet of type,code=%d,%d\n",icmp_header->icmp_type,icmp_header->icmp_code);
352             if (icmp_header->icmp_type==ICMP_ECHOREPLY) {
353                 if ((icmp_header->icmp_id==id) && (icmp_header->icmp_seq==seq))
354                     ier->Status=IP_SUCCESS;
355             } else {
356                 switch (icmp_header->icmp_type) {
357                 case ICMP_UNREACH:
358                     switch (icmp_header->icmp_code) {
359                     case ICMP_UNREACH_HOST:
360 #ifdef ICMP_UNREACH_HOST_UNKNOWN
361                     case ICMP_UNREACH_HOST_UNKNOWN:
362 #endif
363 #ifdef ICMP_UNREACH_ISOLATED
364                     case ICMP_UNREACH_ISOLATED:
365 #endif
366 #ifdef ICMP_UNREACH_HOST_PROHIB
367                     case ICMP_UNREACH_HOST_PROHIB:
368 #endif
369 #ifdef ICMP_UNREACH_TOSHOST
370                     case ICMP_UNREACH_TOSHOST:
371 #endif
372                         ier->Status=IP_DEST_HOST_UNREACHABLE;
373                         break;
374                     case ICMP_UNREACH_PORT:
375                         ier->Status=IP_DEST_PORT_UNREACHABLE;
376                         break;
377                     case ICMP_UNREACH_PROTOCOL:
378                         ier->Status=IP_DEST_PROT_UNREACHABLE;
379                         break;
380                     case ICMP_UNREACH_SRCFAIL:
381                         ier->Status=IP_BAD_ROUTE;
382                         break;
383                     default:
384                         ier->Status=IP_DEST_NET_UNREACHABLE;
385                     }
386                     break;
387                 case ICMP_TIMXCEED:
388                     if (icmp_header->icmp_code==ICMP_TIMXCEED_REASS)
389                         ier->Status=IP_TTL_EXPIRED_REASSEM;
390                     else
391                         ier->Status=IP_TTL_EXPIRED_TRANSIT;
392                     break;
393                 case ICMP_PARAMPROB:
394                     ier->Status=IP_PARAM_PROBLEM;
395                     break;
396                 case ICMP_SOURCEQUENCH:
397                     ier->Status=IP_SOURCE_QUENCH;
398                     break;
399                 }
400                 if (ier->Status!=IP_REQ_TIMED_OUT) {
401                     struct ip* rep_ip_header;
402                     struct icmp* rep_icmp_header;
403                     /* The ICMP header size of all the packets we accept is the same */
404                     rep_ip_header=(struct ip*)(((char*)icmp_header)+ICMP_MINLEN);
405                     rep_icmp_header=(struct icmp*)(((char*)rep_ip_header)+(rep_ip_header->ip_hl << 2));
406
407                     /* Make sure that this is really a reply to our packet */
408                     if (ip_header_len+ICMP_MINLEN+(rep_ip_header->ip_hl << 2)+ICMP_MINLEN>ip_header->ip_len) {
409                         ier->Status=IP_REQ_TIMED_OUT;
410                     } else if ((rep_icmp_header->icmp_type!=ICMP_ECHO) ||
411                         (rep_icmp_header->icmp_code!=0) ||
412                         (rep_icmp_header->icmp_id!=id) ||
413                         /* windows doesn't check this checksum, else tracert */
414                         /* behind a Linux 2.2 masquerading firewall would fail*/
415                         /* (rep_icmp_header->icmp_cksum!=cksum) || */
416                         (rep_icmp_header->icmp_seq!=seq)) {
417                         /* This was not a reply to one of our packets after all */
418                         TRACE("skipping type,code=%d,%d id,seq=%d,%d cksum=%d\n",
419                             rep_icmp_header->icmp_type,rep_icmp_header->icmp_code,
420                             rep_icmp_header->icmp_id,rep_icmp_header->icmp_seq,
421                             rep_icmp_header->icmp_cksum);
422                         TRACE("expected type,code=8,0 id,seq=%d,%d cksum=%d\n",
423                             id,seq,
424                             cksum);
425                         ier->Status=IP_REQ_TIMED_OUT;
426                     }
427                 }
428             }
429         }
430
431         if (ier->Status==IP_REQ_TIMED_OUT) {
432             /* This packet was not for us.
433              * Decrease the timeout so that we don't enter an endless loop even
434              * if we get flooded with ICMP packets that are not for us.
435              */
436             DWORD t = (recv_time - send_time);
437             if (Timeout > t) Timeout -= t;
438             else             Timeout = 0;
439             continue;
440         } else {
441             /* This is a reply to our packet */
442             memcpy(&ier->Address,&ip_header->ip_src,sizeof(IPAddr));
443             /* Status is already set */
444             ier->RoundTripTime= recv_time - send_time;
445             ier->DataSize=res-ip_header_len-ICMP_MINLEN;
446             ier->Reserved=0;
447             ier->Data=endbuf-ier->DataSize;
448             memmove(ier->Data,((char*)ip_header)+ip_header_len+ICMP_MINLEN,ier->DataSize);
449             ier->Options.Ttl=ip_header->ip_ttl;
450             ier->Options.Tos=ip_header->ip_tos;
451             ier->Options.Flags=ip_header->ip_off >> 13;
452             ier->Options.OptionsSize=ip_header_len-sizeof(struct ip);
453             if (ier->Options.OptionsSize!=0) {
454                 ier->Options.OptionsData=(unsigned char *) ier->Data-ier->Options.OptionsSize;
455                 /* FIXME: We are supposed to rearrange the option's 'source route' data */
456                 memmove(ier->Options.OptionsData,((char*)ip_header)+ip_header_len,ier->Options.OptionsSize);
457                 endbuf=(char*)ier->Options.OptionsData;
458             } else {
459                 ier->Options.OptionsData=NULL;
460                 endbuf=ier->Data;
461             }
462
463             /* Prepare for the next packet */
464             ier++;
465             ip_header=(struct ip*)(((char*)ip_header)+sizeof(ICMP_ECHO_REPLY));
466             maxlen=endbuf-(char*)ip_header;
467
468             /* Check out whether there is more but don't wait this time */
469             Timeout=0;
470         }
471     }
472     res=ier-(ICMP_ECHO_REPLY*)ReplyBuffer;
473     if (res==0)
474         SetLastError(IP_REQ_TIMED_OUT);
475     TRACE("received %d replies\n",res);
476     return res;
477 }
478
479 /*
480  * Copyright (c) 1989 The Regents of the University of California.
481  * All rights reserved.
482  *
483  * This code is derived from software contributed to Berkeley by
484  * Mike Muuss.
485  *
486  * Redistribution and use in source and binary forms, with or without
487  * modification, are permitted provided that the following conditions
488  * are met:
489  * 1. Redistributions of source code must retain the above copyright
490  *    notice, this list of conditions and the following disclaimer.
491  * 2. Redistributions in binary form must reproduce the above copyright
492  *    notice, this list of conditions and the following disclaimer in the
493  *    documentation and/or other materials provided with the distribution.
494  * 3. Neither the name of the University nor the names of its contributors
495  *    may be used to endorse or promote products derived from this software
496  *    without specific prior written permission.
497  *
498  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
499  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
500  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
501  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
502  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
503  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
504  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
505  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
506  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
507  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
508  * SUCH DAMAGE.
509  *
510  */