GNU Linux-libre 4.14.251-gnu1
[releases.git] / net / tipc / socket.c
1 /*
2  * net/tipc/socket.c: TIPC socket API
3  *
4  * Copyright (c) 2001-2007, 2012-2016, Ericsson AB
5  * Copyright (c) 2004-2008, 2010-2013, Wind River Systems
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the names of the copyright holders nor the names of its
17  *    contributors may be used to endorse or promote products derived from
18  *    this software without specific prior written permission.
19  *
20  * Alternatively, this software may be distributed under the terms of the
21  * GNU General Public License ("GPL") version 2 as published by the Free
22  * Software Foundation.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
25  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
28  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34  * POSSIBILITY OF SUCH DAMAGE.
35  */
36
37 #include <linux/rhashtable.h>
38 #include <linux/sched/signal.h>
39
40 #include "core.h"
41 #include "name_table.h"
42 #include "node.h"
43 #include "link.h"
44 #include "name_distr.h"
45 #include "socket.h"
46 #include "bcast.h"
47 #include "netlink.h"
48
49 #define CONN_TIMEOUT_DEFAULT    8000    /* default connect timeout = 8s */
50 #define CONN_PROBING_INTERVAL   msecs_to_jiffies(3600000)  /* [ms] => 1 h */
51 #define TIPC_FWD_MSG            1
52 #define TIPC_MAX_PORT           0xffffffff
53 #define TIPC_MIN_PORT           1
54 #define TIPC_ACK_RATE           4       /* ACK at 1/4 of of rcv window size */
55
56 enum {
57         TIPC_LISTEN = TCP_LISTEN,
58         TIPC_ESTABLISHED = TCP_ESTABLISHED,
59         TIPC_OPEN = TCP_CLOSE,
60         TIPC_DISCONNECTING = TCP_CLOSE_WAIT,
61         TIPC_CONNECTING = TCP_SYN_SENT,
62 };
63
64 /**
65  * struct tipc_sock - TIPC socket structure
66  * @sk: socket - interacts with 'port' and with user via the socket API
67  * @conn_type: TIPC type used when connection was established
68  * @conn_instance: TIPC instance used when connection was established
69  * @published: non-zero if port has one or more associated names
70  * @max_pkt: maximum packet size "hint" used when building messages sent by port
71  * @portid: unique port identity in TIPC socket hash table
72  * @phdr: preformatted message header used when sending messages
73  * #cong_links: list of congested links
74  * @publications: list of publications for port
75  * @blocking_link: address of the congested link we are currently sleeping on
76  * @pub_count: total # of publications port has made during its lifetime
77  * @probing_state:
78  * @conn_timeout: the time we can wait for an unresponded setup request
79  * @dupl_rcvcnt: number of bytes counted twice, in both backlog and rcv queue
80  * @cong_link_cnt: number of congested links
81  * @sent_unacked: # messages sent by socket, and not yet acked by peer
82  * @rcv_unacked: # messages read by user, but not yet acked back to peer
83  * @peer: 'connected' peer for dgram/rdm
84  * @node: hash table node
85  * @mc_method: cookie for use between socket and broadcast layer
86  * @rcu: rcu struct for tipc_sock
87  */
88 struct tipc_sock {
89         struct sock sk;
90         u32 conn_type;
91         u32 conn_instance;
92         int published;
93         u32 max_pkt;
94         u32 portid;
95         struct tipc_msg phdr;
96         struct list_head cong_links;
97         struct list_head publications;
98         u32 pub_count;
99         uint conn_timeout;
100         atomic_t dupl_rcvcnt;
101         bool probe_unacked;
102         u16 cong_link_cnt;
103         u16 snt_unacked;
104         u16 snd_win;
105         u16 peer_caps;
106         u16 rcv_unacked;
107         u16 rcv_win;
108         struct sockaddr_tipc peer;
109         struct rhash_head node;
110         struct tipc_mc_method mc_method;
111         struct rcu_head rcu;
112 };
113
114 static int tipc_backlog_rcv(struct sock *sk, struct sk_buff *skb);
115 static void tipc_data_ready(struct sock *sk);
116 static void tipc_write_space(struct sock *sk);
117 static void tipc_sock_destruct(struct sock *sk);
118 static int tipc_release(struct socket *sock);
119 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags,
120                        bool kern);
121 static void tipc_sk_timeout(unsigned long data);
122 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
123                            struct tipc_name_seq const *seq);
124 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
125                             struct tipc_name_seq const *seq);
126 static struct tipc_sock *tipc_sk_lookup(struct net *net, u32 portid);
127 static int tipc_sk_insert(struct tipc_sock *tsk);
128 static void tipc_sk_remove(struct tipc_sock *tsk);
129 static int __tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dsz);
130 static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dsz);
131
132 static const struct proto_ops packet_ops;
133 static const struct proto_ops stream_ops;
134 static const struct proto_ops msg_ops;
135 static struct proto tipc_proto;
136 static const struct rhashtable_params tsk_rht_params;
137
138 static u32 tsk_own_node(struct tipc_sock *tsk)
139 {
140         return msg_prevnode(&tsk->phdr);
141 }
142
143 static u32 tsk_peer_node(struct tipc_sock *tsk)
144 {
145         return msg_destnode(&tsk->phdr);
146 }
147
148 static u32 tsk_peer_port(struct tipc_sock *tsk)
149 {
150         return msg_destport(&tsk->phdr);
151 }
152
153 static  bool tsk_unreliable(struct tipc_sock *tsk)
154 {
155         return msg_src_droppable(&tsk->phdr) != 0;
156 }
157
158 static void tsk_set_unreliable(struct tipc_sock *tsk, bool unreliable)
159 {
160         msg_set_src_droppable(&tsk->phdr, unreliable ? 1 : 0);
161 }
162
163 static bool tsk_unreturnable(struct tipc_sock *tsk)
164 {
165         return msg_dest_droppable(&tsk->phdr) != 0;
166 }
167
168 static void tsk_set_unreturnable(struct tipc_sock *tsk, bool unreturnable)
169 {
170         msg_set_dest_droppable(&tsk->phdr, unreturnable ? 1 : 0);
171 }
172
173 static int tsk_importance(struct tipc_sock *tsk)
174 {
175         return msg_importance(&tsk->phdr);
176 }
177
178 static int tsk_set_importance(struct tipc_sock *tsk, int imp)
179 {
180         if (imp > TIPC_CRITICAL_IMPORTANCE)
181                 return -EINVAL;
182         msg_set_importance(&tsk->phdr, (u32)imp);
183         return 0;
184 }
185
186 static struct tipc_sock *tipc_sk(const struct sock *sk)
187 {
188         return container_of(sk, struct tipc_sock, sk);
189 }
190
191 static bool tsk_conn_cong(struct tipc_sock *tsk)
192 {
193         return tsk->snt_unacked > tsk->snd_win;
194 }
195
196 /* tsk_blocks(): translate a buffer size in bytes to number of
197  * advertisable blocks, taking into account the ratio truesize(len)/len
198  * We can trust that this ratio is always < 4 for len >= FLOWCTL_BLK_SZ
199  */
200 static u16 tsk_adv_blocks(int len)
201 {
202         return len / FLOWCTL_BLK_SZ / 4;
203 }
204
205 /* tsk_inc(): increment counter for sent or received data
206  * - If block based flow control is not supported by peer we
207  *   fall back to message based ditto, incrementing the counter
208  */
209 static u16 tsk_inc(struct tipc_sock *tsk, int msglen)
210 {
211         if (likely(tsk->peer_caps & TIPC_BLOCK_FLOWCTL))
212                 return ((msglen / FLOWCTL_BLK_SZ) + 1);
213         return 1;
214 }
215
216 /**
217  * tsk_advance_rx_queue - discard first buffer in socket receive queue
218  *
219  * Caller must hold socket lock
220  */
221 static void tsk_advance_rx_queue(struct sock *sk)
222 {
223         kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
224 }
225
226 /* tipc_sk_respond() : send response message back to sender
227  */
228 static void tipc_sk_respond(struct sock *sk, struct sk_buff *skb, int err)
229 {
230         u32 selector;
231         u32 dnode;
232         u32 onode = tipc_own_addr(sock_net(sk));
233
234         if (!tipc_msg_reverse(onode, &skb, err))
235                 return;
236
237         dnode = msg_destnode(buf_msg(skb));
238         selector = msg_origport(buf_msg(skb));
239         tipc_node_xmit_skb(sock_net(sk), skb, dnode, selector);
240 }
241
242 /**
243  * tsk_rej_rx_queue - reject all buffers in socket receive queue
244  *
245  * Caller must hold socket lock
246  */
247 static void tsk_rej_rx_queue(struct sock *sk)
248 {
249         struct sk_buff *skb;
250
251         while ((skb = __skb_dequeue(&sk->sk_receive_queue)))
252                 tipc_sk_respond(sk, skb, TIPC_ERR_NO_PORT);
253 }
254
255 static bool tipc_sk_connected(struct sock *sk)
256 {
257         return sk->sk_state == TIPC_ESTABLISHED;
258 }
259
260 /* tipc_sk_type_connectionless - check if the socket is datagram socket
261  * @sk: socket
262  *
263  * Returns true if connection less, false otherwise
264  */
265 static bool tipc_sk_type_connectionless(struct sock *sk)
266 {
267         return sk->sk_type == SOCK_RDM || sk->sk_type == SOCK_DGRAM;
268 }
269
270 /* tsk_peer_msg - verify if message was sent by connected port's peer
271  *
272  * Handles cases where the node's network address has changed from
273  * the default of <0.0.0> to its configured setting.
274  */
275 static bool tsk_peer_msg(struct tipc_sock *tsk, struct tipc_msg *msg)
276 {
277         struct sock *sk = &tsk->sk;
278         struct tipc_net *tn = net_generic(sock_net(sk), tipc_net_id);
279         u32 peer_port = tsk_peer_port(tsk);
280         u32 orig_node;
281         u32 peer_node;
282
283         if (unlikely(!tipc_sk_connected(sk)))
284                 return false;
285
286         if (unlikely(msg_origport(msg) != peer_port))
287                 return false;
288
289         orig_node = msg_orignode(msg);
290         peer_node = tsk_peer_node(tsk);
291
292         if (likely(orig_node == peer_node))
293                 return true;
294
295         if (!orig_node && (peer_node == tn->own_addr))
296                 return true;
297
298         if (!peer_node && (orig_node == tn->own_addr))
299                 return true;
300
301         return false;
302 }
303
304 /* tipc_set_sk_state - set the sk_state of the socket
305  * @sk: socket
306  *
307  * Caller must hold socket lock
308  *
309  * Returns 0 on success, errno otherwise
310  */
311 static int tipc_set_sk_state(struct sock *sk, int state)
312 {
313         int oldsk_state = sk->sk_state;
314         int res = -EINVAL;
315
316         switch (state) {
317         case TIPC_OPEN:
318                 res = 0;
319                 break;
320         case TIPC_LISTEN:
321         case TIPC_CONNECTING:
322                 if (oldsk_state == TIPC_OPEN)
323                         res = 0;
324                 break;
325         case TIPC_ESTABLISHED:
326                 if (oldsk_state == TIPC_CONNECTING ||
327                     oldsk_state == TIPC_OPEN)
328                         res = 0;
329                 break;
330         case TIPC_DISCONNECTING:
331                 if (oldsk_state == TIPC_CONNECTING ||
332                     oldsk_state == TIPC_ESTABLISHED)
333                         res = 0;
334                 break;
335         }
336
337         if (!res)
338                 sk->sk_state = state;
339
340         return res;
341 }
342
343 static int tipc_sk_sock_err(struct socket *sock, long *timeout)
344 {
345         struct sock *sk = sock->sk;
346         int err = sock_error(sk);
347         int typ = sock->type;
348
349         if (err)
350                 return err;
351         if (typ == SOCK_STREAM || typ == SOCK_SEQPACKET) {
352                 if (sk->sk_state == TIPC_DISCONNECTING)
353                         return -EPIPE;
354                 else if (!tipc_sk_connected(sk))
355                         return -ENOTCONN;
356         }
357         if (!*timeout)
358                 return -EAGAIN;
359         if (signal_pending(current))
360                 return sock_intr_errno(*timeout);
361
362         return 0;
363 }
364
365 #define tipc_wait_for_cond(sock_, timeo_, condition_)                          \
366 ({                                                                             \
367         struct sock *sk_;                                                      \
368         int rc_;                                                               \
369                                                                                \
370         while ((rc_ = !(condition_))) {                                        \
371                 DEFINE_WAIT_FUNC(wait_, woken_wake_function);                  \
372                 sk_ = (sock_)->sk;                                             \
373                 rc_ = tipc_sk_sock_err((sock_), timeo_);                       \
374                 if (rc_)                                                       \
375                         break;                                                 \
376                 prepare_to_wait(sk_sleep(sk_), &wait_, TASK_INTERRUPTIBLE);    \
377                 release_sock(sk_);                                             \
378                 *(timeo_) = wait_woken(&wait_, TASK_INTERRUPTIBLE, *(timeo_)); \
379                 sched_annotate_sleep();                                        \
380                 lock_sock(sk_);                                                \
381                 remove_wait_queue(sk_sleep(sk_), &wait_);                      \
382         }                                                                      \
383         rc_;                                                                   \
384 })
385
386 /**
387  * tipc_sk_create - create a TIPC socket
388  * @net: network namespace (must be default network)
389  * @sock: pre-allocated socket structure
390  * @protocol: protocol indicator (must be 0)
391  * @kern: caused by kernel or by userspace?
392  *
393  * This routine creates additional data structures used by the TIPC socket,
394  * initializes them, and links them together.
395  *
396  * Returns 0 on success, errno otherwise
397  */
398 static int tipc_sk_create(struct net *net, struct socket *sock,
399                           int protocol, int kern)
400 {
401         struct tipc_net *tn;
402         const struct proto_ops *ops;
403         struct sock *sk;
404         struct tipc_sock *tsk;
405         struct tipc_msg *msg;
406
407         /* Validate arguments */
408         if (unlikely(protocol != 0))
409                 return -EPROTONOSUPPORT;
410
411         switch (sock->type) {
412         case SOCK_STREAM:
413                 ops = &stream_ops;
414                 break;
415         case SOCK_SEQPACKET:
416                 ops = &packet_ops;
417                 break;
418         case SOCK_DGRAM:
419         case SOCK_RDM:
420                 ops = &msg_ops;
421                 break;
422         default:
423                 return -EPROTOTYPE;
424         }
425
426         /* Allocate socket's protocol area */
427         sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto, kern);
428         if (sk == NULL)
429                 return -ENOMEM;
430
431         tsk = tipc_sk(sk);
432         tsk->max_pkt = MAX_PKT_DEFAULT;
433         INIT_LIST_HEAD(&tsk->publications);
434         INIT_LIST_HEAD(&tsk->cong_links);
435         msg = &tsk->phdr;
436         tn = net_generic(sock_net(sk), tipc_net_id);
437
438         /* Finish initializing socket data structures */
439         sock->ops = ops;
440         sock_init_data(sock, sk);
441         tipc_set_sk_state(sk, TIPC_OPEN);
442         if (tipc_sk_insert(tsk)) {
443                 pr_warn("Socket create failed; port number exhausted\n");
444                 return -EINVAL;
445         }
446
447         /* Ensure tsk is visible before we read own_addr. */
448         smp_mb();
449
450         tipc_msg_init(tn->own_addr, msg, TIPC_LOW_IMPORTANCE, TIPC_NAMED_MSG,
451                       NAMED_H_SIZE, 0);
452
453         msg_set_origport(msg, tsk->portid);
454         setup_timer(&sk->sk_timer, tipc_sk_timeout, (unsigned long)tsk);
455         sk->sk_shutdown = 0;
456         sk->sk_backlog_rcv = tipc_backlog_rcv;
457         sk->sk_rcvbuf = sysctl_tipc_rmem[1];
458         sk->sk_data_ready = tipc_data_ready;
459         sk->sk_write_space = tipc_write_space;
460         sk->sk_destruct = tipc_sock_destruct;
461         tsk->conn_timeout = CONN_TIMEOUT_DEFAULT;
462         atomic_set(&tsk->dupl_rcvcnt, 0);
463
464         /* Start out with safe limits until we receive an advertised window */
465         tsk->snd_win = tsk_adv_blocks(RCVBUF_MIN);
466         tsk->rcv_win = tsk->snd_win;
467
468         if (tipc_sk_type_connectionless(sk)) {
469                 tsk_set_unreturnable(tsk, true);
470                 if (sock->type == SOCK_DGRAM)
471                         tsk_set_unreliable(tsk, true);
472         }
473
474         return 0;
475 }
476
477 static void tipc_sk_callback(struct rcu_head *head)
478 {
479         struct tipc_sock *tsk = container_of(head, struct tipc_sock, rcu);
480
481         sock_put(&tsk->sk);
482 }
483
484 /* Caller should hold socket lock for the socket. */
485 static void __tipc_shutdown(struct socket *sock, int error)
486 {
487         struct sock *sk = sock->sk;
488         struct tipc_sock *tsk = tipc_sk(sk);
489         struct net *net = sock_net(sk);
490         long timeout = msecs_to_jiffies(CONN_TIMEOUT_DEFAULT);
491         u32 dnode = tsk_peer_node(tsk);
492         struct sk_buff *skb;
493
494         /* Avoid that hi-prio shutdown msgs bypass msgs in link wakeup queue */
495         tipc_wait_for_cond(sock, &timeout, (!tsk->cong_link_cnt &&
496                                             !tsk_conn_cong(tsk)));
497
498         /* Reject all unreceived messages, except on an active connection
499          * (which disconnects locally & sends a 'FIN+' to peer).
500          */
501         while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
502                 if (TIPC_SKB_CB(skb)->bytes_read) {
503                         kfree_skb(skb);
504                         continue;
505                 }
506                 if (!tipc_sk_type_connectionless(sk) &&
507                     sk->sk_state != TIPC_DISCONNECTING) {
508                         tipc_set_sk_state(sk, TIPC_DISCONNECTING);
509                         tipc_node_remove_conn(net, dnode, tsk->portid);
510                 }
511                 tipc_sk_respond(sk, skb, error);
512         }
513
514         if (tipc_sk_type_connectionless(sk))
515                 return;
516
517         if (sk->sk_state != TIPC_DISCONNECTING) {
518                 skb = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE,
519                                       TIPC_CONN_MSG, SHORT_H_SIZE, 0, dnode,
520                                       tsk_own_node(tsk), tsk_peer_port(tsk),
521                                       tsk->portid, error);
522                 if (skb)
523                         tipc_node_xmit_skb(net, skb, dnode, tsk->portid);
524                 tipc_node_remove_conn(net, dnode, tsk->portid);
525                 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
526         }
527 }
528
529 /**
530  * tipc_release - destroy a TIPC socket
531  * @sock: socket to destroy
532  *
533  * This routine cleans up any messages that are still queued on the socket.
534  * For DGRAM and RDM socket types, all queued messages are rejected.
535  * For SEQPACKET and STREAM socket types, the first message is rejected
536  * and any others are discarded.  (If the first message on a STREAM socket
537  * is partially-read, it is discarded and the next one is rejected instead.)
538  *
539  * NOTE: Rejected messages are not necessarily returned to the sender!  They
540  * are returned or discarded according to the "destination droppable" setting
541  * specified for the message by the sender.
542  *
543  * Returns 0 on success, errno otherwise
544  */
545 static int tipc_release(struct socket *sock)
546 {
547         struct sock *sk = sock->sk;
548         struct tipc_sock *tsk;
549
550         /*
551          * Exit if socket isn't fully initialized (occurs when a failed accept()
552          * releases a pre-allocated child socket that was never used)
553          */
554         if (sk == NULL)
555                 return 0;
556
557         tsk = tipc_sk(sk);
558         lock_sock(sk);
559
560         __tipc_shutdown(sock, TIPC_ERR_NO_PORT);
561         sk->sk_shutdown = SHUTDOWN_MASK;
562         tipc_sk_withdraw(tsk, 0, NULL);
563         sk_stop_timer(sk, &sk->sk_timer);
564         tipc_sk_remove(tsk);
565
566         /* Reject any messages that accumulated in backlog queue */
567         release_sock(sk);
568         u32_list_purge(&tsk->cong_links);
569         tsk->cong_link_cnt = 0;
570         call_rcu(&tsk->rcu, tipc_sk_callback);
571         sock->sk = NULL;
572
573         return 0;
574 }
575
576 /**
577  * tipc_bind - associate or disassocate TIPC name(s) with a socket
578  * @sock: socket structure
579  * @uaddr: socket address describing name(s) and desired operation
580  * @uaddr_len: size of socket address data structure
581  *
582  * Name and name sequence binding is indicated using a positive scope value;
583  * a negative scope value unbinds the specified name.  Specifying no name
584  * (i.e. a socket address length of 0) unbinds all names from the socket.
585  *
586  * Returns 0 on success, errno otherwise
587  *
588  * NOTE: This routine doesn't need to take the socket lock since it doesn't
589  *       access any non-constant socket information.
590  */
591 static int tipc_bind(struct socket *sock, struct sockaddr *uaddr,
592                      int uaddr_len)
593 {
594         struct sock *sk = sock->sk;
595         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
596         struct tipc_sock *tsk = tipc_sk(sk);
597         int res = -EINVAL;
598
599         lock_sock(sk);
600         if (unlikely(!uaddr_len)) {
601                 res = tipc_sk_withdraw(tsk, 0, NULL);
602                 goto exit;
603         }
604
605         if (uaddr_len < sizeof(struct sockaddr_tipc)) {
606                 res = -EINVAL;
607                 goto exit;
608         }
609         if (addr->family != AF_TIPC) {
610                 res = -EAFNOSUPPORT;
611                 goto exit;
612         }
613
614         if (addr->addrtype == TIPC_ADDR_NAME)
615                 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
616         else if (addr->addrtype != TIPC_ADDR_NAMESEQ) {
617                 res = -EAFNOSUPPORT;
618                 goto exit;
619         }
620
621         if ((addr->addr.nameseq.type < TIPC_RESERVED_TYPES) &&
622             (addr->addr.nameseq.type != TIPC_TOP_SRV) &&
623             (addr->addr.nameseq.type != TIPC_CFG_SRV)) {
624                 res = -EACCES;
625                 goto exit;
626         }
627
628         res = (addr->scope > 0) ?
629                 tipc_sk_publish(tsk, addr->scope, &addr->addr.nameseq) :
630                 tipc_sk_withdraw(tsk, -addr->scope, &addr->addr.nameseq);
631 exit:
632         release_sock(sk);
633         return res;
634 }
635
636 /**
637  * tipc_getname - get port ID of socket or peer socket
638  * @sock: socket structure
639  * @uaddr: area for returned socket address
640  * @uaddr_len: area for returned length of socket address
641  * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
642  *
643  * Returns 0 on success, errno otherwise
644  *
645  * NOTE: This routine doesn't need to take the socket lock since it only
646  *       accesses socket information that is unchanging (or which changes in
647  *       a completely predictable manner).
648  */
649 static int tipc_getname(struct socket *sock, struct sockaddr *uaddr,
650                         int *uaddr_len, int peer)
651 {
652         struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
653         struct sock *sk = sock->sk;
654         struct tipc_sock *tsk = tipc_sk(sk);
655         struct tipc_net *tn = net_generic(sock_net(sock->sk), tipc_net_id);
656
657         memset(addr, 0, sizeof(*addr));
658         if (peer) {
659                 if ((!tipc_sk_connected(sk)) &&
660                     ((peer != 2) || (sk->sk_state != TIPC_DISCONNECTING)))
661                         return -ENOTCONN;
662                 addr->addr.id.ref = tsk_peer_port(tsk);
663                 addr->addr.id.node = tsk_peer_node(tsk);
664         } else {
665                 addr->addr.id.ref = tsk->portid;
666                 addr->addr.id.node = tn->own_addr;
667         }
668
669         *uaddr_len = sizeof(*addr);
670         addr->addrtype = TIPC_ADDR_ID;
671         addr->family = AF_TIPC;
672         addr->scope = 0;
673         addr->addr.name.domain = 0;
674
675         return 0;
676 }
677
678 /**
679  * tipc_poll - read and possibly block on pollmask
680  * @file: file structure associated with the socket
681  * @sock: socket for which to calculate the poll bits
682  * @wait: ???
683  *
684  * Returns pollmask value
685  *
686  * COMMENTARY:
687  * It appears that the usual socket locking mechanisms are not useful here
688  * since the pollmask info is potentially out-of-date the moment this routine
689  * exits.  TCP and other protocols seem to rely on higher level poll routines
690  * to handle any preventable race conditions, so TIPC will do the same ...
691  *
692  * IMPORTANT: The fact that a read or write operation is indicated does NOT
693  * imply that the operation will succeed, merely that it should be performed
694  * and will not block.
695  */
696 static unsigned int tipc_poll(struct file *file, struct socket *sock,
697                               poll_table *wait)
698 {
699         struct sock *sk = sock->sk;
700         struct tipc_sock *tsk = tipc_sk(sk);
701         u32 mask = 0;
702
703         sock_poll_wait(file, sk_sleep(sk), wait);
704
705         if (sk->sk_shutdown & RCV_SHUTDOWN)
706                 mask |= POLLRDHUP | POLLIN | POLLRDNORM;
707         if (sk->sk_shutdown == SHUTDOWN_MASK)
708                 mask |= POLLHUP;
709
710         switch (sk->sk_state) {
711         case TIPC_ESTABLISHED:
712                 if (!tsk->cong_link_cnt && !tsk_conn_cong(tsk))
713                         mask |= POLLOUT;
714                 /* fall thru' */
715         case TIPC_LISTEN:
716         case TIPC_CONNECTING:
717                 if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
718                         mask |= (POLLIN | POLLRDNORM);
719                 break;
720         case TIPC_OPEN:
721                 if (!tsk->cong_link_cnt)
722                         mask |= POLLOUT;
723                 if (tipc_sk_type_connectionless(sk) &&
724                     (!skb_queue_empty_lockless(&sk->sk_receive_queue)))
725                         mask |= (POLLIN | POLLRDNORM);
726                 break;
727         case TIPC_DISCONNECTING:
728                 mask = (POLLIN | POLLRDNORM | POLLHUP);
729                 break;
730         }
731
732         return mask;
733 }
734
735 /**
736  * tipc_sendmcast - send multicast message
737  * @sock: socket structure
738  * @seq: destination address
739  * @msg: message to send
740  * @dlen: length of data to send
741  * @timeout: timeout to wait for wakeup
742  *
743  * Called from function tipc_sendmsg(), which has done all sanity checks
744  * Returns the number of bytes sent on success, or errno
745  */
746 static int tipc_sendmcast(struct  socket *sock, struct tipc_name_seq *seq,
747                           struct msghdr *msg, size_t dlen, long timeout)
748 {
749         struct sock *sk = sock->sk;
750         struct tipc_sock *tsk = tipc_sk(sk);
751         struct tipc_msg *hdr = &tsk->phdr;
752         struct net *net = sock_net(sk);
753         int mtu = tipc_bcast_get_mtu(net);
754         struct tipc_mc_method *method = &tsk->mc_method;
755         u32 domain = addr_domain(net, TIPC_CLUSTER_SCOPE);
756         struct sk_buff_head pkts;
757         struct tipc_nlist dsts;
758         int rc;
759
760         /* Block or return if any destination link is congested */
761         rc = tipc_wait_for_cond(sock, &timeout, !tsk->cong_link_cnt);
762         if (unlikely(rc))
763                 return rc;
764
765         /* Lookup destination nodes */
766         tipc_nlist_init(&dsts, tipc_own_addr(net));
767         tipc_nametbl_lookup_dst_nodes(net, seq->type, seq->lower,
768                                       seq->upper, domain, &dsts);
769         if (!dsts.local && !dsts.remote)
770                 return -EHOSTUNREACH;
771
772         /* Build message header */
773         msg_set_type(hdr, TIPC_MCAST_MSG);
774         msg_set_hdr_sz(hdr, MCAST_H_SIZE);
775         msg_set_lookup_scope(hdr, TIPC_CLUSTER_SCOPE);
776         msg_set_destport(hdr, 0);
777         msg_set_destnode(hdr, 0);
778         msg_set_nametype(hdr, seq->type);
779         msg_set_namelower(hdr, seq->lower);
780         msg_set_nameupper(hdr, seq->upper);
781
782         /* Build message as chain of buffers */
783         skb_queue_head_init(&pkts);
784         rc = tipc_msg_build(hdr, msg, 0, dlen, mtu, &pkts);
785
786         /* Send message if build was successful */
787         if (unlikely(rc == dlen))
788                 rc = tipc_mcast_xmit(net, &pkts, method, &dsts,
789                                      &tsk->cong_link_cnt);
790
791         tipc_nlist_purge(&dsts);
792
793         return rc ? rc : dlen;
794 }
795
796 /**
797  * tipc_sk_mcast_rcv - Deliver multicast messages to all destination sockets
798  * @arrvq: queue with arriving messages, to be cloned after destination lookup
799  * @inputq: queue with cloned messages, delivered to socket after dest lookup
800  *
801  * Multi-threaded: parallel calls with reference to same queues may occur
802  */
803 void tipc_sk_mcast_rcv(struct net *net, struct sk_buff_head *arrvq,
804                        struct sk_buff_head *inputq)
805 {
806         struct tipc_msg *msg;
807         struct list_head dports;
808         u32 portid;
809         u32 scope = TIPC_CLUSTER_SCOPE;
810         struct sk_buff_head tmpq;
811         uint hsz;
812         struct sk_buff *skb, *_skb;
813
814         __skb_queue_head_init(&tmpq);
815         INIT_LIST_HEAD(&dports);
816
817         skb = tipc_skb_peek(arrvq, &inputq->lock);
818         for (; skb; skb = tipc_skb_peek(arrvq, &inputq->lock)) {
819                 msg = buf_msg(skb);
820                 hsz = skb_headroom(skb) + msg_hdr_sz(msg);
821
822                 if (in_own_node(net, msg_orignode(msg)))
823                         scope = TIPC_NODE_SCOPE;
824
825                 /* Create destination port list and message clones: */
826                 tipc_nametbl_mc_translate(net,
827                                           msg_nametype(msg), msg_namelower(msg),
828                                           msg_nameupper(msg), scope, &dports);
829                 portid = u32_pop(&dports);
830                 for (; portid; portid = u32_pop(&dports)) {
831                         _skb = __pskb_copy(skb, hsz, GFP_ATOMIC);
832                         if (_skb) {
833                                 msg_set_destport(buf_msg(_skb), portid);
834                                 __skb_queue_tail(&tmpq, _skb);
835                                 continue;
836                         }
837                         pr_warn("Failed to clone mcast rcv buffer\n");
838                 }
839                 /* Append to inputq if not already done by other thread */
840                 spin_lock_bh(&inputq->lock);
841                 if (skb_peek(arrvq) == skb) {
842                         skb_queue_splice_tail_init(&tmpq, inputq);
843                         /* Decrease the skb's refcnt as increasing in the
844                          * function tipc_skb_peek
845                          */
846                         kfree_skb(__skb_dequeue(arrvq));
847                 }
848                 spin_unlock_bh(&inputq->lock);
849                 __skb_queue_purge(&tmpq);
850                 kfree_skb(skb);
851         }
852         tipc_sk_rcv(net, inputq);
853 }
854
855 /**
856  * tipc_sk_proto_rcv - receive a connection mng protocol message
857  * @tsk: receiving socket
858  * @skb: pointer to message buffer.
859  */
860 static void tipc_sk_proto_rcv(struct tipc_sock *tsk, struct sk_buff *skb,
861                               struct sk_buff_head *xmitq)
862 {
863         struct sock *sk = &tsk->sk;
864         u32 onode = tsk_own_node(tsk);
865         struct tipc_msg *hdr = buf_msg(skb);
866         int mtyp = msg_type(hdr);
867         bool conn_cong;
868
869         /* Ignore if connection cannot be validated: */
870         if (!tsk_peer_msg(tsk, hdr))
871                 goto exit;
872
873         if (unlikely(msg_errcode(hdr))) {
874                 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
875                 tipc_node_remove_conn(sock_net(sk), tsk_peer_node(tsk),
876                                       tsk_peer_port(tsk));
877                 sk->sk_state_change(sk);
878                 goto exit;
879         }
880
881         tsk->probe_unacked = false;
882
883         if (mtyp == CONN_PROBE) {
884                 msg_set_type(hdr, CONN_PROBE_REPLY);
885                 if (tipc_msg_reverse(onode, &skb, TIPC_OK))
886                         __skb_queue_tail(xmitq, skb);
887                 return;
888         } else if (mtyp == CONN_ACK) {
889                 conn_cong = tsk_conn_cong(tsk);
890                 tsk->snt_unacked -= msg_conn_ack(hdr);
891                 if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL)
892                         tsk->snd_win = msg_adv_win(hdr);
893                 if (conn_cong)
894                         sk->sk_write_space(sk);
895         } else if (mtyp != CONN_PROBE_REPLY) {
896                 pr_warn("Received unknown CONN_PROTO msg\n");
897         }
898 exit:
899         kfree_skb(skb);
900 }
901
902 /**
903  * tipc_sendmsg - send message in connectionless manner
904  * @sock: socket structure
905  * @m: message to send
906  * @dsz: amount of user data to be sent
907  *
908  * Message must have an destination specified explicitly.
909  * Used for SOCK_RDM and SOCK_DGRAM messages,
910  * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
911  * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
912  *
913  * Returns the number of bytes sent on success, or errno otherwise
914  */
915 static int tipc_sendmsg(struct socket *sock,
916                         struct msghdr *m, size_t dsz)
917 {
918         struct sock *sk = sock->sk;
919         int ret;
920
921         lock_sock(sk);
922         ret = __tipc_sendmsg(sock, m, dsz);
923         release_sock(sk);
924
925         return ret;
926 }
927
928 static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dlen)
929 {
930         struct sock *sk = sock->sk;
931         struct net *net = sock_net(sk);
932         struct tipc_sock *tsk = tipc_sk(sk);
933         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
934         long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
935         struct list_head *clinks = &tsk->cong_links;
936         bool syn = !tipc_sk_type_connectionless(sk);
937         struct tipc_msg *hdr = &tsk->phdr;
938         struct tipc_name_seq *seq;
939         struct sk_buff_head pkts;
940         u32 type, inst, domain;
941         u32 dnode, dport;
942         int mtu, rc;
943
944         if (unlikely(dlen > TIPC_MAX_USER_MSG_SIZE))
945                 return -EMSGSIZE;
946
947         if (unlikely(!dest)) {
948                 dest = &tsk->peer;
949                 if (!syn && dest->family != AF_TIPC)
950                         return -EDESTADDRREQ;
951         }
952
953         if (unlikely(m->msg_namelen < sizeof(*dest)))
954                 return -EINVAL;
955
956         if (unlikely(dest->family != AF_TIPC))
957                 return -EINVAL;
958
959         if (unlikely(syn)) {
960                 if (sk->sk_state == TIPC_LISTEN)
961                         return -EPIPE;
962                 if (sk->sk_state != TIPC_OPEN)
963                         return -EISCONN;
964                 if (tsk->published)
965                         return -EOPNOTSUPP;
966                 if (dest->addrtype == TIPC_ADDR_NAME) {
967                         tsk->conn_type = dest->addr.name.name.type;
968                         tsk->conn_instance = dest->addr.name.name.instance;
969                 }
970         }
971
972         seq = &dest->addr.nameseq;
973         if (dest->addrtype == TIPC_ADDR_MCAST)
974                 return tipc_sendmcast(sock, seq, m, dlen, timeout);
975
976         if (dest->addrtype == TIPC_ADDR_NAME) {
977                 type = dest->addr.name.name.type;
978                 inst = dest->addr.name.name.instance;
979                 domain = dest->addr.name.domain;
980                 dnode = domain;
981                 msg_set_type(hdr, TIPC_NAMED_MSG);
982                 msg_set_hdr_sz(hdr, NAMED_H_SIZE);
983                 msg_set_nametype(hdr, type);
984                 msg_set_nameinst(hdr, inst);
985                 msg_set_lookup_scope(hdr, tipc_addr_scope(domain));
986                 dport = tipc_nametbl_translate(net, type, inst, &dnode);
987                 msg_set_destnode(hdr, dnode);
988                 msg_set_destport(hdr, dport);
989                 if (unlikely(!dport && !dnode))
990                         return -EHOSTUNREACH;
991
992         } else if (dest->addrtype == TIPC_ADDR_ID) {
993                 dnode = dest->addr.id.node;
994                 msg_set_type(hdr, TIPC_DIRECT_MSG);
995                 msg_set_lookup_scope(hdr, 0);
996                 msg_set_destnode(hdr, dnode);
997                 msg_set_destport(hdr, dest->addr.id.ref);
998                 msg_set_hdr_sz(hdr, BASIC_H_SIZE);
999         }
1000
1001         /* Block or return if destination link is congested */
1002         rc = tipc_wait_for_cond(sock, &timeout, !u32_find(clinks, dnode));
1003         if (unlikely(rc))
1004                 return rc;
1005
1006         skb_queue_head_init(&pkts);
1007         mtu = tipc_node_get_mtu(net, dnode, tsk->portid);
1008         rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);
1009         if (unlikely(rc != dlen))
1010                 return rc;
1011
1012         rc = tipc_node_xmit(net, &pkts, dnode, tsk->portid);
1013         if (unlikely(rc == -ELINKCONG)) {
1014                 u32_push(clinks, dnode);
1015                 tsk->cong_link_cnt++;
1016                 rc = 0;
1017         }
1018
1019         if (unlikely(syn && !rc))
1020                 tipc_set_sk_state(sk, TIPC_CONNECTING);
1021
1022         return rc ? rc : dlen;
1023 }
1024
1025 /**
1026  * tipc_sendstream - send stream-oriented data
1027  * @sock: socket structure
1028  * @m: data to send
1029  * @dsz: total length of data to be transmitted
1030  *
1031  * Used for SOCK_STREAM data.
1032  *
1033  * Returns the number of bytes sent on success (or partial success),
1034  * or errno if no data sent
1035  */
1036 static int tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dsz)
1037 {
1038         struct sock *sk = sock->sk;
1039         int ret;
1040
1041         lock_sock(sk);
1042         ret = __tipc_sendstream(sock, m, dsz);
1043         release_sock(sk);
1044
1045         return ret;
1046 }
1047
1048 static int __tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dlen)
1049 {
1050         struct sock *sk = sock->sk;
1051         DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1052         long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
1053         struct tipc_sock *tsk = tipc_sk(sk);
1054         struct tipc_msg *hdr = &tsk->phdr;
1055         struct net *net = sock_net(sk);
1056         struct sk_buff_head pkts;
1057         u32 dnode = tsk_peer_node(tsk);
1058         int send, sent = 0;
1059         int rc = 0;
1060
1061         skb_queue_head_init(&pkts);
1062
1063         if (unlikely(dlen > INT_MAX))
1064                 return -EMSGSIZE;
1065
1066         /* Handle implicit connection setup */
1067         if (unlikely(dest)) {
1068                 rc = __tipc_sendmsg(sock, m, dlen);
1069                 if (dlen && dlen == rc) {
1070                         tsk->peer_caps = tipc_node_get_capabilities(net, dnode);
1071                         tsk->snt_unacked = tsk_inc(tsk, dlen + msg_hdr_sz(hdr));
1072                 }
1073                 return rc;
1074         }
1075
1076         do {
1077                 rc = tipc_wait_for_cond(sock, &timeout,
1078                                         (!tsk->cong_link_cnt &&
1079                                          !tsk_conn_cong(tsk) &&
1080                                          tipc_sk_connected(sk)));
1081                 if (unlikely(rc))
1082                         break;
1083
1084                 send = min_t(size_t, dlen - sent, TIPC_MAX_USER_MSG_SIZE);
1085                 rc = tipc_msg_build(hdr, m, sent, send, tsk->max_pkt, &pkts);
1086                 if (unlikely(rc != send))
1087                         break;
1088
1089                 rc = tipc_node_xmit(net, &pkts, dnode, tsk->portid);
1090                 if (unlikely(rc == -ELINKCONG)) {
1091                         tsk->cong_link_cnt = 1;
1092                         rc = 0;
1093                 }
1094                 if (likely(!rc)) {
1095                         tsk->snt_unacked += tsk_inc(tsk, send + MIN_H_SIZE);
1096                         sent += send;
1097                 }
1098         } while (sent < dlen && !rc);
1099
1100         return sent ? sent : rc;
1101 }
1102
1103 /**
1104  * tipc_send_packet - send a connection-oriented message
1105  * @sock: socket structure
1106  * @m: message to send
1107  * @dsz: length of data to be transmitted
1108  *
1109  * Used for SOCK_SEQPACKET messages.
1110  *
1111  * Returns the number of bytes sent on success, or errno otherwise
1112  */
1113 static int tipc_send_packet(struct socket *sock, struct msghdr *m, size_t dsz)
1114 {
1115         if (dsz > TIPC_MAX_USER_MSG_SIZE)
1116                 return -EMSGSIZE;
1117
1118         return tipc_sendstream(sock, m, dsz);
1119 }
1120
1121 /* tipc_sk_finish_conn - complete the setup of a connection
1122  */
1123 static void tipc_sk_finish_conn(struct tipc_sock *tsk, u32 peer_port,
1124                                 u32 peer_node)
1125 {
1126         struct sock *sk = &tsk->sk;
1127         struct net *net = sock_net(sk);
1128         struct tipc_msg *msg = &tsk->phdr;
1129
1130         msg_set_destnode(msg, peer_node);
1131         msg_set_destport(msg, peer_port);
1132         msg_set_type(msg, TIPC_CONN_MSG);
1133         msg_set_lookup_scope(msg, 0);
1134         msg_set_hdr_sz(msg, SHORT_H_SIZE);
1135
1136         sk_reset_timer(sk, &sk->sk_timer, jiffies + CONN_PROBING_INTERVAL);
1137         tipc_set_sk_state(sk, TIPC_ESTABLISHED);
1138         tipc_node_add_conn(net, peer_node, tsk->portid, peer_port);
1139         tsk->max_pkt = tipc_node_get_mtu(net, peer_node, tsk->portid);
1140         tsk->peer_caps = tipc_node_get_capabilities(net, peer_node);
1141         if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL)
1142                 return;
1143
1144         /* Fall back to message based flow control */
1145         tsk->rcv_win = FLOWCTL_MSG_WIN;
1146         tsk->snd_win = FLOWCTL_MSG_WIN;
1147 }
1148
1149 /**
1150  * set_orig_addr - capture sender's address for received message
1151  * @m: descriptor for message info
1152  * @msg: received message header
1153  *
1154  * Note: Address is not captured if not requested by receiver.
1155  */
1156 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
1157 {
1158         DECLARE_SOCKADDR(struct sockaddr_tipc *, addr, m->msg_name);
1159
1160         if (addr) {
1161                 addr->family = AF_TIPC;
1162                 addr->addrtype = TIPC_ADDR_ID;
1163                 memset(&addr->addr, 0, sizeof(addr->addr));
1164                 addr->addr.id.ref = msg_origport(msg);
1165                 addr->addr.id.node = msg_orignode(msg);
1166                 addr->addr.name.domain = 0;     /* could leave uninitialized */
1167                 addr->scope = 0;                /* could leave uninitialized */
1168                 m->msg_namelen = sizeof(struct sockaddr_tipc);
1169         }
1170 }
1171
1172 /**
1173  * tipc_sk_anc_data_recv - optionally capture ancillary data for received message
1174  * @m: descriptor for message info
1175  * @msg: received message header
1176  * @tsk: TIPC port associated with message
1177  *
1178  * Note: Ancillary data is not captured if not requested by receiver.
1179  *
1180  * Returns 0 if successful, otherwise errno
1181  */
1182 static int tipc_sk_anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
1183                                  struct tipc_sock *tsk)
1184 {
1185         u32 anc_data[3];
1186         u32 err;
1187         u32 dest_type;
1188         int has_name;
1189         int res;
1190
1191         if (likely(m->msg_controllen == 0))
1192                 return 0;
1193
1194         /* Optionally capture errored message object(s) */
1195         err = msg ? msg_errcode(msg) : 0;
1196         if (unlikely(err)) {
1197                 anc_data[0] = err;
1198                 anc_data[1] = msg_data_sz(msg);
1199                 res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
1200                 if (res)
1201                         return res;
1202                 if (anc_data[1]) {
1203                         res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
1204                                        msg_data(msg));
1205                         if (res)
1206                                 return res;
1207                 }
1208         }
1209
1210         /* Optionally capture message destination object */
1211         dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
1212         switch (dest_type) {
1213         case TIPC_NAMED_MSG:
1214                 has_name = 1;
1215                 anc_data[0] = msg_nametype(msg);
1216                 anc_data[1] = msg_namelower(msg);
1217                 anc_data[2] = msg_namelower(msg);
1218                 break;
1219         case TIPC_MCAST_MSG:
1220                 has_name = 1;
1221                 anc_data[0] = msg_nametype(msg);
1222                 anc_data[1] = msg_namelower(msg);
1223                 anc_data[2] = msg_nameupper(msg);
1224                 break;
1225         case TIPC_CONN_MSG:
1226                 has_name = (tsk->conn_type != 0);
1227                 anc_data[0] = tsk->conn_type;
1228                 anc_data[1] = tsk->conn_instance;
1229                 anc_data[2] = tsk->conn_instance;
1230                 break;
1231         default:
1232                 has_name = 0;
1233         }
1234         if (has_name) {
1235                 res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
1236                 if (res)
1237                         return res;
1238         }
1239
1240         return 0;
1241 }
1242
1243 static void tipc_sk_send_ack(struct tipc_sock *tsk)
1244 {
1245         struct sock *sk = &tsk->sk;
1246         struct net *net = sock_net(sk);
1247         struct sk_buff *skb = NULL;
1248         struct tipc_msg *msg;
1249         u32 peer_port = tsk_peer_port(tsk);
1250         u32 dnode = tsk_peer_node(tsk);
1251
1252         if (!tipc_sk_connected(sk))
1253                 return;
1254         skb = tipc_msg_create(CONN_MANAGER, CONN_ACK, INT_H_SIZE, 0,
1255                               dnode, tsk_own_node(tsk), peer_port,
1256                               tsk->portid, TIPC_OK);
1257         if (!skb)
1258                 return;
1259         msg = buf_msg(skb);
1260         msg_set_conn_ack(msg, tsk->rcv_unacked);
1261         tsk->rcv_unacked = 0;
1262
1263         /* Adjust to and advertize the correct window limit */
1264         if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL) {
1265                 tsk->rcv_win = tsk_adv_blocks(tsk->sk.sk_rcvbuf);
1266                 msg_set_adv_win(msg, tsk->rcv_win);
1267         }
1268         tipc_node_xmit_skb(net, skb, dnode, msg_link_selector(msg));
1269 }
1270
1271 static int tipc_wait_for_rcvmsg(struct socket *sock, long *timeop)
1272 {
1273         struct sock *sk = sock->sk;
1274         DEFINE_WAIT(wait);
1275         long timeo = *timeop;
1276         int err = sock_error(sk);
1277
1278         if (err)
1279                 return err;
1280
1281         for (;;) {
1282                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1283                 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1284                         if (sk->sk_shutdown & RCV_SHUTDOWN) {
1285                                 err = -ENOTCONN;
1286                                 break;
1287                         }
1288                         release_sock(sk);
1289                         timeo = schedule_timeout(timeo);
1290                         lock_sock(sk);
1291                 }
1292                 err = 0;
1293                 if (!skb_queue_empty(&sk->sk_receive_queue))
1294                         break;
1295                 err = -EAGAIN;
1296                 if (!timeo)
1297                         break;
1298                 err = sock_intr_errno(timeo);
1299                 if (signal_pending(current))
1300                         break;
1301
1302                 err = sock_error(sk);
1303                 if (err)
1304                         break;
1305         }
1306         finish_wait(sk_sleep(sk), &wait);
1307         *timeop = timeo;
1308         return err;
1309 }
1310
1311 /**
1312  * tipc_recvmsg - receive packet-oriented message
1313  * @m: descriptor for message info
1314  * @buflen: length of user buffer area
1315  * @flags: receive flags
1316  *
1317  * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
1318  * If the complete message doesn't fit in user area, truncate it.
1319  *
1320  * Returns size of returned message data, errno otherwise
1321  */
1322 static int tipc_recvmsg(struct socket *sock, struct msghdr *m,
1323                         size_t buflen,  int flags)
1324 {
1325         struct sock *sk = sock->sk;
1326         struct tipc_sock *tsk = tipc_sk(sk);
1327         struct sk_buff *skb;
1328         struct tipc_msg *hdr;
1329         bool connected = !tipc_sk_type_connectionless(sk);
1330         int rc, err, hlen, dlen, copy;
1331         long timeout;
1332
1333         /* Catch invalid receive requests */
1334         if (unlikely(!buflen))
1335                 return -EINVAL;
1336
1337         lock_sock(sk);
1338         if (unlikely(connected && sk->sk_state == TIPC_OPEN)) {
1339                 rc = -ENOTCONN;
1340                 goto exit;
1341         }
1342         timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1343
1344         do {
1345                 /* Look at first msg in receive queue; wait if necessary */
1346                 rc = tipc_wait_for_rcvmsg(sock, &timeout);
1347                 if (unlikely(rc))
1348                         goto exit;
1349                 skb = skb_peek(&sk->sk_receive_queue);
1350                 hdr = buf_msg(skb);
1351                 dlen = msg_data_sz(hdr);
1352                 hlen = msg_hdr_sz(hdr);
1353                 err = msg_errcode(hdr);
1354                 if (likely(dlen || err))
1355                         break;
1356                 tsk_advance_rx_queue(sk);
1357         } while (1);
1358
1359         /* Collect msg meta data, including error code and rejected data */
1360         set_orig_addr(m, hdr);
1361         rc = tipc_sk_anc_data_recv(m, hdr, tsk);
1362         if (unlikely(rc))
1363                 goto exit;
1364
1365         /* Capture data if non-error msg, otherwise just set return value */
1366         if (likely(!err)) {
1367                 copy = min_t(int, dlen, buflen);
1368                 if (unlikely(copy != dlen))
1369                         m->msg_flags |= MSG_TRUNC;
1370                 rc = skb_copy_datagram_msg(skb, hlen, m, copy);
1371         } else {
1372                 copy = 0;
1373                 rc = 0;
1374                 if (err != TIPC_CONN_SHUTDOWN && connected && !m->msg_control)
1375                         rc = -ECONNRESET;
1376         }
1377         if (unlikely(rc))
1378                 goto exit;
1379
1380         /* Caption of data or error code/rejected data was successful */
1381         if (unlikely(flags & MSG_PEEK))
1382                 goto exit;
1383
1384         tsk_advance_rx_queue(sk);
1385         if (likely(!connected))
1386                 goto exit;
1387
1388         /* Send connection flow control ack when applicable */
1389         tsk->rcv_unacked += tsk_inc(tsk, hlen + dlen);
1390         if (tsk->rcv_unacked >= tsk->rcv_win / TIPC_ACK_RATE)
1391                 tipc_sk_send_ack(tsk);
1392 exit:
1393         release_sock(sk);
1394         return rc ? rc : copy;
1395 }
1396
1397 /**
1398  * tipc_recvstream - receive stream-oriented data
1399  * @m: descriptor for message info
1400  * @buflen: total size of user buffer area
1401  * @flags: receive flags
1402  *
1403  * Used for SOCK_STREAM messages only.  If not enough data is available
1404  * will optionally wait for more; never truncates data.
1405  *
1406  * Returns size of returned message data, errno otherwise
1407  */
1408 static int tipc_recvstream(struct socket *sock, struct msghdr *m,
1409                            size_t buflen, int flags)
1410 {
1411         struct sock *sk = sock->sk;
1412         struct tipc_sock *tsk = tipc_sk(sk);
1413         struct sk_buff *skb;
1414         struct tipc_msg *hdr;
1415         struct tipc_skb_cb *skb_cb;
1416         bool peek = flags & MSG_PEEK;
1417         int offset, required, copy, copied = 0;
1418         int hlen, dlen, err, rc;
1419         long timeout;
1420
1421         /* Catch invalid receive attempts */
1422         if (unlikely(!buflen))
1423                 return -EINVAL;
1424
1425         lock_sock(sk);
1426
1427         if (unlikely(sk->sk_state == TIPC_OPEN)) {
1428                 rc = -ENOTCONN;
1429                 goto exit;
1430         }
1431         required = sock_rcvlowat(sk, flags & MSG_WAITALL, buflen);
1432         timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1433
1434         do {
1435                 /* Look at first msg in receive queue; wait if necessary */
1436                 rc = tipc_wait_for_rcvmsg(sock, &timeout);
1437                 if (unlikely(rc))
1438                         break;
1439                 skb = skb_peek(&sk->sk_receive_queue);
1440                 skb_cb = TIPC_SKB_CB(skb);
1441                 hdr = buf_msg(skb);
1442                 dlen = msg_data_sz(hdr);
1443                 hlen = msg_hdr_sz(hdr);
1444                 err = msg_errcode(hdr);
1445
1446                 /* Discard any empty non-errored (SYN-) message */
1447                 if (unlikely(!dlen && !err)) {
1448                         tsk_advance_rx_queue(sk);
1449                         continue;
1450                 }
1451
1452                 /* Collect msg meta data, incl. error code and rejected data */
1453                 if (!copied) {
1454                         set_orig_addr(m, hdr);
1455                         rc = tipc_sk_anc_data_recv(m, hdr, tsk);
1456                         if (rc)
1457                                 break;
1458                 }
1459
1460                 /* Copy data if msg ok, otherwise return error/partial data */
1461                 if (likely(!err)) {
1462                         offset = skb_cb->bytes_read;
1463                         copy = min_t(int, dlen - offset, buflen - copied);
1464                         rc = skb_copy_datagram_msg(skb, hlen + offset, m, copy);
1465                         if (unlikely(rc))
1466                                 break;
1467                         copied += copy;
1468                         offset += copy;
1469                         if (unlikely(offset < dlen)) {
1470                                 if (!peek)
1471                                         skb_cb->bytes_read = offset;
1472                                 break;
1473                         }
1474                 } else {
1475                         rc = 0;
1476                         if ((err != TIPC_CONN_SHUTDOWN) && !m->msg_control)
1477                                 rc = -ECONNRESET;
1478                         if (copied || rc)
1479                                 break;
1480                 }
1481
1482                 if (unlikely(peek))
1483                         break;
1484
1485                 tsk_advance_rx_queue(sk);
1486
1487                 /* Send connection flow control advertisement when applicable */
1488                 tsk->rcv_unacked += tsk_inc(tsk, hlen + dlen);
1489                 if (unlikely(tsk->rcv_unacked >= tsk->rcv_win / TIPC_ACK_RATE))
1490                         tipc_sk_send_ack(tsk);
1491
1492                 /* Exit if all requested data or FIN/error received */
1493                 if (copied == buflen || err)
1494                         break;
1495
1496         } while (!skb_queue_empty(&sk->sk_receive_queue) || copied < required);
1497 exit:
1498         release_sock(sk);
1499         return copied ? copied : rc;
1500 }
1501
1502 /**
1503  * tipc_write_space - wake up thread if port congestion is released
1504  * @sk: socket
1505  */
1506 static void tipc_write_space(struct sock *sk)
1507 {
1508         struct socket_wq *wq;
1509
1510         rcu_read_lock();
1511         wq = rcu_dereference(sk->sk_wq);
1512         if (skwq_has_sleeper(wq))
1513                 wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
1514                                                 POLLWRNORM | POLLWRBAND);
1515         rcu_read_unlock();
1516 }
1517
1518 /**
1519  * tipc_data_ready - wake up threads to indicate messages have been received
1520  * @sk: socket
1521  * @len: the length of messages
1522  */
1523 static void tipc_data_ready(struct sock *sk)
1524 {
1525         struct socket_wq *wq;
1526
1527         rcu_read_lock();
1528         wq = rcu_dereference(sk->sk_wq);
1529         if (skwq_has_sleeper(wq))
1530                 wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
1531                                                 POLLRDNORM | POLLRDBAND);
1532         rcu_read_unlock();
1533 }
1534
1535 static void tipc_sock_destruct(struct sock *sk)
1536 {
1537         __skb_queue_purge(&sk->sk_receive_queue);
1538 }
1539
1540 /**
1541  * filter_connect - Handle all incoming messages for a connection-based socket
1542  * @tsk: TIPC socket
1543  * @skb: pointer to message buffer. Set to NULL if buffer is consumed
1544  *
1545  * Returns true if everything ok, false otherwise
1546  */
1547 static bool filter_connect(struct tipc_sock *tsk, struct sk_buff *skb)
1548 {
1549         struct sock *sk = &tsk->sk;
1550         struct net *net = sock_net(sk);
1551         struct tipc_msg *hdr = buf_msg(skb);
1552         u32 pport = msg_origport(hdr);
1553         u32 pnode = msg_orignode(hdr);
1554
1555         if (unlikely(msg_mcast(hdr)))
1556                 return false;
1557
1558         switch (sk->sk_state) {
1559         case TIPC_CONNECTING:
1560                 /* Accept only ACK or NACK message */
1561                 if (unlikely(!msg_connected(hdr))) {
1562                         if (pport != tsk_peer_port(tsk) ||
1563                             pnode != tsk_peer_node(tsk))
1564                                 return false;
1565
1566                         tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1567                         sk->sk_err = ECONNREFUSED;
1568                         sk->sk_state_change(sk);
1569                         return true;
1570                 }
1571
1572                 if (unlikely(msg_errcode(hdr))) {
1573                         tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1574                         sk->sk_err = ECONNREFUSED;
1575                         sk->sk_state_change(sk);
1576                         return true;
1577                 }
1578
1579                 if (unlikely(!msg_isdata(hdr))) {
1580                         tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1581                         sk->sk_err = EINVAL;
1582                         sk->sk_state_change(sk);
1583                         return true;
1584                 }
1585
1586                 tipc_sk_finish_conn(tsk, msg_origport(hdr), msg_orignode(hdr));
1587                 msg_set_importance(&tsk->phdr, msg_importance(hdr));
1588
1589                 /* If 'ACK+' message, add to socket receive queue */
1590                 if (msg_data_sz(hdr))
1591                         return true;
1592
1593                 /* If empty 'ACK-' message, wake up sleeping connect() */
1594                 sk->sk_state_change(sk);
1595
1596                 /* 'ACK-' message is neither accepted nor rejected: */
1597                 msg_set_dest_droppable(hdr, 1);
1598                 return false;
1599
1600         case TIPC_OPEN:
1601         case TIPC_DISCONNECTING:
1602                 break;
1603         case TIPC_LISTEN:
1604                 /* Accept only SYN message */
1605                 if (!msg_connected(hdr) && !(msg_errcode(hdr)))
1606                         return true;
1607                 break;
1608         case TIPC_ESTABLISHED:
1609                 /* Accept only connection-based messages sent by peer */
1610                 if (unlikely(!tsk_peer_msg(tsk, hdr)))
1611                         return false;
1612
1613                 if (unlikely(msg_errcode(hdr))) {
1614                         tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1615                         /* Let timer expire on it's own */
1616                         tipc_node_remove_conn(net, tsk_peer_node(tsk),
1617                                               tsk->portid);
1618                         sk->sk_state_change(sk);
1619                 }
1620                 return true;
1621         default:
1622                 pr_err("Unknown sk_state %u\n", sk->sk_state);
1623         }
1624
1625         return false;
1626 }
1627
1628 /**
1629  * rcvbuf_limit - get proper overload limit of socket receive queue
1630  * @sk: socket
1631  * @skb: message
1632  *
1633  * For connection oriented messages, irrespective of importance,
1634  * default queue limit is 2 MB.
1635  *
1636  * For connectionless messages, queue limits are based on message
1637  * importance as follows:
1638  *
1639  * TIPC_LOW_IMPORTANCE       (2 MB)
1640  * TIPC_MEDIUM_IMPORTANCE    (4 MB)
1641  * TIPC_HIGH_IMPORTANCE      (8 MB)
1642  * TIPC_CRITICAL_IMPORTANCE  (16 MB)
1643  *
1644  * Returns overload limit according to corresponding message importance
1645  */
1646 static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *skb)
1647 {
1648         struct tipc_sock *tsk = tipc_sk(sk);
1649         struct tipc_msg *hdr = buf_msg(skb);
1650
1651         if (unlikely(!msg_connected(hdr)))
1652                 return sk->sk_rcvbuf << msg_importance(hdr);
1653
1654         if (likely(tsk->peer_caps & TIPC_BLOCK_FLOWCTL))
1655                 return sk->sk_rcvbuf;
1656
1657         return FLOWCTL_MSG_LIM;
1658 }
1659
1660 /**
1661  * filter_rcv - validate incoming message
1662  * @sk: socket
1663  * @skb: pointer to message.
1664  *
1665  * Enqueues message on receive queue if acceptable; optionally handles
1666  * disconnect indication for a connected socket.
1667  *
1668  * Called with socket lock already taken
1669  *
1670  * Returns true if message was added to socket receive queue, otherwise false
1671  */
1672 static bool filter_rcv(struct sock *sk, struct sk_buff *skb,
1673                        struct sk_buff_head *xmitq)
1674 {
1675         struct tipc_sock *tsk = tipc_sk(sk);
1676         struct tipc_msg *hdr = buf_msg(skb);
1677         unsigned int limit = rcvbuf_limit(sk, skb);
1678         int err = TIPC_OK;
1679         int usr = msg_user(hdr);
1680         u32 onode;
1681
1682         if (unlikely(msg_user(hdr) == CONN_MANAGER)) {
1683                 tipc_sk_proto_rcv(tsk, skb, xmitq);
1684                 return false;
1685         }
1686
1687         if (unlikely(usr == SOCK_WAKEUP)) {
1688                 onode = msg_orignode(hdr);
1689                 kfree_skb(skb);
1690                 u32_del(&tsk->cong_links, onode);
1691                 tsk->cong_link_cnt--;
1692                 sk->sk_write_space(sk);
1693                 return false;
1694         }
1695
1696         /* Drop if illegal message type */
1697         if (unlikely(msg_type(hdr) > TIPC_DIRECT_MSG)) {
1698                 kfree_skb(skb);
1699                 return false;
1700         }
1701
1702         /* Reject if wrong message type for current socket state */
1703         if (tipc_sk_type_connectionless(sk)) {
1704                 if (msg_connected(hdr)) {
1705                         err = TIPC_ERR_NO_PORT;
1706                         goto reject;
1707                 }
1708         } else if (unlikely(!filter_connect(tsk, skb))) {
1709                 err = TIPC_ERR_NO_PORT;
1710                 goto reject;
1711         }
1712
1713         /* Reject message if there isn't room to queue it */
1714         if (unlikely(sk_rmem_alloc_get(sk) + skb->truesize >= limit)) {
1715                 err = TIPC_ERR_OVERLOAD;
1716                 goto reject;
1717         }
1718
1719         /* Enqueue message */
1720         TIPC_SKB_CB(skb)->bytes_read = 0;
1721         __skb_queue_tail(&sk->sk_receive_queue, skb);
1722         skb_set_owner_r(skb, sk);
1723
1724         sk->sk_data_ready(sk);
1725         return true;
1726
1727 reject:
1728         if (tipc_msg_reverse(tsk_own_node(tsk), &skb, err))
1729                 __skb_queue_tail(xmitq, skb);
1730         return false;
1731 }
1732
1733 /**
1734  * tipc_backlog_rcv - handle incoming message from backlog queue
1735  * @sk: socket
1736  * @skb: message
1737  *
1738  * Caller must hold socket lock
1739  *
1740  * Returns 0
1741  */
1742 static int tipc_backlog_rcv(struct sock *sk, struct sk_buff *skb)
1743 {
1744         unsigned int truesize = skb->truesize;
1745         struct sk_buff_head xmitq;
1746         u32 dnode, selector;
1747
1748         __skb_queue_head_init(&xmitq);
1749
1750         if (likely(filter_rcv(sk, skb, &xmitq))) {
1751                 atomic_add(truesize, &tipc_sk(sk)->dupl_rcvcnt);
1752                 return 0;
1753         }
1754
1755         if (skb_queue_empty(&xmitq))
1756                 return 0;
1757
1758         /* Send response/rejected message */
1759         skb = __skb_dequeue(&xmitq);
1760         dnode = msg_destnode(buf_msg(skb));
1761         selector = msg_origport(buf_msg(skb));
1762         tipc_node_xmit_skb(sock_net(sk), skb, dnode, selector);
1763         return 0;
1764 }
1765
1766 /**
1767  * tipc_sk_enqueue - extract all buffers with destination 'dport' from
1768  *                   inputq and try adding them to socket or backlog queue
1769  * @inputq: list of incoming buffers with potentially different destinations
1770  * @sk: socket where the buffers should be enqueued
1771  * @dport: port number for the socket
1772  *
1773  * Caller must hold socket lock
1774  */
1775 static void tipc_sk_enqueue(struct sk_buff_head *inputq, struct sock *sk,
1776                             u32 dport, struct sk_buff_head *xmitq)
1777 {
1778         unsigned long time_limit = jiffies + usecs_to_jiffies(20000);
1779         struct sk_buff *skb;
1780         unsigned int lim;
1781         atomic_t *dcnt;
1782         u32 onode;
1783
1784         while (skb_queue_len(inputq)) {
1785                 if (unlikely(time_after_eq(jiffies, time_limit)))
1786                         return;
1787
1788                 skb = tipc_skb_dequeue(inputq, dport);
1789                 if (unlikely(!skb))
1790                         return;
1791
1792                 /* Add message directly to receive queue if possible */
1793                 if (!sock_owned_by_user(sk)) {
1794                         filter_rcv(sk, skb, xmitq);
1795                         continue;
1796                 }
1797
1798                 /* Try backlog, compensating for double-counted bytes */
1799                 dcnt = &tipc_sk(sk)->dupl_rcvcnt;
1800                 if (!sk->sk_backlog.len)
1801                         atomic_set(dcnt, 0);
1802                 lim = rcvbuf_limit(sk, skb) + atomic_read(dcnt);
1803                 if (likely(!sk_add_backlog(sk, skb, lim)))
1804                         continue;
1805
1806                 /* Overload => reject message back to sender */
1807                 onode = tipc_own_addr(sock_net(sk));
1808                 if (tipc_msg_reverse(onode, &skb, TIPC_ERR_OVERLOAD))
1809                         __skb_queue_tail(xmitq, skb);
1810                 break;
1811         }
1812 }
1813
1814 /**
1815  * tipc_sk_rcv - handle a chain of incoming buffers
1816  * @inputq: buffer list containing the buffers
1817  * Consumes all buffers in list until inputq is empty
1818  * Note: may be called in multiple threads referring to the same queue
1819  */
1820 void tipc_sk_rcv(struct net *net, struct sk_buff_head *inputq)
1821 {
1822         struct sk_buff_head xmitq;
1823         u32 dnode, dport = 0;
1824         int err;
1825         struct tipc_sock *tsk;
1826         struct sock *sk;
1827         struct sk_buff *skb;
1828
1829         __skb_queue_head_init(&xmitq);
1830         while (skb_queue_len(inputq)) {
1831                 dport = tipc_skb_peek_port(inputq, dport);
1832                 tsk = tipc_sk_lookup(net, dport);
1833
1834                 if (likely(tsk)) {
1835                         sk = &tsk->sk;
1836                         if (likely(spin_trylock_bh(&sk->sk_lock.slock))) {
1837                                 tipc_sk_enqueue(inputq, sk, dport, &xmitq);
1838                                 spin_unlock_bh(&sk->sk_lock.slock);
1839                         }
1840                         /* Send pending response/rejected messages, if any */
1841                         while ((skb = __skb_dequeue(&xmitq))) {
1842                                 dnode = msg_destnode(buf_msg(skb));
1843                                 tipc_node_xmit_skb(net, skb, dnode, dport);
1844                         }
1845                         sock_put(sk);
1846                         continue;
1847                 }
1848
1849                 /* No destination socket => dequeue skb if still there */
1850                 skb = tipc_skb_dequeue(inputq, dport);
1851                 if (!skb)
1852                         return;
1853
1854                 /* Try secondary lookup if unresolved named message */
1855                 err = TIPC_ERR_NO_PORT;
1856                 if (tipc_msg_lookup_dest(net, skb, &err))
1857                         goto xmit;
1858
1859                 /* Prepare for message rejection */
1860                 if (!tipc_msg_reverse(tipc_own_addr(net), &skb, err))
1861                         continue;
1862 xmit:
1863                 dnode = msg_destnode(buf_msg(skb));
1864                 tipc_node_xmit_skb(net, skb, dnode, dport);
1865         }
1866 }
1867
1868 static int tipc_wait_for_connect(struct socket *sock, long *timeo_p)
1869 {
1870         DEFINE_WAIT_FUNC(wait, woken_wake_function);
1871         struct sock *sk = sock->sk;
1872         int done;
1873
1874         do {
1875                 int err = sock_error(sk);
1876                 if (err)
1877                         return err;
1878                 if (!*timeo_p)
1879                         return -ETIMEDOUT;
1880                 if (signal_pending(current))
1881                         return sock_intr_errno(*timeo_p);
1882
1883                 add_wait_queue(sk_sleep(sk), &wait);
1884                 done = sk_wait_event(sk, timeo_p,
1885                                      sk->sk_state != TIPC_CONNECTING, &wait);
1886                 remove_wait_queue(sk_sleep(sk), &wait);
1887         } while (!done);
1888         return 0;
1889 }
1890
1891 /**
1892  * tipc_connect - establish a connection to another TIPC port
1893  * @sock: socket structure
1894  * @dest: socket address for destination port
1895  * @destlen: size of socket address data structure
1896  * @flags: file-related flags associated with socket
1897  *
1898  * Returns 0 on success, errno otherwise
1899  */
1900 static int tipc_connect(struct socket *sock, struct sockaddr *dest,
1901                         int destlen, int flags)
1902 {
1903         struct sock *sk = sock->sk;
1904         struct tipc_sock *tsk = tipc_sk(sk);
1905         struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1906         struct msghdr m = {NULL,};
1907         long timeout = (flags & O_NONBLOCK) ? 0 : tsk->conn_timeout;
1908         int previous;
1909         int res = 0;
1910
1911         lock_sock(sk);
1912
1913         /* DGRAM/RDM connect(), just save the destaddr */
1914         if (tipc_sk_type_connectionless(sk)) {
1915                 if (dst->family == AF_UNSPEC) {
1916                         memset(&tsk->peer, 0, sizeof(struct sockaddr_tipc));
1917                 } else if (destlen != sizeof(struct sockaddr_tipc)) {
1918                         res = -EINVAL;
1919                 } else {
1920                         memcpy(&tsk->peer, dest, destlen);
1921                 }
1922                 goto exit;
1923         }
1924
1925         /*
1926          * Reject connection attempt using multicast address
1927          *
1928          * Note: send_msg() validates the rest of the address fields,
1929          *       so there's no need to do it here
1930          */
1931         if (dst->addrtype == TIPC_ADDR_MCAST) {
1932                 res = -EINVAL;
1933                 goto exit;
1934         }
1935
1936         previous = sk->sk_state;
1937
1938         switch (sk->sk_state) {
1939         case TIPC_OPEN:
1940                 /* Send a 'SYN-' to destination */
1941                 m.msg_name = dest;
1942                 m.msg_namelen = destlen;
1943
1944                 /* If connect is in non-blocking case, set MSG_DONTWAIT to
1945                  * indicate send_msg() is never blocked.
1946                  */
1947                 if (!timeout)
1948                         m.msg_flags = MSG_DONTWAIT;
1949
1950                 res = __tipc_sendmsg(sock, &m, 0);
1951                 if ((res < 0) && (res != -EWOULDBLOCK))
1952                         goto exit;
1953
1954                 /* Just entered TIPC_CONNECTING state; the only
1955                  * difference is that return value in non-blocking
1956                  * case is EINPROGRESS, rather than EALREADY.
1957                  */
1958                 res = -EINPROGRESS;
1959                 /* fall thru' */
1960         case TIPC_CONNECTING:
1961                 if (!timeout) {
1962                         if (previous == TIPC_CONNECTING)
1963                                 res = -EALREADY;
1964                         goto exit;
1965                 }
1966                 timeout = msecs_to_jiffies(timeout);
1967                 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1968                 res = tipc_wait_for_connect(sock, &timeout);
1969                 break;
1970         case TIPC_ESTABLISHED:
1971                 res = -EISCONN;
1972                 break;
1973         default:
1974                 res = -EINVAL;
1975         }
1976
1977 exit:
1978         release_sock(sk);
1979         return res;
1980 }
1981
1982 /**
1983  * tipc_listen - allow socket to listen for incoming connections
1984  * @sock: socket structure
1985  * @len: (unused)
1986  *
1987  * Returns 0 on success, errno otherwise
1988  */
1989 static int tipc_listen(struct socket *sock, int len)
1990 {
1991         struct sock *sk = sock->sk;
1992         int res;
1993
1994         lock_sock(sk);
1995         res = tipc_set_sk_state(sk, TIPC_LISTEN);
1996         release_sock(sk);
1997
1998         return res;
1999 }
2000
2001 static int tipc_wait_for_accept(struct socket *sock, long timeo)
2002 {
2003         struct sock *sk = sock->sk;
2004         DEFINE_WAIT_FUNC(wait, woken_wake_function);
2005         int err;
2006
2007         /* True wake-one mechanism for incoming connections: only
2008          * one process gets woken up, not the 'whole herd'.
2009          * Since we do not 'race & poll' for established sockets
2010          * anymore, the common case will execute the loop only once.
2011         */
2012         for (;;) {
2013                 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
2014                         add_wait_queue(sk_sleep(sk), &wait);
2015                         release_sock(sk);
2016                         timeo = wait_woken(&wait, TASK_INTERRUPTIBLE, timeo);
2017                         lock_sock(sk);
2018                         remove_wait_queue(sk_sleep(sk), &wait);
2019                 }
2020                 err = 0;
2021                 if (!skb_queue_empty(&sk->sk_receive_queue))
2022                         break;
2023                 err = -EAGAIN;
2024                 if (!timeo)
2025                         break;
2026                 err = sock_intr_errno(timeo);
2027                 if (signal_pending(current))
2028                         break;
2029         }
2030         return err;
2031 }
2032
2033 /**
2034  * tipc_accept - wait for connection request
2035  * @sock: listening socket
2036  * @newsock: new socket that is to be connected
2037  * @flags: file-related flags associated with socket
2038  *
2039  * Returns 0 on success, errno otherwise
2040  */
2041 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags,
2042                        bool kern)
2043 {
2044         struct sock *new_sk, *sk = sock->sk;
2045         struct sk_buff *buf;
2046         struct tipc_sock *new_tsock;
2047         struct tipc_msg *msg;
2048         long timeo;
2049         int res;
2050
2051         lock_sock(sk);
2052
2053         if (sk->sk_state != TIPC_LISTEN) {
2054                 res = -EINVAL;
2055                 goto exit;
2056         }
2057         timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
2058         res = tipc_wait_for_accept(sock, timeo);
2059         if (res)
2060                 goto exit;
2061
2062         buf = skb_peek(&sk->sk_receive_queue);
2063
2064         res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, kern);
2065         if (res)
2066                 goto exit;
2067         security_sk_clone(sock->sk, new_sock->sk);
2068
2069         new_sk = new_sock->sk;
2070         new_tsock = tipc_sk(new_sk);
2071         msg = buf_msg(buf);
2072
2073         /* we lock on new_sk; but lockdep sees the lock on sk */
2074         lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
2075
2076         /*
2077          * Reject any stray messages received by new socket
2078          * before the socket lock was taken (very, very unlikely)
2079          */
2080         tsk_rej_rx_queue(new_sk);
2081
2082         /* Connect new socket to it's peer */
2083         tipc_sk_finish_conn(new_tsock, msg_origport(msg), msg_orignode(msg));
2084
2085         tsk_set_importance(new_tsock, msg_importance(msg));
2086         if (msg_named(msg)) {
2087                 new_tsock->conn_type = msg_nametype(msg);
2088                 new_tsock->conn_instance = msg_nameinst(msg);
2089         }
2090
2091         /*
2092          * Respond to 'SYN-' by discarding it & returning 'ACK'-.
2093          * Respond to 'SYN+' by queuing it on new socket.
2094          */
2095         if (!msg_data_sz(msg)) {
2096                 struct msghdr m = {NULL,};
2097
2098                 tsk_advance_rx_queue(sk);
2099                 __tipc_sendstream(new_sock, &m, 0);
2100         } else {
2101                 __skb_dequeue(&sk->sk_receive_queue);
2102                 __skb_queue_head(&new_sk->sk_receive_queue, buf);
2103                 skb_set_owner_r(buf, new_sk);
2104         }
2105         release_sock(new_sk);
2106 exit:
2107         release_sock(sk);
2108         return res;
2109 }
2110
2111 /**
2112  * tipc_shutdown - shutdown socket connection
2113  * @sock: socket structure
2114  * @how: direction to close (must be SHUT_RDWR)
2115  *
2116  * Terminates connection (if necessary), then purges socket's receive queue.
2117  *
2118  * Returns 0 on success, errno otherwise
2119  */
2120 static int tipc_shutdown(struct socket *sock, int how)
2121 {
2122         struct sock *sk = sock->sk;
2123         int res;
2124
2125         if (how != SHUT_RDWR)
2126                 return -EINVAL;
2127
2128         lock_sock(sk);
2129
2130         __tipc_shutdown(sock, TIPC_CONN_SHUTDOWN);
2131         sk->sk_shutdown = SHUTDOWN_MASK;
2132
2133         if (sk->sk_state == TIPC_DISCONNECTING) {
2134                 /* Discard any unreceived messages */
2135                 __skb_queue_purge(&sk->sk_receive_queue);
2136
2137                 res = 0;
2138         } else {
2139                 res = -ENOTCONN;
2140         }
2141         /* Wake up anyone sleeping in poll. */
2142         sk->sk_state_change(sk);
2143
2144         release_sock(sk);
2145         return res;
2146 }
2147
2148 static void tipc_sk_timeout(unsigned long data)
2149 {
2150         struct tipc_sock *tsk = (struct tipc_sock *)data;
2151         struct sock *sk = &tsk->sk;
2152         struct sk_buff *skb = NULL;
2153         u32 peer_port, peer_node;
2154         u32 own_node = tsk_own_node(tsk);
2155
2156         bh_lock_sock(sk);
2157         if (!tipc_sk_connected(sk)) {
2158                 bh_unlock_sock(sk);
2159                 goto exit;
2160         }
2161         peer_port = tsk_peer_port(tsk);
2162         peer_node = tsk_peer_node(tsk);
2163
2164         if (tsk->probe_unacked) {
2165                 if (!sock_owned_by_user(sk)) {
2166                         tipc_set_sk_state(sk, TIPC_DISCONNECTING);
2167                         tipc_node_remove_conn(sock_net(sk), tsk_peer_node(tsk),
2168                                               tsk_peer_port(tsk));
2169                         sk->sk_state_change(sk);
2170                 } else {
2171                         /* Try again later */
2172                         sk_reset_timer(sk, &sk->sk_timer, (HZ / 20));
2173                 }
2174
2175                 bh_unlock_sock(sk);
2176                 goto exit;
2177         }
2178
2179         skb = tipc_msg_create(CONN_MANAGER, CONN_PROBE,
2180                               INT_H_SIZE, 0, peer_node, own_node,
2181                               peer_port, tsk->portid, TIPC_OK);
2182         tsk->probe_unacked = true;
2183         sk_reset_timer(sk, &sk->sk_timer, jiffies + CONN_PROBING_INTERVAL);
2184         bh_unlock_sock(sk);
2185         if (skb)
2186                 tipc_node_xmit_skb(sock_net(sk), skb, peer_node, tsk->portid);
2187 exit:
2188         sock_put(sk);
2189 }
2190
2191 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
2192                            struct tipc_name_seq const *seq)
2193 {
2194         struct sock *sk = &tsk->sk;
2195         struct net *net = sock_net(sk);
2196         struct publication *publ;
2197         u32 key;
2198
2199         if (tipc_sk_connected(sk))
2200                 return -EINVAL;
2201         key = tsk->portid + tsk->pub_count + 1;
2202         if (key == tsk->portid)
2203                 return -EADDRINUSE;
2204
2205         publ = tipc_nametbl_publish(net, seq->type, seq->lower, seq->upper,
2206                                     scope, tsk->portid, key);
2207         if (unlikely(!publ))
2208                 return -EINVAL;
2209
2210         list_add(&publ->pport_list, &tsk->publications);
2211         tsk->pub_count++;
2212         tsk->published = 1;
2213         return 0;
2214 }
2215
2216 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
2217                             struct tipc_name_seq const *seq)
2218 {
2219         struct net *net = sock_net(&tsk->sk);
2220         struct publication *publ;
2221         struct publication *safe;
2222         int rc = -EINVAL;
2223
2224         list_for_each_entry_safe(publ, safe, &tsk->publications, pport_list) {
2225                 if (seq) {
2226                         if (publ->scope != scope)
2227                                 continue;
2228                         if (publ->type != seq->type)
2229                                 continue;
2230                         if (publ->lower != seq->lower)
2231                                 continue;
2232                         if (publ->upper != seq->upper)
2233                                 break;
2234                         tipc_nametbl_withdraw(net, publ->type, publ->lower,
2235                                               publ->ref, publ->key);
2236                         rc = 0;
2237                         break;
2238                 }
2239                 tipc_nametbl_withdraw(net, publ->type, publ->lower,
2240                                       publ->ref, publ->key);
2241                 rc = 0;
2242         }
2243         if (list_empty(&tsk->publications))
2244                 tsk->published = 0;
2245         return rc;
2246 }
2247
2248 /* tipc_sk_reinit: set non-zero address in all existing sockets
2249  *                 when we go from standalone to network mode.
2250  */
2251 void tipc_sk_reinit(struct net *net)
2252 {
2253         struct tipc_net *tn = net_generic(net, tipc_net_id);
2254         struct rhashtable_iter iter;
2255         struct tipc_sock *tsk;
2256         struct tipc_msg *msg;
2257
2258         rhashtable_walk_enter(&tn->sk_rht, &iter);
2259
2260         do {
2261                 tsk = ERR_PTR(rhashtable_walk_start(&iter));
2262                 if (IS_ERR(tsk))
2263                         goto walk_stop;
2264
2265                 while ((tsk = rhashtable_walk_next(&iter)) && !IS_ERR(tsk)) {
2266                         sock_hold(&tsk->sk);
2267                         rhashtable_walk_stop(&iter);
2268                         lock_sock(&tsk->sk);
2269                         msg = &tsk->phdr;
2270                         msg_set_prevnode(msg, tn->own_addr);
2271                         msg_set_orignode(msg, tn->own_addr);
2272                         release_sock(&tsk->sk);
2273                         rhashtable_walk_start(&iter);
2274                         sock_put(&tsk->sk);
2275                 }
2276 walk_stop:
2277                 rhashtable_walk_stop(&iter);
2278         } while (tsk == ERR_PTR(-EAGAIN));
2279
2280         rhashtable_walk_exit(&iter);
2281 }
2282
2283 static struct tipc_sock *tipc_sk_lookup(struct net *net, u32 portid)
2284 {
2285         struct tipc_net *tn = net_generic(net, tipc_net_id);
2286         struct tipc_sock *tsk;
2287
2288         rcu_read_lock();
2289         tsk = rhashtable_lookup_fast(&tn->sk_rht, &portid, tsk_rht_params);
2290         if (tsk)
2291                 sock_hold(&tsk->sk);
2292         rcu_read_unlock();
2293
2294         return tsk;
2295 }
2296
2297 static int tipc_sk_insert(struct tipc_sock *tsk)
2298 {
2299         struct sock *sk = &tsk->sk;
2300         struct net *net = sock_net(sk);
2301         struct tipc_net *tn = net_generic(net, tipc_net_id);
2302         u32 remaining = (TIPC_MAX_PORT - TIPC_MIN_PORT) + 1;
2303         u32 portid = prandom_u32() % remaining + TIPC_MIN_PORT;
2304
2305         while (remaining--) {
2306                 portid++;
2307                 if ((portid < TIPC_MIN_PORT) || (portid > TIPC_MAX_PORT))
2308                         portid = TIPC_MIN_PORT;
2309                 tsk->portid = portid;
2310                 sock_hold(&tsk->sk);
2311                 if (!rhashtable_lookup_insert_fast(&tn->sk_rht, &tsk->node,
2312                                                    tsk_rht_params))
2313                         return 0;
2314                 sock_put(&tsk->sk);
2315         }
2316
2317         return -1;
2318 }
2319
2320 static void tipc_sk_remove(struct tipc_sock *tsk)
2321 {
2322         struct sock *sk = &tsk->sk;
2323         struct tipc_net *tn = net_generic(sock_net(sk), tipc_net_id);
2324
2325         if (!rhashtable_remove_fast(&tn->sk_rht, &tsk->node, tsk_rht_params)) {
2326                 WARN_ON(refcount_read(&sk->sk_refcnt) == 1);
2327                 __sock_put(sk);
2328         }
2329 }
2330
2331 static const struct rhashtable_params tsk_rht_params = {
2332         .nelem_hint = 192,
2333         .head_offset = offsetof(struct tipc_sock, node),
2334         .key_offset = offsetof(struct tipc_sock, portid),
2335         .key_len = sizeof(u32), /* portid */
2336         .max_size = 1048576,
2337         .min_size = 256,
2338         .automatic_shrinking = true,
2339 };
2340
2341 int tipc_sk_rht_init(struct net *net)
2342 {
2343         struct tipc_net *tn = net_generic(net, tipc_net_id);
2344
2345         return rhashtable_init(&tn->sk_rht, &tsk_rht_params);
2346 }
2347
2348 void tipc_sk_rht_destroy(struct net *net)
2349 {
2350         struct tipc_net *tn = net_generic(net, tipc_net_id);
2351
2352         /* Wait for socket readers to complete */
2353         synchronize_net();
2354
2355         rhashtable_destroy(&tn->sk_rht);
2356 }
2357
2358 /**
2359  * tipc_setsockopt - set socket option
2360  * @sock: socket structure
2361  * @lvl: option level
2362  * @opt: option identifier
2363  * @ov: pointer to new option value
2364  * @ol: length of option value
2365  *
2366  * For stream sockets only, accepts and ignores all IPPROTO_TCP options
2367  * (to ease compatibility).
2368  *
2369  * Returns 0 on success, errno otherwise
2370  */
2371 static int tipc_setsockopt(struct socket *sock, int lvl, int opt,
2372                            char __user *ov, unsigned int ol)
2373 {
2374         struct sock *sk = sock->sk;
2375         struct tipc_sock *tsk = tipc_sk(sk);
2376         u32 value = 0;
2377         int res = 0;
2378
2379         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2380                 return 0;
2381         if (lvl != SOL_TIPC)
2382                 return -ENOPROTOOPT;
2383
2384         switch (opt) {
2385         case TIPC_IMPORTANCE:
2386         case TIPC_SRC_DROPPABLE:
2387         case TIPC_DEST_DROPPABLE:
2388         case TIPC_CONN_TIMEOUT:
2389                 if (ol < sizeof(value))
2390                         return -EINVAL;
2391                 res = get_user(value, (u32 __user *)ov);
2392                 if (res)
2393                         return res;
2394                 break;
2395         default:
2396                 if (ov || ol)
2397                         return -EINVAL;
2398         }
2399
2400         lock_sock(sk);
2401
2402         switch (opt) {
2403         case TIPC_IMPORTANCE:
2404                 res = tsk_set_importance(tsk, value);
2405                 break;
2406         case TIPC_SRC_DROPPABLE:
2407                 if (sock->type != SOCK_STREAM)
2408                         tsk_set_unreliable(tsk, value);
2409                 else
2410                         res = -ENOPROTOOPT;
2411                 break;
2412         case TIPC_DEST_DROPPABLE:
2413                 tsk_set_unreturnable(tsk, value);
2414                 break;
2415         case TIPC_CONN_TIMEOUT:
2416                 tipc_sk(sk)->conn_timeout = value;
2417                 break;
2418         case TIPC_MCAST_BROADCAST:
2419                 tsk->mc_method.rcast = false;
2420                 tsk->mc_method.mandatory = true;
2421                 break;
2422         case TIPC_MCAST_REPLICAST:
2423                 tsk->mc_method.rcast = true;
2424                 tsk->mc_method.mandatory = true;
2425                 break;
2426         default:
2427                 res = -EINVAL;
2428         }
2429
2430         release_sock(sk);
2431
2432         return res;
2433 }
2434
2435 /**
2436  * tipc_getsockopt - get socket option
2437  * @sock: socket structure
2438  * @lvl: option level
2439  * @opt: option identifier
2440  * @ov: receptacle for option value
2441  * @ol: receptacle for length of option value
2442  *
2443  * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
2444  * (to ease compatibility).
2445  *
2446  * Returns 0 on success, errno otherwise
2447  */
2448 static int tipc_getsockopt(struct socket *sock, int lvl, int opt,
2449                            char __user *ov, int __user *ol)
2450 {
2451         struct sock *sk = sock->sk;
2452         struct tipc_sock *tsk = tipc_sk(sk);
2453         int len;
2454         u32 value;
2455         int res;
2456
2457         if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2458                 return put_user(0, ol);
2459         if (lvl != SOL_TIPC)
2460                 return -ENOPROTOOPT;
2461         res = get_user(len, ol);
2462         if (res)
2463                 return res;
2464
2465         lock_sock(sk);
2466
2467         switch (opt) {
2468         case TIPC_IMPORTANCE:
2469                 value = tsk_importance(tsk);
2470                 break;
2471         case TIPC_SRC_DROPPABLE:
2472                 value = tsk_unreliable(tsk);
2473                 break;
2474         case TIPC_DEST_DROPPABLE:
2475                 value = tsk_unreturnable(tsk);
2476                 break;
2477         case TIPC_CONN_TIMEOUT:
2478                 value = tsk->conn_timeout;
2479                 /* no need to set "res", since already 0 at this point */
2480                 break;
2481         case TIPC_NODE_RECVQ_DEPTH:
2482                 value = 0; /* was tipc_queue_size, now obsolete */
2483                 break;
2484         case TIPC_SOCK_RECVQ_DEPTH:
2485                 value = skb_queue_len(&sk->sk_receive_queue);
2486                 break;
2487         default:
2488                 res = -EINVAL;
2489         }
2490
2491         release_sock(sk);
2492
2493         if (res)
2494                 return res;     /* "get" failed */
2495
2496         if (len < sizeof(value))
2497                 return -EINVAL;
2498
2499         if (copy_to_user(ov, &value, sizeof(value)))
2500                 return -EFAULT;
2501
2502         return put_user(sizeof(value), ol);
2503 }
2504
2505 static int tipc_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
2506 {
2507         struct sock *sk = sock->sk;
2508         struct tipc_sioc_ln_req lnr;
2509         void __user *argp = (void __user *)arg;
2510
2511         switch (cmd) {
2512         case SIOCGETLINKNAME:
2513                 if (copy_from_user(&lnr, argp, sizeof(lnr)))
2514                         return -EFAULT;
2515                 if (!tipc_node_get_linkname(sock_net(sk),
2516                                             lnr.bearer_id & 0xffff, lnr.peer,
2517                                             lnr.linkname, TIPC_MAX_LINK_NAME)) {
2518                         if (copy_to_user(argp, &lnr, sizeof(lnr)))
2519                                 return -EFAULT;
2520                         return 0;
2521                 }
2522                 return -EADDRNOTAVAIL;
2523         default:
2524                 return -ENOIOCTLCMD;
2525         }
2526 }
2527
2528 static int tipc_socketpair(struct socket *sock1, struct socket *sock2)
2529 {
2530         struct tipc_sock *tsk2 = tipc_sk(sock2->sk);
2531         struct tipc_sock *tsk1 = tipc_sk(sock1->sk);
2532         u32 onode = tipc_own_addr(sock_net(sock1->sk));
2533
2534         tsk1->peer.family = AF_TIPC;
2535         tsk1->peer.addrtype = TIPC_ADDR_ID;
2536         tsk1->peer.scope = TIPC_NODE_SCOPE;
2537         tsk1->peer.addr.id.ref = tsk2->portid;
2538         tsk1->peer.addr.id.node = onode;
2539         tsk2->peer.family = AF_TIPC;
2540         tsk2->peer.addrtype = TIPC_ADDR_ID;
2541         tsk2->peer.scope = TIPC_NODE_SCOPE;
2542         tsk2->peer.addr.id.ref = tsk1->portid;
2543         tsk2->peer.addr.id.node = onode;
2544
2545         tipc_sk_finish_conn(tsk1, tsk2->portid, onode);
2546         tipc_sk_finish_conn(tsk2, tsk1->portid, onode);
2547         return 0;
2548 }
2549
2550 /* Protocol switches for the various types of TIPC sockets */
2551
2552 static const struct proto_ops msg_ops = {
2553         .owner          = THIS_MODULE,
2554         .family         = AF_TIPC,
2555         .release        = tipc_release,
2556         .bind           = tipc_bind,
2557         .connect        = tipc_connect,
2558         .socketpair     = tipc_socketpair,
2559         .accept         = sock_no_accept,
2560         .getname        = tipc_getname,
2561         .poll           = tipc_poll,
2562         .ioctl          = tipc_ioctl,
2563         .listen         = sock_no_listen,
2564         .shutdown       = tipc_shutdown,
2565         .setsockopt     = tipc_setsockopt,
2566         .getsockopt     = tipc_getsockopt,
2567         .sendmsg        = tipc_sendmsg,
2568         .recvmsg        = tipc_recvmsg,
2569         .mmap           = sock_no_mmap,
2570         .sendpage       = sock_no_sendpage
2571 };
2572
2573 static const struct proto_ops packet_ops = {
2574         .owner          = THIS_MODULE,
2575         .family         = AF_TIPC,
2576         .release        = tipc_release,
2577         .bind           = tipc_bind,
2578         .connect        = tipc_connect,
2579         .socketpair     = tipc_socketpair,
2580         .accept         = tipc_accept,
2581         .getname        = tipc_getname,
2582         .poll           = tipc_poll,
2583         .ioctl          = tipc_ioctl,
2584         .listen         = tipc_listen,
2585         .shutdown       = tipc_shutdown,
2586         .setsockopt     = tipc_setsockopt,
2587         .getsockopt     = tipc_getsockopt,
2588         .sendmsg        = tipc_send_packet,
2589         .recvmsg        = tipc_recvmsg,
2590         .mmap           = sock_no_mmap,
2591         .sendpage       = sock_no_sendpage
2592 };
2593
2594 static const struct proto_ops stream_ops = {
2595         .owner          = THIS_MODULE,
2596         .family         = AF_TIPC,
2597         .release        = tipc_release,
2598         .bind           = tipc_bind,
2599         .connect        = tipc_connect,
2600         .socketpair     = tipc_socketpair,
2601         .accept         = tipc_accept,
2602         .getname        = tipc_getname,
2603         .poll           = tipc_poll,
2604         .ioctl          = tipc_ioctl,
2605         .listen         = tipc_listen,
2606         .shutdown       = tipc_shutdown,
2607         .setsockopt     = tipc_setsockopt,
2608         .getsockopt     = tipc_getsockopt,
2609         .sendmsg        = tipc_sendstream,
2610         .recvmsg        = tipc_recvstream,
2611         .mmap           = sock_no_mmap,
2612         .sendpage       = sock_no_sendpage
2613 };
2614
2615 static const struct net_proto_family tipc_family_ops = {
2616         .owner          = THIS_MODULE,
2617         .family         = AF_TIPC,
2618         .create         = tipc_sk_create
2619 };
2620
2621 static struct proto tipc_proto = {
2622         .name           = "TIPC",
2623         .owner          = THIS_MODULE,
2624         .obj_size       = sizeof(struct tipc_sock),
2625         .sysctl_rmem    = sysctl_tipc_rmem
2626 };
2627
2628 /**
2629  * tipc_socket_init - initialize TIPC socket interface
2630  *
2631  * Returns 0 on success, errno otherwise
2632  */
2633 int tipc_socket_init(void)
2634 {
2635         int res;
2636
2637         res = proto_register(&tipc_proto, 1);
2638         if (res) {
2639                 pr_err("Failed to register TIPC protocol type\n");
2640                 goto out;
2641         }
2642
2643         res = sock_register(&tipc_family_ops);
2644         if (res) {
2645                 pr_err("Failed to register TIPC socket type\n");
2646                 proto_unregister(&tipc_proto);
2647                 goto out;
2648         }
2649  out:
2650         return res;
2651 }
2652
2653 /**
2654  * tipc_socket_stop - stop TIPC socket interface
2655  */
2656 void tipc_socket_stop(void)
2657 {
2658         sock_unregister(tipc_family_ops.family);
2659         proto_unregister(&tipc_proto);
2660 }
2661
2662 /* Caller should hold socket lock for the passed tipc socket. */
2663 static int __tipc_nl_add_sk_con(struct sk_buff *skb, struct tipc_sock *tsk)
2664 {
2665         u32 peer_node;
2666         u32 peer_port;
2667         struct nlattr *nest;
2668
2669         peer_node = tsk_peer_node(tsk);
2670         peer_port = tsk_peer_port(tsk);
2671
2672         nest = nla_nest_start(skb, TIPC_NLA_SOCK_CON);
2673
2674         if (nla_put_u32(skb, TIPC_NLA_CON_NODE, peer_node))
2675                 goto msg_full;
2676         if (nla_put_u32(skb, TIPC_NLA_CON_SOCK, peer_port))
2677                 goto msg_full;
2678
2679         if (tsk->conn_type != 0) {
2680                 if (nla_put_flag(skb, TIPC_NLA_CON_FLAG))
2681                         goto msg_full;
2682                 if (nla_put_u32(skb, TIPC_NLA_CON_TYPE, tsk->conn_type))
2683                         goto msg_full;
2684                 if (nla_put_u32(skb, TIPC_NLA_CON_INST, tsk->conn_instance))
2685                         goto msg_full;
2686         }
2687         nla_nest_end(skb, nest);
2688
2689         return 0;
2690
2691 msg_full:
2692         nla_nest_cancel(skb, nest);
2693
2694         return -EMSGSIZE;
2695 }
2696
2697 /* Caller should hold socket lock for the passed tipc socket. */
2698 static int __tipc_nl_add_sk(struct sk_buff *skb, struct netlink_callback *cb,
2699                             struct tipc_sock *tsk)
2700 {
2701         int err;
2702         void *hdr;
2703         struct nlattr *attrs;
2704         struct net *net = sock_net(skb->sk);
2705         struct tipc_net *tn = net_generic(net, tipc_net_id);
2706         struct sock *sk = &tsk->sk;
2707
2708         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
2709                           &tipc_genl_family, NLM_F_MULTI, TIPC_NL_SOCK_GET);
2710         if (!hdr)
2711                 goto msg_cancel;
2712
2713         attrs = nla_nest_start(skb, TIPC_NLA_SOCK);
2714         if (!attrs)
2715                 goto genlmsg_cancel;
2716         if (nla_put_u32(skb, TIPC_NLA_SOCK_REF, tsk->portid))
2717                 goto attr_msg_cancel;
2718         if (nla_put_u32(skb, TIPC_NLA_SOCK_ADDR, tn->own_addr))
2719                 goto attr_msg_cancel;
2720
2721         if (tipc_sk_connected(sk)) {
2722                 err = __tipc_nl_add_sk_con(skb, tsk);
2723                 if (err)
2724                         goto attr_msg_cancel;
2725         } else if (!list_empty(&tsk->publications)) {
2726                 if (nla_put_flag(skb, TIPC_NLA_SOCK_HAS_PUBL))
2727                         goto attr_msg_cancel;
2728         }
2729         nla_nest_end(skb, attrs);
2730         genlmsg_end(skb, hdr);
2731
2732         return 0;
2733
2734 attr_msg_cancel:
2735         nla_nest_cancel(skb, attrs);
2736 genlmsg_cancel:
2737         genlmsg_cancel(skb, hdr);
2738 msg_cancel:
2739         return -EMSGSIZE;
2740 }
2741
2742 int tipc_nl_sk_dump(struct sk_buff *skb, struct netlink_callback *cb)
2743 {
2744         int err;
2745         struct tipc_sock *tsk;
2746         const struct bucket_table *tbl;
2747         struct rhash_head *pos;
2748         struct net *net = sock_net(skb->sk);
2749         struct tipc_net *tn = net_generic(net, tipc_net_id);
2750         u32 tbl_id = cb->args[0];
2751         u32 prev_portid = cb->args[1];
2752
2753         rcu_read_lock();
2754         tbl = rht_dereference_rcu((&tn->sk_rht)->tbl, &tn->sk_rht);
2755         for (; tbl_id < tbl->size; tbl_id++) {
2756                 rht_for_each_entry_rcu(tsk, pos, tbl, tbl_id, node) {
2757                         spin_lock_bh(&tsk->sk.sk_lock.slock);
2758                         if (prev_portid && prev_portid != tsk->portid) {
2759                                 spin_unlock_bh(&tsk->sk.sk_lock.slock);
2760                                 continue;
2761                         }
2762
2763                         err = __tipc_nl_add_sk(skb, cb, tsk);
2764                         if (err) {
2765                                 prev_portid = tsk->portid;
2766                                 spin_unlock_bh(&tsk->sk.sk_lock.slock);
2767                                 goto out;
2768                         }
2769                         prev_portid = 0;
2770                         spin_unlock_bh(&tsk->sk.sk_lock.slock);
2771                 }
2772         }
2773 out:
2774         rcu_read_unlock();
2775         cb->args[0] = tbl_id;
2776         cb->args[1] = prev_portid;
2777
2778         return skb->len;
2779 }
2780
2781 /* Caller should hold socket lock for the passed tipc socket. */
2782 static int __tipc_nl_add_sk_publ(struct sk_buff *skb,
2783                                  struct netlink_callback *cb,
2784                                  struct publication *publ)
2785 {
2786         void *hdr;
2787         struct nlattr *attrs;
2788
2789         hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
2790                           &tipc_genl_family, NLM_F_MULTI, TIPC_NL_PUBL_GET);
2791         if (!hdr)
2792                 goto msg_cancel;
2793
2794         attrs = nla_nest_start(skb, TIPC_NLA_PUBL);
2795         if (!attrs)
2796                 goto genlmsg_cancel;
2797
2798         if (nla_put_u32(skb, TIPC_NLA_PUBL_KEY, publ->key))
2799                 goto attr_msg_cancel;
2800         if (nla_put_u32(skb, TIPC_NLA_PUBL_TYPE, publ->type))
2801                 goto attr_msg_cancel;
2802         if (nla_put_u32(skb, TIPC_NLA_PUBL_LOWER, publ->lower))
2803                 goto attr_msg_cancel;
2804         if (nla_put_u32(skb, TIPC_NLA_PUBL_UPPER, publ->upper))
2805                 goto attr_msg_cancel;
2806
2807         nla_nest_end(skb, attrs);
2808         genlmsg_end(skb, hdr);
2809
2810         return 0;
2811
2812 attr_msg_cancel:
2813         nla_nest_cancel(skb, attrs);
2814 genlmsg_cancel:
2815         genlmsg_cancel(skb, hdr);
2816 msg_cancel:
2817         return -EMSGSIZE;
2818 }
2819
2820 /* Caller should hold socket lock for the passed tipc socket. */
2821 static int __tipc_nl_list_sk_publ(struct sk_buff *skb,
2822                                   struct netlink_callback *cb,
2823                                   struct tipc_sock *tsk, u32 *last_publ)
2824 {
2825         int err;
2826         struct publication *p;
2827
2828         if (*last_publ) {
2829                 list_for_each_entry(p, &tsk->publications, pport_list) {
2830                         if (p->key == *last_publ)
2831                                 break;
2832                 }
2833                 if (p->key != *last_publ) {
2834                         /* We never set seq or call nl_dump_check_consistent()
2835                          * this means that setting prev_seq here will cause the
2836                          * consistence check to fail in the netlink callback
2837                          * handler. Resulting in the last NLMSG_DONE message
2838                          * having the NLM_F_DUMP_INTR flag set.
2839                          */
2840                         cb->prev_seq = 1;
2841                         *last_publ = 0;
2842                         return -EPIPE;
2843                 }
2844         } else {
2845                 p = list_first_entry(&tsk->publications, struct publication,
2846                                      pport_list);
2847         }
2848
2849         list_for_each_entry_from(p, &tsk->publications, pport_list) {
2850                 err = __tipc_nl_add_sk_publ(skb, cb, p);
2851                 if (err) {
2852                         *last_publ = p->key;
2853                         return err;
2854                 }
2855         }
2856         *last_publ = 0;
2857
2858         return 0;
2859 }
2860
2861 int tipc_nl_publ_dump(struct sk_buff *skb, struct netlink_callback *cb)
2862 {
2863         int err;
2864         u32 tsk_portid = cb->args[0];
2865         u32 last_publ = cb->args[1];
2866         u32 done = cb->args[2];
2867         struct net *net = sock_net(skb->sk);
2868         struct tipc_sock *tsk;
2869
2870         if (!tsk_portid) {
2871                 struct nlattr **attrs;
2872                 struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1];
2873
2874                 err = tipc_nlmsg_parse(cb->nlh, &attrs);
2875                 if (err)
2876                         return err;
2877
2878                 if (!attrs[TIPC_NLA_SOCK])
2879                         return -EINVAL;
2880
2881                 err = nla_parse_nested(sock, TIPC_NLA_SOCK_MAX,
2882                                        attrs[TIPC_NLA_SOCK],
2883                                        tipc_nl_sock_policy, NULL);
2884                 if (err)
2885                         return err;
2886
2887                 if (!sock[TIPC_NLA_SOCK_REF])
2888                         return -EINVAL;
2889
2890                 tsk_portid = nla_get_u32(sock[TIPC_NLA_SOCK_REF]);
2891         }
2892
2893         if (done)
2894                 return 0;
2895
2896         tsk = tipc_sk_lookup(net, tsk_portid);
2897         if (!tsk)
2898                 return -EINVAL;
2899
2900         lock_sock(&tsk->sk);
2901         err = __tipc_nl_list_sk_publ(skb, cb, tsk, &last_publ);
2902         if (!err)
2903                 done = 1;
2904         release_sock(&tsk->sk);
2905         sock_put(&tsk->sk);
2906
2907         cb->args[0] = tsk_portid;
2908         cb->args[1] = last_publ;
2909         cb->args[2] = done;
2910
2911         return skb->len;
2912 }