vserver 1.9.5.x5
[linux-2.6.git] / net / appletalk / ddp.c
1 /*
2  *      DDP:    An implementation of the AppleTalk DDP protocol for
3  *              Ethernet 'ELAP'.
4  *
5  *              Alan Cox  <Alan.Cox@linux.org>
6  *
7  *              With more than a little assistance from
8  *
9  *              Wesley Craig <netatalk@umich.edu>
10  *
11  *      Fixes:
12  *              Neil Horman             :       Added missing device ioctls
13  *              Michael Callahan        :       Made routing work
14  *              Wesley Craig            :       Fix probing to listen to a
15  *                                              passed node id.
16  *              Alan Cox                :       Added send/recvmsg support
17  *              Alan Cox                :       Moved at. to protinfo in
18  *                                              socket.
19  *              Alan Cox                :       Added firewall hooks.
20  *              Alan Cox                :       Supports new ARPHRD_LOOPBACK
21  *              Christer Weinigel       :       Routing and /proc fixes.
22  *              Bradford Johnson        :       LocalTalk.
23  *              Tom Dyas                :       Module support.
24  *              Alan Cox                :       Hooks for PPP (based on the
25  *                                              LocalTalk hook).
26  *              Alan Cox                :       Posix bits
27  *              Alan Cox/Mike Freeman   :       Possible fix to NBP problems
28  *              Bradford Johnson        :       IP-over-DDP (experimental)
29  *              Jay Schulist            :       Moved IP-over-DDP to its own
30  *                                              driver file. (ipddp.c & ipddp.h)
31  *              Jay Schulist            :       Made work as module with 
32  *                                              AppleTalk drivers, cleaned it.
33  *              Rob Newberry            :       Added proxy AARP and AARP
34  *                                              procfs, moved probing to AARP
35  *                                              module.
36  *              Adrian Sun/ 
37  *              Michael Zuelsdorff      :       fix for net.0 packets. don't 
38  *                                              allow illegal ether/tokentalk
39  *                                              port assignment. we lose a 
40  *                                              valid localtalk port as a 
41  *                                              result.
42  *              Arnaldo C. de Melo      :       Cleanup, in preparation for
43  *                                              shared skb support 8)
44  *              Arnaldo C. de Melo      :       Move proc stuff to atalk_proc.c,
45  *                                              use seq_file
46  *
47  *              This program is free software; you can redistribute it and/or
48  *              modify it under the terms of the GNU General Public License
49  *              as published by the Free Software Foundation; either version
50  *              2 of the License, or (at your option) any later version.
51  * 
52  */
53
54 #include <linux/config.h>
55 #include <linux/module.h>
56 #include <linux/tcp.h>
57 #include <linux/if_arp.h>
58 #include <linux/termios.h>      /* For TIOCOUTQ/INQ */
59 #include <net/datalink.h>
60 #include <net/psnap.h>
61 #include <net/sock.h>
62 #include <net/route.h>
63 #include <linux/atalk.h>
64
65 struct datalink_proto *ddp_dl, *aarp_dl;
66 static struct proto_ops atalk_dgram_ops;
67
68 /**************************************************************************\
69 *                                                                          *
70 * Handlers for the socket list.                                            *
71 *                                                                          *
72 \**************************************************************************/
73
74 HLIST_HEAD(atalk_sockets);
75 DEFINE_RWLOCK(atalk_sockets_lock);
76
77 static inline void __atalk_insert_socket(struct sock *sk)
78 {
79         sk_add_node(sk, &atalk_sockets);
80 }
81
82 static inline void atalk_remove_socket(struct sock *sk)
83 {
84         write_lock_bh(&atalk_sockets_lock);
85         sk_del_node_init(sk);
86         write_unlock_bh(&atalk_sockets_lock);
87 }
88
89 static struct sock *atalk_search_socket(struct sockaddr_at *to,
90                                         struct atalk_iface *atif)
91 {
92         struct sock *s;
93         struct hlist_node *node;
94
95         read_lock_bh(&atalk_sockets_lock);
96         sk_for_each(s, node, &atalk_sockets) {
97                 struct atalk_sock *at = at_sk(s);
98
99                 if (to->sat_port != at->src_port)
100                         continue;
101
102                 if (to->sat_addr.s_net == ATADDR_ANYNET &&
103                     to->sat_addr.s_node == ATADDR_BCAST &&
104                     at->src_net == atif->address.s_net)
105                         goto found;
106
107                 if (to->sat_addr.s_net == at->src_net &&
108                     (to->sat_addr.s_node == at->src_node ||
109                      to->sat_addr.s_node == ATADDR_BCAST ||
110                      to->sat_addr.s_node == ATADDR_ANYNODE))
111                         goto found;
112
113                 /* XXXX.0 -- we got a request for this router. make sure
114                  * that the node is appropriately set. */
115                 if (to->sat_addr.s_node == ATADDR_ANYNODE &&
116                     to->sat_addr.s_net != ATADDR_ANYNET &&
117                     atif->address.s_node == at->src_node) {
118                         to->sat_addr.s_node = atif->address.s_node;
119                         goto found;
120                 }
121         }
122         s = NULL;
123 found:
124         read_unlock_bh(&atalk_sockets_lock);
125         return s;
126 }
127
128 /**
129  * atalk_find_or_insert_socket - Try to find a socket matching ADDR
130  * @sk - socket to insert in the list if it is not there already
131  * @sat - address to search for
132  *
133  * Try to find a socket matching ADDR in the socket list, if found then return
134  * it. If not, insert SK into the socket list.
135  *
136  * This entire operation must execute atomically.
137  */
138 static struct sock *atalk_find_or_insert_socket(struct sock *sk,
139                                                 struct sockaddr_at *sat)
140 {
141         struct sock *s;
142         struct hlist_node *node;
143         struct atalk_sock *at;
144
145         write_lock_bh(&atalk_sockets_lock);
146         sk_for_each(s, node, &atalk_sockets) {
147                 at = at_sk(s);
148
149                 if (at->src_net == sat->sat_addr.s_net &&
150                     at->src_node == sat->sat_addr.s_node &&
151                     at->src_port == sat->sat_port)
152                         goto found;
153         }
154         s = NULL;
155         __atalk_insert_socket(sk); /* Wheee, it's free, assign and insert. */
156 found:
157         write_unlock_bh(&atalk_sockets_lock);
158         return s;
159 }
160
161 static void atalk_destroy_timer(unsigned long data)
162 {
163         struct sock *sk = (struct sock *)data;
164
165         if (atomic_read(&sk->sk_wmem_alloc) ||
166             atomic_read(&sk->sk_rmem_alloc)) {
167                 sk->sk_timer.expires = jiffies + SOCK_DESTROY_TIME;
168                 add_timer(&sk->sk_timer);
169         } else
170                 sock_put(sk);
171 }
172
173 static inline void atalk_destroy_socket(struct sock *sk)
174 {
175         atalk_remove_socket(sk);
176         skb_queue_purge(&sk->sk_receive_queue);
177
178         if (atomic_read(&sk->sk_wmem_alloc) ||
179             atomic_read(&sk->sk_rmem_alloc)) {
180                 init_timer(&sk->sk_timer);
181                 sk->sk_timer.expires    = jiffies + SOCK_DESTROY_TIME;
182                 sk->sk_timer.function   = atalk_destroy_timer;
183                 sk->sk_timer.data       = (unsigned long)sk;
184                 add_timer(&sk->sk_timer);
185         } else
186                 sock_put(sk);
187 }
188
189 /**************************************************************************\
190 *                                                                          *
191 * Routing tables for the AppleTalk socket layer.                           *
192 *                                                                          *
193 \**************************************************************************/
194
195 /* Anti-deadlock ordering is atalk_routes_lock --> iface_lock -DaveM */
196 struct atalk_route *atalk_routes;
197 DEFINE_RWLOCK(atalk_routes_lock);
198
199 struct atalk_iface *atalk_interfaces;
200 DEFINE_RWLOCK(atalk_interfaces_lock);
201
202 /* For probing devices or in a routerless network */
203 struct atalk_route atrtr_default;
204
205 /* AppleTalk interface control */
206 /*
207  * Drop a device. Doesn't drop any of its routes - that is the caller's
208  * problem. Called when we down the interface or delete the address.
209  */
210 static void atif_drop_device(struct net_device *dev)
211 {
212         struct atalk_iface **iface = &atalk_interfaces;
213         struct atalk_iface *tmp;
214
215         write_lock_bh(&atalk_interfaces_lock);
216         while ((tmp = *iface) != NULL) {
217                 if (tmp->dev == dev) {
218                         *iface = tmp->next;
219                         dev_put(dev);
220                         kfree(tmp);
221                         dev->atalk_ptr = NULL;
222                 } else
223                         iface = &tmp->next;
224         }
225         write_unlock_bh(&atalk_interfaces_lock);
226 }
227
228 static struct atalk_iface *atif_add_device(struct net_device *dev,
229                                            struct atalk_addr *sa)
230 {
231         struct atalk_iface *iface = kmalloc(sizeof(*iface), GFP_KERNEL);
232
233         if (!iface)
234                 goto out;
235
236         memset(iface, 0, sizeof(*iface));
237         dev_hold(dev);
238         iface->dev = dev;
239         dev->atalk_ptr = iface;
240         iface->address = *sa;
241         iface->status = 0;
242
243         write_lock_bh(&atalk_interfaces_lock);
244         iface->next = atalk_interfaces;
245         atalk_interfaces = iface;
246         write_unlock_bh(&atalk_interfaces_lock);
247 out:
248         return iface;
249 }
250
251 /* Perform phase 2 AARP probing on our tentative address */
252 static int atif_probe_device(struct atalk_iface *atif)
253 {
254         int netrange = ntohs(atif->nets.nr_lastnet) -
255                         ntohs(atif->nets.nr_firstnet) + 1;
256         int probe_net = ntohs(atif->address.s_net);
257         int probe_node = atif->address.s_node;
258         int netct, nodect;
259
260         /* Offset the network we start probing with */
261         if (probe_net == ATADDR_ANYNET) {
262                 probe_net = ntohs(atif->nets.nr_firstnet);
263                 if (netrange)
264                         probe_net += jiffies % netrange;
265         }
266         if (probe_node == ATADDR_ANYNODE)
267                 probe_node = jiffies & 0xFF;
268
269         /* Scan the networks */
270         atif->status |= ATIF_PROBE;
271         for (netct = 0; netct <= netrange; netct++) {
272                 /* Sweep the available nodes from a given start */
273                 atif->address.s_net = htons(probe_net);
274                 for (nodect = 0; nodect < 256; nodect++) {
275                         atif->address.s_node = (nodect + probe_node) & 0xFF;
276                         if (atif->address.s_node > 0 &&
277                             atif->address.s_node < 254) {
278                                 /* Probe a proposed address */
279                                 aarp_probe_network(atif);
280
281                                 if (!(atif->status & ATIF_PROBE_FAIL)) {
282                                         atif->status &= ~ATIF_PROBE;
283                                         return 0;
284                                 }
285                         }
286                         atif->status &= ~ATIF_PROBE_FAIL;
287                 }
288                 probe_net++;
289                 if (probe_net > ntohs(atif->nets.nr_lastnet))
290                         probe_net = ntohs(atif->nets.nr_firstnet);
291         }
292         atif->status &= ~ATIF_PROBE;
293
294         return -EADDRINUSE;     /* Network is full... */
295 }
296
297
298 /* Perform AARP probing for a proxy address */
299 static int atif_proxy_probe_device(struct atalk_iface *atif,
300                                    struct atalk_addr* proxy_addr)
301 {
302         int netrange = ntohs(atif->nets.nr_lastnet) -
303                         ntohs(atif->nets.nr_firstnet) + 1;
304         /* we probe the interface's network */
305         int probe_net = ntohs(atif->address.s_net);
306         int probe_node = ATADDR_ANYNODE;            /* we'll take anything */
307         int netct, nodect;
308
309         /* Offset the network we start probing with */
310         if (probe_net == ATADDR_ANYNET) {
311                 probe_net = ntohs(atif->nets.nr_firstnet);
312                 if (netrange)
313                         probe_net += jiffies % netrange;
314         }
315
316         if (probe_node == ATADDR_ANYNODE)
317                 probe_node = jiffies & 0xFF;
318                 
319         /* Scan the networks */
320         for (netct = 0; netct <= netrange; netct++) {
321                 /* Sweep the available nodes from a given start */
322                 proxy_addr->s_net = htons(probe_net);
323                 for (nodect = 0; nodect < 256; nodect++) {
324                         proxy_addr->s_node = (nodect + probe_node) & 0xFF;
325                         if (proxy_addr->s_node > 0 &&
326                             proxy_addr->s_node < 254) {
327                                 /* Tell AARP to probe a proposed address */
328                                 int ret = aarp_proxy_probe_network(atif,
329                                                                     proxy_addr);
330
331                                 if (ret != -EADDRINUSE)
332                                         return ret;
333                         }
334                 }
335                 probe_net++;
336                 if (probe_net > ntohs(atif->nets.nr_lastnet))
337                         probe_net = ntohs(atif->nets.nr_firstnet);
338         }
339
340         return -EADDRINUSE;     /* Network is full... */
341 }
342
343
344 struct atalk_addr *atalk_find_dev_addr(struct net_device *dev)
345 {
346         struct atalk_iface *iface = dev->atalk_ptr;
347         return iface ? &iface->address : NULL;
348 }
349
350 static struct atalk_addr *atalk_find_primary(void)
351 {
352         struct atalk_iface *fiface = NULL;
353         struct atalk_addr *retval;
354         struct atalk_iface *iface;
355
356         /*
357          * Return a point-to-point interface only if
358          * there is no non-ptp interface available.
359          */
360         read_lock_bh(&atalk_interfaces_lock);
361         for (iface = atalk_interfaces; iface; iface = iface->next) {
362                 if (!fiface && !(iface->dev->flags & IFF_LOOPBACK))
363                         fiface = iface;
364                 if (!(iface->dev->flags & (IFF_LOOPBACK | IFF_POINTOPOINT))) {
365                         retval = &iface->address;
366                         goto out;
367                 }
368         }
369
370         if (fiface)
371                 retval = &fiface->address;
372         else if (atalk_interfaces)
373                 retval = &atalk_interfaces->address;
374         else
375                 retval = NULL;
376 out:
377         read_unlock_bh(&atalk_interfaces_lock);
378         return retval;
379 }
380
381 /*
382  * Find a match for 'any network' - ie any of our interfaces with that
383  * node number will do just nicely.
384  */
385 static struct atalk_iface *atalk_find_anynet(int node, struct net_device *dev)
386 {
387         struct atalk_iface *iface = dev->atalk_ptr;
388
389         if (!iface || iface->status & ATIF_PROBE)
390                 goto out_err;
391
392         if (node != ATADDR_BCAST &&
393             iface->address.s_node != node &&
394             node != ATADDR_ANYNODE)
395                 goto out_err;
396 out:
397         return iface;
398 out_err:
399         iface = NULL;
400         goto out;
401 }
402
403 /* Find a match for a specific network:node pair */
404 static struct atalk_iface *atalk_find_interface(int net, int node)
405 {
406         struct atalk_iface *iface;
407
408         read_lock_bh(&atalk_interfaces_lock);
409         for (iface = atalk_interfaces; iface; iface = iface->next) {
410                 if ((node == ATADDR_BCAST ||
411                      node == ATADDR_ANYNODE ||
412                      iface->address.s_node == node) &&
413                     iface->address.s_net == net &&
414                     !(iface->status & ATIF_PROBE))
415                         break;
416
417                 /* XXXX.0 -- net.0 returns the iface associated with net */
418                 if (node == ATADDR_ANYNODE && net != ATADDR_ANYNET &&
419                     ntohs(iface->nets.nr_firstnet) <= ntohs(net) &&
420                     ntohs(net) <= ntohs(iface->nets.nr_lastnet))
421                         break;
422         }
423         read_unlock_bh(&atalk_interfaces_lock);
424         return iface;
425 }
426
427
428 /*
429  * Find a route for an AppleTalk packet. This ought to get cached in
430  * the socket (later on...). We know about host routes and the fact
431  * that a route must be direct to broadcast.
432  */
433 static struct atalk_route *atrtr_find(struct atalk_addr *target)
434 {
435         /*
436          * we must search through all routes unless we find a 
437          * host route, because some host routes might overlap
438          * network routes
439          */
440         struct atalk_route *net_route = NULL;
441         struct atalk_route *r;
442         
443         read_lock_bh(&atalk_routes_lock);
444         for (r = atalk_routes; r; r = r->next) {
445                 if (!(r->flags & RTF_UP))
446                         continue;
447
448                 if (r->target.s_net == target->s_net) {
449                         if (r->flags & RTF_HOST) {
450                                 /*
451                                  * if this host route is for the target,
452                                  * the we're done
453                                  */
454                                 if (r->target.s_node == target->s_node)
455                                         goto out;
456                         } else
457                                 /*
458                                  * this route will work if there isn't a
459                                  * direct host route, so cache it
460                                  */
461                                 net_route = r;
462                 }
463         }
464         
465         /* 
466          * if we found a network route but not a direct host
467          * route, then return it
468          */
469         if (net_route)
470                 r = net_route;
471         else if (atrtr_default.dev)
472                 r = &atrtr_default;
473         else /* No route can be found */
474                 r = NULL;
475 out:
476         read_unlock_bh(&atalk_routes_lock);
477         return r;
478 }
479
480
481 /*
482  * Given an AppleTalk network, find the device to use. This can be
483  * a simple lookup.
484  */
485 struct net_device *atrtr_get_dev(struct atalk_addr *sa)
486 {
487         struct atalk_route *atr = atrtr_find(sa);
488         return atr ? atr->dev : NULL;
489 }
490
491 /* Set up a default router */
492 static void atrtr_set_default(struct net_device *dev)
493 {
494         atrtr_default.dev            = dev;
495         atrtr_default.flags          = RTF_UP;
496         atrtr_default.gateway.s_net  = htons(0);
497         atrtr_default.gateway.s_node = 0;
498 }
499
500 /*
501  * Add a router. Basically make sure it looks valid and stuff the
502  * entry in the list. While it uses netranges we always set them to one
503  * entry to work like netatalk.
504  */
505 static int atrtr_create(struct rtentry *r, struct net_device *devhint)
506 {
507         struct sockaddr_at *ta = (struct sockaddr_at *)&r->rt_dst;
508         struct sockaddr_at *ga = (struct sockaddr_at *)&r->rt_gateway;
509         struct atalk_route *rt;
510         struct atalk_iface *iface, *riface;
511         int retval = -EINVAL;
512
513         /*
514          * Fixme: Raise/Lower a routing change semaphore for these
515          * operations.
516          */
517
518         /* Validate the request */
519         if (ta->sat_family != AF_APPLETALK ||
520             (!devhint && ga->sat_family != AF_APPLETALK))
521                 goto out;
522
523         /* Now walk the routing table and make our decisions */
524         write_lock_bh(&atalk_routes_lock);
525         for (rt = atalk_routes; rt; rt = rt->next) {
526                 if (r->rt_flags != rt->flags)
527                         continue;
528
529                 if (ta->sat_addr.s_net == rt->target.s_net) {
530                         if (!(rt->flags & RTF_HOST))
531                                 break;
532                         if (ta->sat_addr.s_node == rt->target.s_node)
533                                 break;
534                 }
535         }
536
537         if (!devhint) {
538                 riface = NULL;
539
540                 read_lock_bh(&atalk_interfaces_lock);
541                 for (iface = atalk_interfaces; iface; iface = iface->next) {
542                         if (!riface &&
543                             ntohs(ga->sat_addr.s_net) >=
544                                         ntohs(iface->nets.nr_firstnet) &&
545                             ntohs(ga->sat_addr.s_net) <=
546                                         ntohs(iface->nets.nr_lastnet))
547                                 riface = iface;
548
549                         if (ga->sat_addr.s_net == iface->address.s_net &&
550                             ga->sat_addr.s_node == iface->address.s_node)
551                                 riface = iface;
552                 }               
553                 read_unlock_bh(&atalk_interfaces_lock);
554
555                 retval = -ENETUNREACH;
556                 if (!riface)
557                         goto out_unlock;
558
559                 devhint = riface->dev;
560         }
561
562         if (!rt) {
563                 rt = kmalloc(sizeof(*rt), GFP_ATOMIC);
564
565                 retval = -ENOBUFS;
566                 if (!rt)
567                         goto out_unlock;
568                 memset(rt, 0, sizeof(*rt));
569
570                 rt->next = atalk_routes;
571                 atalk_routes = rt;
572         }
573
574         /* Fill in the routing entry */
575         rt->target  = ta->sat_addr;
576         rt->dev     = devhint;
577         rt->flags   = r->rt_flags;
578         rt->gateway = ga->sat_addr;
579
580         retval = 0;
581 out_unlock:
582         write_unlock_bh(&atalk_routes_lock);
583 out:
584         return retval;
585 }
586
587 /* Delete a route. Find it and discard it */
588 static int atrtr_delete(struct atalk_addr * addr)
589 {
590         struct atalk_route **r = &atalk_routes;
591         int retval = 0;
592         struct atalk_route *tmp;
593
594         write_lock_bh(&atalk_routes_lock);
595         while ((tmp = *r) != NULL) {
596                 if (tmp->target.s_net == addr->s_net &&
597                     (!(tmp->flags&RTF_GATEWAY) ||
598                      tmp->target.s_node == addr->s_node)) {
599                         *r = tmp->next;
600                         dev_put(tmp->dev);
601                         kfree(tmp);
602                         goto out;
603                 }
604                 r = &tmp->next;
605         }
606         retval = -ENOENT;
607 out:
608         write_unlock_bh(&atalk_routes_lock);
609         return retval;
610 }
611
612 /*
613  * Called when a device is downed. Just throw away any routes
614  * via it.
615  */
616 static void atrtr_device_down(struct net_device *dev)
617 {
618         struct atalk_route **r = &atalk_routes;
619         struct atalk_route *tmp;
620
621         write_lock_bh(&atalk_routes_lock);
622         while ((tmp = *r) != NULL) {
623                 if (tmp->dev == dev) {
624                         *r = tmp->next;
625                         dev_put(dev);
626                         kfree(tmp);
627                 } else
628                         r = &tmp->next;
629         }
630         write_unlock_bh(&atalk_routes_lock);
631
632         if (atrtr_default.dev == dev)
633                 atrtr_set_default(NULL);
634 }
635
636 /* Actually down the interface */
637 static inline void atalk_dev_down(struct net_device *dev)
638 {
639         atrtr_device_down(dev); /* Remove all routes for the device */
640         aarp_device_down(dev);  /* Remove AARP entries for the device */
641         atif_drop_device(dev);  /* Remove the device */
642 }
643
644 /*
645  * A device event has occurred. Watch for devices going down and
646  * delete our use of them (iface and route).
647  */
648 static int ddp_device_event(struct notifier_block *this, unsigned long event,
649                             void *ptr)
650 {
651         if (event == NETDEV_DOWN)
652                 /* Discard any use of this */
653                 atalk_dev_down(ptr);
654
655         return NOTIFY_DONE;
656 }
657
658 /* ioctl calls. Shouldn't even need touching */
659 /* Device configuration ioctl calls */
660 static int atif_ioctl(int cmd, void __user *arg)
661 {
662         static char aarp_mcast[6] = { 0x09, 0x00, 0x00, 0xFF, 0xFF, 0xFF };
663         struct ifreq atreq;
664         struct atalk_netrange *nr;
665         struct sockaddr_at *sa;
666         struct net_device *dev;
667         struct atalk_iface *atif;
668         int ct;
669         int limit;
670         struct rtentry rtdef;
671         int add_route;
672
673         if (copy_from_user(&atreq, arg, sizeof(atreq)))
674                 return -EFAULT;
675
676         dev = __dev_get_by_name(atreq.ifr_name);
677         if (!dev)
678                 return -ENODEV;
679
680         sa = (struct sockaddr_at *)&atreq.ifr_addr;
681         atif = atalk_find_dev(dev);
682
683         switch (cmd) {
684                 case SIOCSIFADDR:
685                         if (!capable(CAP_NET_ADMIN))
686                                 return -EPERM;
687                         if (sa->sat_family != AF_APPLETALK)
688                                 return -EINVAL;
689                         if (dev->type != ARPHRD_ETHER &&
690                             dev->type != ARPHRD_LOOPBACK &&
691                             dev->type != ARPHRD_LOCALTLK &&
692                             dev->type != ARPHRD_PPP)
693                                 return -EPROTONOSUPPORT;
694
695                         nr = (struct atalk_netrange *)&sa->sat_zero[0];
696                         add_route = 1;
697
698                         /*
699                          * if this is a point-to-point iface, and we already
700                          * have an iface for this AppleTalk address, then we
701                          * should not add a route
702                          */
703                         if ((dev->flags & IFF_POINTOPOINT) &&
704                             atalk_find_interface(sa->sat_addr.s_net,
705                                                  sa->sat_addr.s_node)) {
706                                 printk(KERN_DEBUG "AppleTalk: point-to-point "
707                                                   "interface added with "
708                                                   "existing address\n");
709                                 add_route = 0;
710                         }
711                         
712                         /*
713                          * Phase 1 is fine on LocalTalk but we don't do
714                          * EtherTalk phase 1. Anyone wanting to add it go ahead.
715                          */
716                         if (dev->type == ARPHRD_ETHER && nr->nr_phase != 2)
717                                 return -EPROTONOSUPPORT;
718                         if (sa->sat_addr.s_node == ATADDR_BCAST ||
719                             sa->sat_addr.s_node == 254)
720                                 return -EINVAL;
721                         if (atif) {
722                                 /* Already setting address */
723                                 if (atif->status & ATIF_PROBE)
724                                         return -EBUSY;
725
726                                 atif->address.s_net  = sa->sat_addr.s_net;
727                                 atif->address.s_node = sa->sat_addr.s_node;
728                                 atrtr_device_down(dev); /* Flush old routes */
729                         } else {
730                                 atif = atif_add_device(dev, &sa->sat_addr);
731                                 if (!atif)
732                                         return -ENOMEM;
733                         }
734                         atif->nets = *nr;
735
736                         /*
737                          * Check if the chosen address is used. If so we
738                          * error and atalkd will try another.
739                          */
740
741                         if (!(dev->flags & IFF_LOOPBACK) &&
742                             !(dev->flags & IFF_POINTOPOINT) &&
743                             atif_probe_device(atif) < 0) {
744                                 atif_drop_device(dev);
745                                 return -EADDRINUSE;
746                         }
747
748                         /* Hey it worked - add the direct routes */
749                         sa = (struct sockaddr_at *)&rtdef.rt_gateway;
750                         sa->sat_family = AF_APPLETALK;
751                         sa->sat_addr.s_net  = atif->address.s_net;
752                         sa->sat_addr.s_node = atif->address.s_node;
753                         sa = (struct sockaddr_at *)&rtdef.rt_dst;
754                         rtdef.rt_flags = RTF_UP;
755                         sa->sat_family = AF_APPLETALK;
756                         sa->sat_addr.s_node = ATADDR_ANYNODE;
757                         if (dev->flags & IFF_LOOPBACK ||
758                             dev->flags & IFF_POINTOPOINT)
759                                 rtdef.rt_flags |= RTF_HOST;
760
761                         /* Routerless initial state */
762                         if (nr->nr_firstnet == htons(0) &&
763                             nr->nr_lastnet == htons(0xFFFE)) {
764                                 sa->sat_addr.s_net = atif->address.s_net;
765                                 atrtr_create(&rtdef, dev);
766                                 atrtr_set_default(dev);
767                         } else {
768                                 limit = ntohs(nr->nr_lastnet);
769                                 if (limit - ntohs(nr->nr_firstnet) > 4096) {
770                                         printk(KERN_WARNING "Too many routes/"
771                                                             "iface.\n");
772                                         return -EINVAL;
773                                 }
774                                 if (add_route)
775                                         for (ct = ntohs(nr->nr_firstnet);
776                                              ct <= limit; ct++) {
777                                                 sa->sat_addr.s_net = htons(ct);
778                                                 atrtr_create(&rtdef, dev);
779                                         }
780                         }
781                         dev_mc_add(dev, aarp_mcast, 6, 1);
782                         return 0;
783
784                 case SIOCGIFADDR:
785                         if (!atif)
786                                 return -EADDRNOTAVAIL;
787
788                         sa->sat_family = AF_APPLETALK;
789                         sa->sat_addr = atif->address;
790                         break;
791
792                 case SIOCGIFBRDADDR:
793                         if (!atif)
794                                 return -EADDRNOTAVAIL;
795
796                         sa->sat_family = AF_APPLETALK;
797                         sa->sat_addr.s_net = atif->address.s_net;
798                         sa->sat_addr.s_node = ATADDR_BCAST;
799                         break;
800
801                 case SIOCATALKDIFADDR:
802                 case SIOCDIFADDR:
803                         if (!capable(CAP_NET_ADMIN))
804                                 return -EPERM;
805                         if (sa->sat_family != AF_APPLETALK)
806                                 return -EINVAL;
807                         atalk_dev_down(dev);
808                         break;                  
809
810                 case SIOCSARP:
811                         if (!capable(CAP_NET_ADMIN))
812                                 return -EPERM;
813                         if (sa->sat_family != AF_APPLETALK)
814                                 return -EINVAL;
815                         if (!atif)
816                                 return -EADDRNOTAVAIL;
817
818                         /*
819                          * for now, we only support proxy AARP on ELAP;
820                          * we should be able to do it for LocalTalk, too.
821                          */
822                         if (dev->type != ARPHRD_ETHER)
823                                 return -EPROTONOSUPPORT;
824
825                         /*
826                          * atif points to the current interface on this network;
827                          * we aren't concerned about its current status (at
828                          * least for now), but it has all the settings about
829                          * the network we're going to probe. Consequently, it
830                          * must exist.
831                          */
832                         if (!atif)
833                                 return -EADDRNOTAVAIL;
834
835                         nr = (struct atalk_netrange *)&(atif->nets);
836                         /*
837                          * Phase 1 is fine on Localtalk but we don't do
838                          * Ethertalk phase 1. Anyone wanting to add it go ahead.
839                          */
840                         if (dev->type == ARPHRD_ETHER && nr->nr_phase != 2)
841                                 return -EPROTONOSUPPORT;
842
843                         if (sa->sat_addr.s_node == ATADDR_BCAST ||
844                             sa->sat_addr.s_node == 254)
845                                 return -EINVAL;
846
847                         /*
848                          * Check if the chosen address is used. If so we
849                          * error and ATCP will try another.
850                          */
851                         if (atif_proxy_probe_device(atif, &(sa->sat_addr)) < 0)
852                                 return -EADDRINUSE;
853                         
854                         /*
855                          * We now have an address on the local network, and
856                          * the AARP code will defend it for us until we take it
857                          * down. We don't set up any routes right now, because
858                          * ATCP will install them manually via SIOCADDRT.
859                          */
860                         break;
861
862                 case SIOCDARP:
863                         if (!capable(CAP_NET_ADMIN))
864                                 return -EPERM;
865                         if (sa->sat_family != AF_APPLETALK)
866                                 return -EINVAL;
867                         if (!atif)
868                                 return -EADDRNOTAVAIL;
869
870                         /* give to aarp module to remove proxy entry */
871                         aarp_proxy_remove(atif->dev, &(sa->sat_addr));
872                         return 0;
873         }
874
875         return copy_to_user(arg, &atreq, sizeof(atreq)) ? -EFAULT : 0;
876 }
877
878 /* Routing ioctl() calls */
879 static int atrtr_ioctl(unsigned int cmd, void __user *arg)
880 {
881         struct rtentry rt;
882
883         if (copy_from_user(&rt, arg, sizeof(rt)))
884                 return -EFAULT;
885
886         switch (cmd) {
887                 case SIOCDELRT:
888                         if (rt.rt_dst.sa_family != AF_APPLETALK)
889                                 return -EINVAL;
890                         return atrtr_delete(&((struct sockaddr_at *)
891                                                 &rt.rt_dst)->sat_addr);
892
893                 case SIOCADDRT: {
894                         struct net_device *dev = NULL;
895                         if (rt.rt_dev) {
896                                 char name[IFNAMSIZ];
897                                 if (copy_from_user(name, rt.rt_dev, IFNAMSIZ-1))
898                                         return -EFAULT;
899                                 name[IFNAMSIZ-1] = '\0';
900                                 dev = __dev_get_by_name(name);
901                                 if (!dev)
902                                         return -ENODEV;
903                         }                       
904                         return atrtr_create(&rt, dev);
905                 }
906         }
907         return -EINVAL;
908 }
909
910 /**************************************************************************\
911 *                                                                          *
912 * Handling for system calls applied via the various interfaces to an       *
913 * AppleTalk socket object.                                                 *
914 *                                                                          *
915 \**************************************************************************/
916
917 /*
918  * Checksum: This is 'optional'. It's quite likely also a good
919  * candidate for assembler hackery 8)
920  */
921 static unsigned long atalk_sum_partial(const unsigned char *data, 
922                                        int len, unsigned long sum)
923 {
924         /* This ought to be unwrapped neatly. I'll trust gcc for now */
925         while (len--) {
926                 sum += *data;
927                 sum <<= 1;
928                 if (sum & 0x10000) {
929                         sum++;
930                         sum &= 0xffff;
931                 }
932                 data++;
933         }
934         return sum;
935 }
936
937 /*  Checksum skb data --  similar to skb_checksum  */
938 static unsigned long atalk_sum_skb(const struct sk_buff *skb, int offset,
939                                    int len, unsigned long sum)
940 {
941         int start = skb_headlen(skb);
942         int i, copy;
943
944         /* checksum stuff in header space */
945         if ( (copy = start - offset) > 0) {
946                 if (copy > len)
947                         copy = len;
948                 sum = atalk_sum_partial(skb->data + offset, copy, sum);
949                 if ( (len -= copy) == 0) 
950                         return sum;
951
952                 offset += copy;
953         }
954
955         /* checksum stuff in frags */
956         for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
957                 int end;
958
959                 BUG_TRAP(start <= offset + len);
960
961                 end = start + skb_shinfo(skb)->frags[i].size;
962                 if ((copy = end - offset) > 0) {
963                         u8 *vaddr;
964                         skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
965
966                         if (copy > len)
967                                 copy = len;
968                         vaddr = kmap_skb_frag(frag);
969                         sum = atalk_sum_partial(vaddr + frag->page_offset +
970                                                   offset - start, copy, sum);
971                         kunmap_skb_frag(vaddr);
972
973                         if (!(len -= copy))
974                                 return sum;
975                         offset += copy;
976                 }
977                 start = end;
978         }
979
980         if (skb_shinfo(skb)->frag_list) {
981                 struct sk_buff *list = skb_shinfo(skb)->frag_list;
982
983                 for (; list; list = list->next) {
984                         int end;
985
986                         BUG_TRAP(start <= offset + len);
987
988                         end = start + list->len;
989                         if ((copy = end - offset) > 0) {
990                                 if (copy > len)
991                                         copy = len;
992                                 sum = atalk_sum_skb(list, offset - start,
993                                                     copy, sum);
994                                 if ((len -= copy) == 0)
995                                         return sum;
996                                 offset += copy;
997                         }
998                         start = end;
999                 }
1000         }
1001
1002         BUG_ON(len > 0);
1003
1004         return sum;
1005 }
1006
1007 static unsigned short atalk_checksum(const struct sk_buff *skb, int len)
1008 {
1009         unsigned long sum;
1010
1011         /* skip header 4 bytes */
1012         sum = atalk_sum_skb(skb, 4, len-4, 0);
1013
1014         /* Use 0xFFFF for 0. 0 itself means none */
1015         return sum ? htons((unsigned short)sum) : 0xFFFF;
1016 }
1017
1018 /*
1019  * Create a socket. Initialise the socket, blank the addresses
1020  * set the state.
1021  */
1022 static int atalk_create(struct socket *sock, int protocol)
1023 {
1024         struct sock *sk;
1025         struct atalk_sock *at;
1026         int rc = -ESOCKTNOSUPPORT;
1027
1028         /*
1029          * We permit SOCK_DGRAM and RAW is an extension. It is trivial to do
1030          * and gives you the full ELAP frame. Should be handy for CAP 8) 
1031          */
1032         if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
1033                 goto out;
1034         rc = -ENOMEM;
1035         sk = sk_alloc(PF_APPLETALK, GFP_KERNEL, 1, NULL);
1036         if (!sk)
1037                 goto out;
1038         at = sk->sk_protinfo = kmalloc(sizeof(*at), GFP_KERNEL);
1039         if (!at)
1040                 goto outsk;
1041         memset(at, 0, sizeof(*at));
1042         rc = 0;
1043         sock->ops = &atalk_dgram_ops;
1044         sock_init_data(sock, sk);
1045         sk_set_owner(sk, THIS_MODULE);
1046
1047         /* Checksums on by default */
1048         sk->sk_zapped = 1;
1049 out:
1050         return rc;
1051 outsk:
1052         sk_free(sk);
1053         goto out;
1054 }
1055
1056 /* Free a socket. No work needed */
1057 static int atalk_release(struct socket *sock)
1058 {
1059         struct sock *sk = sock->sk;
1060
1061         if (sk) {
1062                 sock_orphan(sk);
1063                 sock->sk = NULL;
1064                 atalk_destroy_socket(sk);
1065         }
1066         return 0;
1067 }
1068
1069 /**
1070  * atalk_pick_and_bind_port - Pick a source port when one is not given
1071  * @sk - socket to insert into the tables
1072  * @sat - address to search for
1073  *
1074  * Pick a source port when one is not given. If we can find a suitable free
1075  * one, we insert the socket into the tables using it.
1076  *
1077  * This whole operation must be atomic.
1078  */
1079 static int atalk_pick_and_bind_port(struct sock *sk, struct sockaddr_at *sat)
1080 {
1081         int retval;
1082
1083         write_lock_bh(&atalk_sockets_lock);
1084
1085         for (sat->sat_port = ATPORT_RESERVED;
1086              sat->sat_port < ATPORT_LAST;
1087              sat->sat_port++) {
1088                 struct sock *s;
1089                 struct hlist_node *node;
1090
1091                 sk_for_each(s, node, &atalk_sockets) {
1092                         struct atalk_sock *at = at_sk(s);
1093
1094                         if (at->src_net == sat->sat_addr.s_net &&
1095                             at->src_node == sat->sat_addr.s_node &&
1096                             at->src_port == sat->sat_port)
1097                                 goto try_next_port;
1098                 }
1099
1100                 /* Wheee, it's free, assign and insert. */
1101                 __atalk_insert_socket(sk);
1102                 at_sk(sk)->src_port = sat->sat_port;
1103                 retval = 0;
1104                 goto out;
1105
1106 try_next_port:;
1107         }
1108
1109         retval = -EBUSY;
1110 out:
1111         write_unlock_bh(&atalk_sockets_lock);
1112         return retval;
1113 }
1114
1115 static int atalk_autobind(struct sock *sk)
1116 {
1117         struct atalk_sock *at = at_sk(sk);
1118         struct sockaddr_at sat;
1119         struct atalk_addr *ap = atalk_find_primary();
1120         int n = -EADDRNOTAVAIL;
1121
1122         if (!ap || ap->s_net == htons(ATADDR_ANYNET))
1123                 goto out;
1124
1125         at->src_net  = sat.sat_addr.s_net  = ap->s_net;
1126         at->src_node = sat.sat_addr.s_node = ap->s_node;
1127
1128         n = atalk_pick_and_bind_port(sk, &sat);
1129         if (!n)
1130                 sk->sk_zapped = 0;
1131 out:
1132         return n;
1133 }
1134
1135 /* Set the address 'our end' of the connection */
1136 static int atalk_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
1137 {
1138         struct sockaddr_at *addr = (struct sockaddr_at *)uaddr;
1139         struct sock *sk = sock->sk;
1140         struct atalk_sock *at = at_sk(sk);
1141
1142         if (!sk->sk_zapped || addr_len != sizeof(struct sockaddr_at))
1143                 return -EINVAL;
1144
1145         if (addr->sat_family != AF_APPLETALK)
1146                 return -EAFNOSUPPORT;
1147
1148         if (addr->sat_addr.s_net == htons(ATADDR_ANYNET)) {
1149                 struct atalk_addr *ap = atalk_find_primary();
1150
1151                 if (!ap)
1152                         return -EADDRNOTAVAIL;
1153
1154                 at->src_net  = addr->sat_addr.s_net = ap->s_net;
1155                 at->src_node = addr->sat_addr.s_node= ap->s_node;
1156         } else {
1157                 if (!atalk_find_interface(addr->sat_addr.s_net,
1158                                           addr->sat_addr.s_node))
1159                         return -EADDRNOTAVAIL;
1160
1161                 at->src_net  = addr->sat_addr.s_net;
1162                 at->src_node = addr->sat_addr.s_node;
1163         }
1164
1165         if (addr->sat_port == ATADDR_ANYPORT) {
1166                 int n = atalk_pick_and_bind_port(sk, addr);
1167
1168                 if (n < 0)
1169                         return n;
1170         } else {
1171                 at->src_port = addr->sat_port;
1172
1173                 if (atalk_find_or_insert_socket(sk, addr))
1174                         return -EADDRINUSE;
1175         }
1176
1177         sk->sk_zapped = 0;
1178         return 0;
1179 }
1180
1181 /* Set the address we talk to */
1182 static int atalk_connect(struct socket *sock, struct sockaddr *uaddr,
1183                          int addr_len, int flags)
1184 {
1185         struct sock *sk = sock->sk;
1186         struct atalk_sock *at = at_sk(sk);
1187         struct sockaddr_at *addr;
1188
1189         sk->sk_state   = TCP_CLOSE;
1190         sock->state = SS_UNCONNECTED;
1191
1192         if (addr_len != sizeof(*addr))
1193                 return -EINVAL;
1194
1195         addr = (struct sockaddr_at *)uaddr;
1196
1197         if (addr->sat_family != AF_APPLETALK)
1198                 return -EAFNOSUPPORT;
1199
1200         if (addr->sat_addr.s_node == ATADDR_BCAST &&
1201             !sock_flag(sk, SOCK_BROADCAST)) {
1202 #if 1   
1203                 printk(KERN_WARNING "%s is broken and did not set "
1204                                     "SO_BROADCAST. It will break when 2.2 is "
1205                                     "released.\n",
1206                         current->comm);
1207 #else
1208                 return -EACCES;
1209 #endif                  
1210         }
1211
1212         if (sk->sk_zapped)
1213                 if (atalk_autobind(sk) < 0)
1214                         return -EBUSY;
1215
1216         if (!atrtr_get_dev(&addr->sat_addr))
1217                 return -ENETUNREACH;
1218
1219         at->dest_port = addr->sat_port;
1220         at->dest_net  = addr->sat_addr.s_net;
1221         at->dest_node = addr->sat_addr.s_node;
1222
1223         sock->state  = SS_CONNECTED;
1224         sk->sk_state = TCP_ESTABLISHED;
1225         return 0;
1226 }
1227
1228 /*
1229  * Find the name of an AppleTalk socket. Just copy the right
1230  * fields into the sockaddr.
1231  */
1232 static int atalk_getname(struct socket *sock, struct sockaddr *uaddr,
1233                          int *uaddr_len, int peer)
1234 {
1235         struct sockaddr_at sat;
1236         struct sock *sk = sock->sk;
1237         struct atalk_sock *at = at_sk(sk);
1238
1239         if (sk->sk_zapped)
1240                 if (atalk_autobind(sk) < 0)
1241                         return -ENOBUFS;
1242
1243         *uaddr_len = sizeof(struct sockaddr_at);
1244
1245         if (peer) {
1246                 if (sk->sk_state != TCP_ESTABLISHED)
1247                         return -ENOTCONN;
1248
1249                 sat.sat_addr.s_net  = at->dest_net;
1250                 sat.sat_addr.s_node = at->dest_node;
1251                 sat.sat_port        = at->dest_port;
1252         } else {
1253                 sat.sat_addr.s_net  = at->src_net;
1254                 sat.sat_addr.s_node = at->src_node;
1255                 sat.sat_port        = at->src_port;
1256         }
1257
1258         sat.sat_family = AF_APPLETALK;
1259         memcpy(uaddr, &sat, sizeof(sat));
1260         return 0;
1261 }
1262
1263 #if defined(CONFIG_IPDDP) || defined(CONFIG_IPDDP_MODULE)
1264 static __inline__ int is_ip_over_ddp(struct sk_buff *skb)
1265 {
1266         return skb->data[12] == 22;
1267 }
1268
1269 static int handle_ip_over_ddp(struct sk_buff *skb)
1270 {
1271         struct net_device *dev = __dev_get_by_name("ipddp0");
1272         struct net_device_stats *stats;
1273
1274         /* This needs to be able to handle ipddp"N" devices */
1275         if (!dev)
1276                 return -ENODEV;
1277
1278         skb->protocol = htons(ETH_P_IP);
1279         skb_pull(skb, 13);
1280         skb->dev   = dev;
1281         skb->h.raw = skb->data;
1282
1283         stats = dev->priv;
1284         stats->rx_packets++;
1285         stats->rx_bytes += skb->len + 13;
1286         netif_rx(skb);  /* Send the SKB up to a higher place. */
1287         return 0;
1288 }
1289 #else
1290 /* make it easy for gcc to optimize this test out, i.e. kill the code */
1291 #define is_ip_over_ddp(skb) 0
1292 #define handle_ip_over_ddp(skb) 0
1293 #endif
1294
1295 static void atalk_route_packet(struct sk_buff *skb, struct net_device *dev,
1296                                struct ddpehdr *ddp, struct ddpebits *ddphv,
1297                                int origlen)
1298 {
1299         struct atalk_route *rt;
1300         struct atalk_addr ta;
1301
1302         /*
1303          * Don't route multicast, etc., packets, or packets sent to "this
1304          * network" 
1305          */
1306         if (skb->pkt_type != PACKET_HOST || !ddp->deh_dnet) {
1307                 /*
1308                  * FIXME:
1309                  *
1310                  * Can it ever happen that a packet is from a PPP iface and
1311                  * needs to be broadcast onto the default network?
1312                  */
1313                 if (dev->type == ARPHRD_PPP)
1314                         printk(KERN_DEBUG "AppleTalk: didn't forward broadcast "
1315                                           "packet received from PPP iface\n");
1316                 goto free_it;
1317         }
1318
1319         ta.s_net  = ddp->deh_dnet;
1320         ta.s_node = ddp->deh_dnode;
1321
1322         /* Route the packet */
1323         rt = atrtr_find(&ta);
1324         if (!rt || ddphv->deh_hops == DDP_MAXHOPS)
1325                 goto free_it;
1326         /* FIXME: use skb->cb to be able to use shared skbs */
1327         ddphv->deh_hops++;
1328
1329         /*
1330          * Route goes through another gateway, so set the target to the
1331          * gateway instead.
1332          */
1333
1334         if (rt->flags & RTF_GATEWAY) {
1335                 ta.s_net  = rt->gateway.s_net;
1336                 ta.s_node = rt->gateway.s_node;
1337         }
1338
1339         /* Fix up skb->len field */
1340         skb_trim(skb, min_t(unsigned int, origlen,
1341                             (rt->dev->hard_header_len +
1342                              ddp_dl->header_length + ddphv->deh_len)));
1343
1344         /* Mend the byte order */
1345         /* FIXME: use skb->cb to be able to use shared skbs */
1346         *((__u16 *)ddp) = ntohs(*((__u16 *)ddphv));
1347
1348         /*
1349          * Send the buffer onwards
1350          *
1351          * Now we must always be careful. If it's come from LocalTalk to
1352          * EtherTalk it might not fit
1353          *
1354          * Order matters here: If a packet has to be copied to make a new
1355          * headroom (rare hopefully) then it won't need unsharing.
1356          *
1357          * Note. ddp-> becomes invalid at the realloc.
1358          */
1359         if (skb_headroom(skb) < 22) {
1360                 /* 22 bytes - 12 ether, 2 len, 3 802.2 5 snap */
1361                 struct sk_buff *nskb = skb_realloc_headroom(skb, 32);
1362                 kfree_skb(skb);
1363                 if (!nskb) 
1364                         goto out;
1365                 skb = nskb;
1366         } else
1367                 skb = skb_unshare(skb, GFP_ATOMIC);
1368         
1369         /*
1370          * If the buffer didn't vanish into the lack of space bitbucket we can
1371          * send it.
1372          */
1373         if (skb && aarp_send_ddp(rt->dev, skb, &ta, NULL) == -1)
1374                 goto free_it;
1375 out:
1376         return;
1377 free_it:
1378         kfree_skb(skb);
1379 }
1380
1381 /**
1382  *      atalk_rcv - Receive a packet (in skb) from device dev
1383  *      @skb - packet received
1384  *      @dev - network device where the packet comes from
1385  *      @pt - packet type
1386  *
1387  *      Receive a packet (in skb) from device dev. This has come from the SNAP
1388  *      decoder, and on entry skb->h.raw is the DDP header, skb->len is the DDP
1389  *      header, skb->len is the DDP length. The physical headers have been
1390  *      extracted. PPP should probably pass frames marked as for this layer.
1391  *      [ie ARPHRD_ETHERTALK]
1392  */
1393 static int atalk_rcv(struct sk_buff *skb, struct net_device *dev,
1394                      struct packet_type *pt)
1395 {
1396         struct ddpehdr *ddp;
1397         struct sock *sock;
1398         struct atalk_iface *atif;
1399         struct sockaddr_at tosat;
1400         int origlen;
1401         struct ddpebits ddphv;
1402
1403         /* Don't mangle buffer if shared */
1404         if (!(skb = skb_share_check(skb, GFP_ATOMIC))) 
1405                 goto out;
1406                 
1407         /* Size check and make sure header is contiguous */
1408         if (!pskb_may_pull(skb, sizeof(*ddp)))
1409                 goto freeit;
1410
1411         ddp = ddp_hdr(skb);
1412
1413         /*
1414          *      Fix up the length field [Ok this is horrible but otherwise
1415          *      I end up with unions of bit fields and messy bit field order
1416          *      compiler/endian dependencies..]
1417          */
1418         *((__u16 *)&ddphv) = ntohs(*((__u16 *)ddp));
1419
1420         /* Trim buffer in case of stray trailing data */
1421         origlen = skb->len;
1422         skb_trim(skb, min_t(unsigned int, skb->len, ddphv.deh_len));
1423
1424         /*
1425          * Size check to see if ddp->deh_len was crap
1426          * (Otherwise we'll detonate most spectacularly
1427          * in the middle of recvmsg()).
1428          */
1429         if (skb->len < sizeof(*ddp))
1430                 goto freeit;
1431
1432         /*
1433          * Any checksums. Note we don't do htons() on this == is assumed to be
1434          * valid for net byte orders all over the networking code...
1435          */
1436         if (ddp->deh_sum &&
1437             atalk_checksum(skb, ddphv.deh_len) != ddp->deh_sum)
1438                 /* Not a valid AppleTalk frame - dustbin time */
1439                 goto freeit;
1440
1441         /* Check the packet is aimed at us */
1442         if (!ddp->deh_dnet)     /* Net 0 is 'this network' */
1443                 atif = atalk_find_anynet(ddp->deh_dnode, dev);
1444         else
1445                 atif = atalk_find_interface(ddp->deh_dnet, ddp->deh_dnode);
1446
1447         /* Not ours, so we route the packet via the correct AppleTalk iface */
1448         if (!atif) {
1449                 atalk_route_packet(skb, dev, ddp, &ddphv, origlen);
1450                 goto out;
1451         }
1452
1453         /* if IP over DDP is not selected this code will be optimized out */
1454         if (is_ip_over_ddp(skb))
1455                 return handle_ip_over_ddp(skb);
1456         /*
1457          * Which socket - atalk_search_socket() looks for a *full match*
1458          * of the <net, node, port> tuple.
1459          */
1460         tosat.sat_addr.s_net  = ddp->deh_dnet;
1461         tosat.sat_addr.s_node = ddp->deh_dnode;
1462         tosat.sat_port        = ddp->deh_dport;
1463
1464         sock = atalk_search_socket(&tosat, atif);
1465         if (!sock) /* But not one of our sockets */
1466                 goto freeit;
1467
1468         /* Queue packet (standard) */
1469         skb->sk = sock;
1470
1471         if (sock_queue_rcv_skb(sock, skb) < 0)
1472                 goto freeit;
1473 out:
1474         return 0;
1475 freeit:
1476         kfree_skb(skb);
1477         goto out;
1478 }
1479
1480 /*
1481  * Receive a LocalTalk frame. We make some demands on the caller here.
1482  * Caller must provide enough headroom on the packet to pull the short
1483  * header and append a long one.
1484  */
1485 static int ltalk_rcv(struct sk_buff *skb, struct net_device *dev,
1486                         struct packet_type *pt)
1487 {
1488         /* Expand any short form frames */
1489         if (skb->mac.raw[2] == 1) {
1490                 struct ddpehdr *ddp;
1491                 /* Find our address */
1492                 struct atalk_addr *ap = atalk_find_dev_addr(dev);
1493
1494                 if (!ap || skb->len < sizeof(struct ddpshdr))
1495                         goto freeit;
1496
1497                 /* Don't mangle buffer if shared */
1498                 if (!(skb = skb_share_check(skb, GFP_ATOMIC))) 
1499                         return 0;
1500
1501                 /*
1502                  * The push leaves us with a ddephdr not an shdr, and
1503                  * handily the port bytes in the right place preset.
1504                  */
1505                 ddp = (struct ddpehdr *) skb_push(skb, sizeof(*ddp) - 4);
1506
1507                 /* Now fill in the long header */
1508
1509                 /*
1510                  * These two first. The mac overlays the new source/dest
1511                  * network information so we MUST copy these before
1512                  * we write the network numbers !
1513                  */
1514
1515                 ddp->deh_dnode = skb->mac.raw[0];     /* From physical header */
1516                 ddp->deh_snode = skb->mac.raw[1];     /* From physical header */
1517
1518                 ddp->deh_dnet  = ap->s_net;     /* Network number */
1519                 ddp->deh_snet  = ap->s_net;
1520                 ddp->deh_sum   = 0;             /* No checksum */
1521                 /*
1522                  * Not sure about this bit...
1523                  */
1524                 ddp->deh_len   = skb->len;
1525                 ddp->deh_hops  = DDP_MAXHOPS;   /* Non routable, so force a drop
1526                                                    if we slip up later */
1527                 /* Mend the byte order */
1528                 *((__u16 *)ddp) = htons(*((__u16 *)ddp));
1529         }
1530         skb->h.raw = skb->data;
1531
1532         return atalk_rcv(skb, dev, pt);
1533 freeit:
1534         kfree_skb(skb);
1535         return 0;
1536 }
1537
1538 static int atalk_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
1539                          size_t len)
1540 {
1541         struct sock *sk = sock->sk;
1542         struct atalk_sock *at = at_sk(sk);
1543         struct sockaddr_at *usat = (struct sockaddr_at *)msg->msg_name;
1544         int flags = msg->msg_flags;
1545         int loopback = 0;
1546         struct sockaddr_at local_satalk, gsat;
1547         struct sk_buff *skb;
1548         struct net_device *dev;
1549         struct ddpehdr *ddp;
1550         int size;
1551         struct atalk_route *rt;
1552         int err;
1553
1554         if (flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT))
1555                 return -EINVAL;
1556
1557         if (len > DDP_MAXSZ)
1558                 return -EMSGSIZE;
1559
1560         if (usat) {
1561                 if (sk->sk_zapped)
1562                         if (atalk_autobind(sk) < 0)
1563                                 return -EBUSY;
1564
1565                 if (msg->msg_namelen < sizeof(*usat) ||
1566                     usat->sat_family != AF_APPLETALK)
1567                         return -EINVAL;
1568
1569                 /* netatalk doesn't implement this check */
1570                 if (usat->sat_addr.s_node == ATADDR_BCAST &&
1571                     !sock_flag(sk, SOCK_BROADCAST)) {
1572                         printk(KERN_INFO "SO_BROADCAST: Fix your netatalk as "
1573                                          "it will break before 2.2\n");
1574 #if 0
1575                         return -EPERM;
1576 #endif
1577                 }
1578         } else {
1579                 if (sk->sk_state != TCP_ESTABLISHED)
1580                         return -ENOTCONN;
1581                 usat = &local_satalk;
1582                 usat->sat_family      = AF_APPLETALK;
1583                 usat->sat_port        = at->dest_port;
1584                 usat->sat_addr.s_node = at->dest_node;
1585                 usat->sat_addr.s_net  = at->dest_net;
1586         }
1587
1588         /* Build a packet */
1589         SOCK_DEBUG(sk, "SK %p: Got address.\n", sk);
1590
1591         /* For headers */
1592         size = sizeof(struct ddpehdr) + len + ddp_dl->header_length;
1593
1594         if (usat->sat_addr.s_net || usat->sat_addr.s_node == ATADDR_ANYNODE) {
1595                 rt = atrtr_find(&usat->sat_addr);
1596                 if (!rt)
1597                         return -ENETUNREACH;
1598
1599                 dev = rt->dev;
1600         } else {
1601                 struct atalk_addr at_hint;
1602
1603                 at_hint.s_node = 0;
1604                 at_hint.s_net  = at->src_net;
1605
1606                 rt = atrtr_find(&at_hint);
1607                 if (!rt)
1608                         return -ENETUNREACH;
1609
1610                 dev = rt->dev;
1611         }
1612
1613         SOCK_DEBUG(sk, "SK %p: Size needed %d, device %s\n",
1614                         sk, size, dev->name);
1615
1616         size += dev->hard_header_len;
1617         skb = sock_alloc_send_skb(sk, size, (flags & MSG_DONTWAIT), &err);
1618         if (!skb)
1619                 return err;
1620         
1621         skb->sk = sk;
1622         skb_reserve(skb, ddp_dl->header_length);
1623         skb_reserve(skb, dev->hard_header_len);
1624         skb->dev = dev;
1625
1626         SOCK_DEBUG(sk, "SK %p: Begin build.\n", sk);
1627
1628         ddp = (struct ddpehdr *)skb_put(skb, sizeof(struct ddpehdr));
1629         ddp->deh_pad  = 0;
1630         ddp->deh_hops = 0;
1631         ddp->deh_len  = len + sizeof(*ddp);
1632         /*
1633          * Fix up the length field [Ok this is horrible but otherwise
1634          * I end up with unions of bit fields and messy bit field order
1635          * compiler/endian dependencies..
1636          */
1637         *((__u16 *)ddp) = ntohs(*((__u16 *)ddp));
1638
1639         ddp->deh_dnet  = usat->sat_addr.s_net;
1640         ddp->deh_snet  = at->src_net;
1641         ddp->deh_dnode = usat->sat_addr.s_node;
1642         ddp->deh_snode = at->src_node;
1643         ddp->deh_dport = usat->sat_port;
1644         ddp->deh_sport = at->src_port;
1645
1646         SOCK_DEBUG(sk, "SK %p: Copy user data (%Zd bytes).\n", sk, len);
1647
1648         err = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len);
1649         if (err) {
1650                 kfree_skb(skb);
1651                 return -EFAULT;
1652         }
1653
1654         if (sk->sk_no_check == 1)
1655                 ddp->deh_sum = 0;
1656         else
1657                 ddp->deh_sum = atalk_checksum(skb, len + sizeof(*ddp));
1658
1659         /*
1660          * Loopback broadcast packets to non gateway targets (ie routes
1661          * to group we are in)
1662          */
1663         if (ddp->deh_dnode == ATADDR_BCAST &&
1664             !(rt->flags & RTF_GATEWAY) && !(dev->flags & IFF_LOOPBACK)) {
1665                 struct sk_buff *skb2 = skb_copy(skb, GFP_KERNEL);
1666
1667                 if (skb2) {
1668                         loopback = 1;
1669                         SOCK_DEBUG(sk, "SK %p: send out(copy).\n", sk);
1670                         if (aarp_send_ddp(dev, skb2,
1671                                           &usat->sat_addr, NULL) == -1)
1672                                 kfree_skb(skb2);
1673                                 /* else queued/sent above in the aarp queue */
1674                 }
1675         }
1676
1677         if (dev->flags & IFF_LOOPBACK || loopback) {
1678                 SOCK_DEBUG(sk, "SK %p: Loop back.\n", sk);
1679                 /* loop back */
1680                 skb_orphan(skb);
1681                 ddp_dl->request(ddp_dl, skb, dev->dev_addr);
1682         } else {
1683                 SOCK_DEBUG(sk, "SK %p: send out.\n", sk);
1684                 if (rt->flags & RTF_GATEWAY) {
1685                     gsat.sat_addr = rt->gateway;
1686                     usat = &gsat;
1687                 }
1688
1689                 if (aarp_send_ddp(dev, skb, &usat->sat_addr, NULL) == -1)
1690                         kfree_skb(skb);
1691                 /* else queued/sent above in the aarp queue */
1692         }
1693         SOCK_DEBUG(sk, "SK %p: Done write (%Zd).\n", sk, len);
1694
1695         return len;
1696 }
1697
1698 static int atalk_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg,
1699                          size_t size, int flags)
1700 {
1701         struct sock *sk = sock->sk;
1702         struct sockaddr_at *sat = (struct sockaddr_at *)msg->msg_name;
1703         struct ddpehdr *ddp;
1704         int copied = 0;
1705         int err = 0;
1706         struct ddpebits ddphv;
1707         struct sk_buff *skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
1708                                                 flags & MSG_DONTWAIT, &err);
1709         if (!skb)
1710                 return err;
1711
1712         /* FIXME: use skb->cb to be able to use shared skbs */
1713         ddp = ddp_hdr(skb);
1714         *((__u16 *)&ddphv) = ntohs(*((__u16 *)ddp));
1715
1716         if (sk->sk_type == SOCK_RAW) {
1717                 copied = ddphv.deh_len;
1718                 if (copied > size) {
1719                         copied = size;
1720                         msg->msg_flags |= MSG_TRUNC;
1721                 }
1722
1723                 err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
1724         } else {
1725                 copied = ddphv.deh_len - sizeof(*ddp);
1726                 if (copied > size) {
1727                         copied = size;
1728                         msg->msg_flags |= MSG_TRUNC;
1729                 }
1730                 err = skb_copy_datagram_iovec(skb, sizeof(*ddp),
1731                                               msg->msg_iov, copied);
1732         }
1733
1734         if (!err) {
1735                 if (sat) {
1736                         sat->sat_family      = AF_APPLETALK;
1737                         sat->sat_port        = ddp->deh_sport;
1738                         sat->sat_addr.s_node = ddp->deh_snode;
1739                         sat->sat_addr.s_net  = ddp->deh_snet;
1740                 }
1741                 msg->msg_namelen = sizeof(*sat);
1742         }
1743
1744         skb_free_datagram(sk, skb);     /* Free the datagram. */
1745         return err ? : copied;
1746 }
1747
1748
1749 /*
1750  * AppleTalk ioctl calls.
1751  */
1752 static int atalk_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
1753 {
1754         int rc = -EINVAL;
1755         struct sock *sk = sock->sk;
1756         void __user *argp = (void __user *)arg;
1757
1758         switch (cmd) {
1759                 /* Protocol layer */
1760                 case TIOCOUTQ: {
1761                         long amount = sk->sk_sndbuf -
1762                                       atomic_read(&sk->sk_wmem_alloc);
1763
1764                         if (amount < 0)
1765                                 amount = 0;
1766                         rc = put_user(amount, (int __user *)argp);
1767                         break;
1768                 }
1769                 case TIOCINQ: {
1770                         /*
1771                          * These two are safe on a single CPU system as only
1772                          * user tasks fiddle here
1773                          */
1774                         struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
1775                         long amount = 0;
1776
1777                         if (skb)
1778                                 amount = skb->len - sizeof(struct ddpehdr);
1779                         rc = put_user(amount, (int __user *)argp);
1780                         break;
1781                 }
1782                 case SIOCGSTAMP:
1783                         rc = sock_get_timestamp(sk, argp);
1784                         break;
1785                 /* Routing */
1786                 case SIOCADDRT:
1787                 case SIOCDELRT:
1788                         rc = -EPERM;
1789                         if (capable(CAP_NET_ADMIN))
1790                                 rc = atrtr_ioctl(cmd, argp);
1791                         break;
1792                 /* Interface */
1793                 case SIOCGIFADDR:
1794                 case SIOCSIFADDR:
1795                 case SIOCGIFBRDADDR:
1796                 case SIOCATALKDIFADDR:
1797                 case SIOCDIFADDR:
1798                 case SIOCSARP:          /* proxy AARP */
1799                 case SIOCDARP:          /* proxy AARP */
1800                         rtnl_lock();
1801                         rc = atif_ioctl(cmd, argp);
1802                         rtnl_unlock();
1803                         break;
1804                 /* Physical layer ioctl calls */
1805                 case SIOCSIFLINK:
1806                 case SIOCGIFHWADDR:
1807                 case SIOCSIFHWADDR:
1808                 case SIOCGIFFLAGS:
1809                 case SIOCSIFFLAGS:
1810                 case SIOCGIFTXQLEN:
1811                 case SIOCSIFTXQLEN:
1812                 case SIOCGIFMTU:
1813                 case SIOCGIFCONF:
1814                 case SIOCADDMULTI:
1815                 case SIOCDELMULTI:
1816                 case SIOCGIFCOUNT:
1817                 case SIOCGIFINDEX:
1818                 case SIOCGIFNAME:
1819                         rc = dev_ioctl(cmd, argp);
1820                         break;
1821         }
1822
1823         return rc;
1824 }
1825
1826 static struct net_proto_family atalk_family_ops = {
1827         .family         = PF_APPLETALK,
1828         .create         = atalk_create,
1829         .owner          = THIS_MODULE,
1830 };
1831
1832 static struct proto_ops SOCKOPS_WRAPPED(atalk_dgram_ops) = {
1833         .family         = PF_APPLETALK,
1834         .owner          = THIS_MODULE,
1835         .release        = atalk_release,
1836         .bind           = atalk_bind,
1837         .connect        = atalk_connect,
1838         .socketpair     = sock_no_socketpair,
1839         .accept         = sock_no_accept,
1840         .getname        = atalk_getname,
1841         .poll           = datagram_poll,
1842         .ioctl          = atalk_ioctl,
1843         .listen         = sock_no_listen,
1844         .shutdown       = sock_no_shutdown,
1845         .setsockopt     = sock_no_setsockopt,
1846         .getsockopt     = sock_no_getsockopt,
1847         .sendmsg        = atalk_sendmsg,
1848         .recvmsg        = atalk_recvmsg,
1849         .mmap           = sock_no_mmap,
1850         .sendpage       = sock_no_sendpage,
1851 };
1852
1853 #include <linux/smp_lock.h>
1854 SOCKOPS_WRAP(atalk_dgram, PF_APPLETALK);
1855
1856 static struct notifier_block ddp_notifier = {
1857         .notifier_call  = ddp_device_event,
1858 };
1859
1860 static struct packet_type ltalk_packet_type = {
1861         .type           = __constant_htons(ETH_P_LOCALTALK),
1862         .func           = ltalk_rcv,
1863 };
1864
1865 static struct packet_type ppptalk_packet_type = {
1866         .type           = __constant_htons(ETH_P_PPPTALK),
1867         .func           = atalk_rcv,
1868 };
1869
1870 static unsigned char ddp_snap_id[] = { 0x08, 0x00, 0x07, 0x80, 0x9B };
1871
1872 /* Export symbols for use by drivers when AppleTalk is a module */
1873 EXPORT_SYMBOL(aarp_send_ddp);
1874 EXPORT_SYMBOL(atrtr_get_dev);
1875 EXPORT_SYMBOL(atalk_find_dev_addr);
1876
1877 static char atalk_err_snap[] __initdata =
1878         KERN_CRIT "Unable to register DDP with SNAP.\n";
1879
1880 /* Called by proto.c on kernel start up */
1881 static int __init atalk_init(void)
1882 {
1883         (void)sock_register(&atalk_family_ops);
1884         ddp_dl = register_snap_client(ddp_snap_id, atalk_rcv);
1885         if (!ddp_dl)
1886                 printk(atalk_err_snap);
1887
1888         dev_add_pack(&ltalk_packet_type);
1889         dev_add_pack(&ppptalk_packet_type);
1890
1891         register_netdevice_notifier(&ddp_notifier);
1892         aarp_proto_init();
1893         atalk_proc_init();
1894         atalk_register_sysctl();
1895         return 0;
1896 }
1897 module_init(atalk_init);
1898
1899 /*
1900  * No explicit module reference count manipulation is needed in the
1901  * protocol. Socket layer sets module reference count for us
1902  * and interfaces reference counting is done
1903  * by the network device layer.
1904  *
1905  * Ergo, before the AppleTalk module can be removed, all AppleTalk
1906  * sockets be closed from user space.
1907  */
1908 static void __exit atalk_exit(void)
1909 {
1910 #ifdef CONFIG_SYSCTL
1911         atalk_unregister_sysctl();
1912 #endif /* CONFIG_SYSCTL */
1913         atalk_proc_exit();
1914         aarp_cleanup_module();  /* General aarp clean-up. */
1915         unregister_netdevice_notifier(&ddp_notifier);
1916         dev_remove_pack(&ltalk_packet_type);
1917         dev_remove_pack(&ppptalk_packet_type);
1918         unregister_snap_client(ddp_dl);
1919         sock_unregister(PF_APPLETALK);
1920 }
1921 module_exit(atalk_exit);
1922
1923 MODULE_LICENSE("GPL");
1924 MODULE_AUTHOR("Alan Cox <Alan.Cox@linux.org>");
1925 MODULE_DESCRIPTION("AppleTalk 0.20\n");
1926 MODULE_ALIAS_NETPROTO(PF_APPLETALK);