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