Initialize
[sdk/emulator/qemu.git] / slirp / ip_icmp.c
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *      @(#)ip_icmp.c   8.2 (Berkeley) 1/4/94
30  * ip_icmp.c,v 1.7 1995/05/30 08:09:42 rgrimes Exp
31  */
32
33 #include "slirp.h"
34 #include "ip_icmp.h"
35
36 /* The message sent when emulating PING */
37 /* Be nice and tell them it's just a pseudo-ping packet */
38 static const char icmp_ping_msg[] = "This is a pseudo-PING packet used by Slirp to emulate ICMP ECHO-REQUEST packets.\n";
39
40 /* list of actions for icmp_error() on RX of an icmp message */
41 static const int icmp_flush[19] = {
42 /*  ECHO REPLY (0)  */   0,
43                          1,
44                          1,
45 /* DEST UNREACH (3) */   1,
46 /* SOURCE QUENCH (4)*/   1,
47 /* REDIRECT (5) */       1,
48                          1,
49                          1,
50 /* ECHO (8) */           0,
51 /* ROUTERADVERT (9) */   1,
52 /* ROUTERSOLICIT (10) */ 1,
53 /* TIME EXCEEDED (11) */ 1,
54 /* PARAMETER PROBLEM (12) */ 1,
55 /* TIMESTAMP (13) */     0,
56 /* TIMESTAMP REPLY (14) */ 0,
57 /* INFO (15) */          0,
58 /* INFO REPLY (16) */    0,
59 /* ADDR MASK (17) */     0,
60 /* ADDR MASK REPLY (18) */ 0
61 };
62
63 int icmp_attach(struct socket *so);
64 void icmp_detach(struct socket *so);
65 int icmp_cksum(u_short *p, int n);
66
67 int
68 icmp_attach(struct socket *so)
69 {
70   /* same as udp_attach except socket creation */
71   if((so->s = qemu_socket(AF_INET,SOCK_RAW,IPPROTO_ICMP)) != -1) {
72     so->so_expire = curtime + SO_EXPIRE;
73     insque(so, &so->slirp->udb);
74   }
75   return(so->s);
76 }
77
78 void
79 icmp_detach(struct socket *so)
80 {
81   /* same as udp_detach */
82   closesocket(so->s);
83   sofree(so);
84 }
85
86 int
87 icmp_cksum(u_short *p, int n)
88 {
89     register u_short answer;
90     register long sum = 0;
91     u_short odd_byte = 0;
92
93     while( n > 1 )
94     {
95         sum += *p++;
96         n -= 2;
97    
98     }/* WHILE */
99
100
101     /* mop up an odd byte, if necessary */
102     if( n == 1 )
103     {
104         *( u_char* )( &odd_byte ) = *( u_char* )p;
105         sum += odd_byte;
106    
107     }/* IF */
108
109     sum = ( sum >> 16 ) + ( sum & 0xffff );    /* add hi 16 to low 16 */
110     sum += ( sum >> 16 );                    /* add carry */
111     answer = ~sum;                            /* ones-complement, truncate*/
112    
113     return ( answer );
114
115 } /* in_cksum() */
116
117 /*
118  * Process a received ICMP message.
119  */
120 void
121 icmp_input(struct mbuf *m, int hlen)
122 {
123   register struct icmp *icp;
124   register struct ip *ip=mtod(m, struct ip *);
125   int icmplen=ip->ip_len;
126   Slirp *slirp = m->slirp;
127
128   DEBUG_CALL("icmp_input");
129   DEBUG_ARG("m = %lx", (long )m);
130   DEBUG_ARG("m_len = %d", m->m_len);
131
132   /*
133    * Locate icmp structure in mbuf, and check
134    * that its not corrupted and of at least minimum length.
135    */
136   if (icmplen < ICMP_MINLEN) {          /* min 8 bytes payload */
137   freeit:
138     m_freem(m);
139     goto end_error;
140   }
141
142   m->m_len -= hlen;
143   m->m_data += hlen;
144   icp = mtod(m, struct icmp *);
145   if (cksum(m, icmplen)) {
146     goto freeit;
147   }
148   m->m_len += hlen;
149   m->m_data -= hlen;
150
151   DEBUG_ARG("icmp_type = %d", icp->icmp_type);
152   switch (icp->icmp_type) {
153   case ICMP_ECHO:
154     icp->icmp_type = ICMP_ECHOREPLY;
155     ip->ip_len += hlen;              /* since ip_input subtracts this */
156     if (ip->ip_dst.s_addr == slirp->vhost_addr.s_addr) {
157       icmp_reflect(m);
158 #ifndef _WIN32
159     } else if( getuid() != 0 ) {
160       char commands[64];
161       int code;
162
163       sprintf( commands, "ping -c 1 %s", inet_ntoa(ip->ip_dst) );
164       code = system( commands ); 
165
166       if( WIFEXITED(code) && WEXITSTATUS(code) == 0 )
167         icmp_reflect(m);
168       else
169         icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_NET, 0, "ping failed");
170 #endif
171     } else {
172       char icmp_buf[128] ;
173       struct icmp *picmp = (struct icmp *)icmp_buf; 
174       struct socket *so;
175       struct sockaddr_in addr;
176       if ((so = socreate(slirp)) == NULL) goto freeit;
177       if(icmp_attach(so) == -1) {
178         DEBUG_MISC((dfd,"icmp_input udp_attach errno = %d-%s\n",
179                     errno,strerror(errno)));
180         sofree(so);
181         m_free(m);
182         goto end_error;
183       }
184       so->so_m = m;
185       so->so_faddr = ip->ip_dst;
186       so->so_fport = htons(7);
187       so->so_laddr = ip->ip_src;
188       so->so_lport = htons(9);
189       so->so_iptos = ip->ip_tos;
190       so->so_type = IPPROTO_ICMP;
191       so->so_state = SS_ISFCONNECTED;
192
193       /* Send the packet */
194       addr.sin_family = AF_INET;
195       if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==
196           slirp->vnetwork_addr.s_addr) {
197         /* It's an alias */
198         if (so->so_faddr.s_addr == slirp->vnameserver_addr.s_addr) {
199           if (get_dns_addr(&addr.sin_addr) < 0)
200             addr.sin_addr = loopback_addr;
201         } else {
202           addr.sin_addr = loopback_addr;
203         }
204       } else {
205         addr.sin_addr = so->so_faddr;
206       }
207       addr.sin_port = so->so_fport;
208
209       picmp->icmp_type = ICMP_ECHO;
210       picmp->icmp_code = 0;
211       picmp->icmp_cksum = 0;
212       picmp->icmp_id = icp->icmp_id;
213       picmp->icmp_seq = icp->icmp_seq;
214       strcpy(icmp_buf+8, icmp_ping_msg);
215       picmp->icmp_cksum = icmp_cksum((u_short *)picmp, sizeof(icmp_ping_msg)+8);
216
217       if(sendto(so->s, picmp, sizeof(icmp_ping_msg)+8, 0,
218                 (struct sockaddr *)&addr, sizeof(addr)) == -1) {
219         DEBUG_MISC((dfd,"icmp_input udp sendto tx errno = %d-%s\n",
220                     errno,strerror(errno)));
221         icmp_error(m, ICMP_UNREACH,ICMP_UNREACH_NET, 0,strerror(errno));
222         icmp_detach(so);
223       }
224     } /* if ip->ip_dst.s_addr == alias_addr.s_addr */
225     break;
226   case ICMP_UNREACH:
227     /* XXX? report error? close socket? */
228   case ICMP_TIMXCEED:
229   case ICMP_PARAMPROB:
230   case ICMP_SOURCEQUENCH:
231   case ICMP_TSTAMP:
232   case ICMP_MASKREQ:
233   case ICMP_REDIRECT:
234     m_freem(m);
235     break;
236
237   default:
238     m_freem(m);
239   } /* swith */
240
241 end_error:
242   /* m is m_free()'d xor put in a socket xor or given to ip_send */
243   return;
244 }
245
246
247 /*
248  *      Send an ICMP message in response to a situation
249  *
250  *      RFC 1122: 3.2.2 MUST send at least the IP header and 8 bytes of header. MAY send more (we do).
251  *                      MUST NOT change this header information.
252  *                      MUST NOT reply to a multicast/broadcast IP address.
253  *                      MUST NOT reply to a multicast/broadcast MAC address.
254  *                      MUST reply to only the first fragment.
255  */
256 /*
257  * Send ICMP_UNREACH back to the source regarding msrc.
258  * mbuf *msrc is used as a template, but is NOT m_free()'d.
259  * It is reported as the bad ip packet.  The header should
260  * be fully correct and in host byte order.
261  * ICMP fragmentation is illegal.  All machines must accept 576 bytes in one
262  * packet.  The maximum payload is 576-20(ip hdr)-8(icmp hdr)=548
263  */
264
265 #define ICMP_MAXDATALEN (IP_MSS-28)
266 void
267 icmp_error(struct mbuf *msrc, u_char type, u_char code, int minsize,
268            const char *message)
269 {
270   unsigned hlen, shlen, s_ip_len;
271   register struct ip *ip;
272   register struct icmp *icp;
273   register struct mbuf *m;
274
275   DEBUG_CALL("icmp_error");
276   DEBUG_ARG("msrc = %lx", (long )msrc);
277   DEBUG_ARG("msrc_len = %d", msrc->m_len);
278
279   if(type!=ICMP_UNREACH && type!=ICMP_TIMXCEED) goto end_error;
280
281   /* check msrc */
282   if(!msrc) goto end_error;
283   ip = mtod(msrc, struct ip *);
284 #ifdef DEBUG
285   { char bufa[20], bufb[20];
286     strcpy(bufa, inet_ntoa(ip->ip_src));
287     strcpy(bufb, inet_ntoa(ip->ip_dst));
288     DEBUG_MISC((dfd, " %.16s to %.16s\n", bufa, bufb));
289   }
290 #endif
291   if(ip->ip_off & IP_OFFMASK) goto end_error;    /* Only reply to fragment 0 */
292
293   shlen=ip->ip_hl << 2;
294   s_ip_len=ip->ip_len;
295   if(ip->ip_p == IPPROTO_ICMP) {
296     icp = (struct icmp *)((char *)ip + shlen);
297     /*
298      *  Assume any unknown ICMP type is an error. This isn't
299      *  specified by the RFC, but think about it..
300      */
301     if(icp->icmp_type>18 || icmp_flush[icp->icmp_type]) goto end_error;
302   }
303
304   /* make a copy */
305   m = m_get(msrc->slirp);
306   if (!m) {
307       goto end_error;
308   }
309
310   { int new_m_size;
311     new_m_size=sizeof(struct ip )+ICMP_MINLEN+msrc->m_len+ICMP_MAXDATALEN;
312     if(new_m_size>m->m_size) m_inc(m, new_m_size);
313   }
314   memcpy(m->m_data, msrc->m_data, msrc->m_len);
315   m->m_len = msrc->m_len;                        /* copy msrc to m */
316
317   /* make the header of the reply packet */
318   ip  = mtod(m, struct ip *);
319   hlen= sizeof(struct ip );     /* no options in reply */
320
321   /* fill in icmp */
322   m->m_data += hlen;
323   m->m_len -= hlen;
324
325   icp = mtod(m, struct icmp *);
326
327   if(minsize) s_ip_len=shlen+ICMP_MINLEN;   /* return header+8b only */
328   else if(s_ip_len>ICMP_MAXDATALEN)         /* maximum size */
329     s_ip_len=ICMP_MAXDATALEN;
330
331   m->m_len=ICMP_MINLEN+s_ip_len;        /* 8 bytes ICMP header */
332
333   /* min. size = 8+sizeof(struct ip)+8 */
334
335   icp->icmp_type = type;
336   icp->icmp_code = code;
337   icp->icmp_id = 0;
338   icp->icmp_seq = 0;
339
340   memcpy(&icp->icmp_ip, msrc->m_data, s_ip_len);   /* report the ip packet */
341   HTONS(icp->icmp_ip.ip_len);
342   HTONS(icp->icmp_ip.ip_id);
343   HTONS(icp->icmp_ip.ip_off);
344
345 #ifdef DEBUG
346   if(message) {           /* DEBUG : append message to ICMP packet */
347     int message_len;
348     char *cpnt;
349     message_len=strlen(message);
350     if(message_len>ICMP_MAXDATALEN) message_len=ICMP_MAXDATALEN;
351     cpnt=(char *)m->m_data+m->m_len;
352     memcpy(cpnt, message, message_len);
353     m->m_len+=message_len;
354   }
355 #endif
356
357   icp->icmp_cksum = 0;
358   icp->icmp_cksum = cksum(m, m->m_len);
359
360   m->m_data -= hlen;
361   m->m_len += hlen;
362
363   /* fill in ip */
364   ip->ip_hl = hlen >> 2;
365   ip->ip_len = m->m_len;
366
367   ip->ip_tos=((ip->ip_tos & 0x1E) | 0xC0);  /* high priority for errors */
368
369   ip->ip_ttl = MAXTTL;
370   ip->ip_p = IPPROTO_ICMP;
371   ip->ip_dst = ip->ip_src;    /* ip adresses */
372   ip->ip_src = m->slirp->vhost_addr;
373
374   (void ) ip_output((struct socket *)NULL, m);
375
376 end_error:
377   return;
378 }
379 #undef ICMP_MAXDATALEN
380
381 /*
382  * Reflect the ip packet back to the source
383  */
384 void
385 icmp_reflect(struct mbuf *m)
386 {
387   register struct ip *ip = mtod(m, struct ip *);
388   int hlen = ip->ip_hl << 2;
389   int optlen = hlen - sizeof(struct ip );
390   register struct icmp *icp;
391
392   /*
393    * Send an icmp packet back to the ip level,
394    * after supplying a checksum.
395    */
396   m->m_data += hlen;
397   m->m_len -= hlen;
398   icp = mtod(m, struct icmp *);
399
400   icp->icmp_cksum = 0;
401   icp->icmp_cksum = cksum(m, ip->ip_len - hlen);
402
403   m->m_data -= hlen;
404   m->m_len += hlen;
405
406   /* fill in ip */
407   if (optlen > 0) {
408     /*
409      * Strip out original options by copying rest of first
410      * mbuf's data back, and adjust the IP length.
411      */
412     memmove((caddr_t)(ip + 1), (caddr_t)ip + hlen,
413             (unsigned )(m->m_len - hlen));
414     hlen -= optlen;
415     ip->ip_hl = hlen >> 2;
416     ip->ip_len -= optlen;
417     m->m_len -= optlen;
418   }
419
420   ip->ip_ttl = MAXTTL;
421   { /* swap */
422     struct in_addr icmp_dst;
423     icmp_dst = ip->ip_dst;
424     ip->ip_dst = ip->ip_src;
425     ip->ip_src = icmp_dst;
426   }
427
428   (void ) ip_output((struct socket *)NULL, m);
429 }