1 /**
2  * @file tcp_high.c  High-level TCP functions
3  *
4  * Copyright (C) 2010 Creytiv.com
5  */
6 #include <re_types.h>
7 #include <re_mem.h>
8 #include <re_mbuf.h>
9 #include <re_tcp.h>
10 
11 
12 /**
13  * Create and listen on a TCP Socket
14  *
15  * @param tsp   Pointer to returned TCP Socket
16  * @param local Local listen address (NULL for any)
17  * @param ch    Incoming connection handler
18  * @param arg   Handler argument
19  *
20  * @return 0 if success, otherwise errorcode
21  */
tcp_listen(struct tcp_sock ** tsp,const struct sa * local,tcp_conn_h * ch,void * arg)22 int tcp_listen(struct tcp_sock **tsp, const struct sa *local,
23 	       tcp_conn_h *ch, void *arg)
24 {
25 	struct tcp_sock *ts = NULL;
26 	int err;
27 
28 	if (!tsp)
29 		return EINVAL;
30 
31 	err = tcp_sock_alloc(&ts, local, ch, arg);
32 	if (err)
33 		goto out;
34 
35 	err = tcp_sock_bind(ts, local);
36 	if (err)
37 		goto out;
38 
39 	err = tcp_sock_listen(ts, 5);
40 	if (err)
41 		goto out;
42 
43  out:
44 	if (err)
45 		ts = mem_deref(ts);
46 	else
47 		*tsp = ts;
48 
49 	return err;
50 }
51 
52 
53 /**
54  * Make a TCP Connection to a remote peer
55  *
56  * @param tcp  Returned TCP Connection object
57  * @param peer Network address of peer
58  * @param eh   TCP Connection Established handler
59  * @param rh   TCP Connection Receive data handler
60  * @param ch   TCP Connection close handler
61  * @param arg  Handler argument
62  *
63  * @return 0 if success, otherwise errorcode
64  */
tcp_connect(struct tcp_conn ** tcp,const struct sa * peer,tcp_estab_h * eh,tcp_recv_h * rh,tcp_close_h * ch,void * arg)65 int tcp_connect(struct tcp_conn **tcp, const struct sa *peer,
66 		tcp_estab_h *eh, tcp_recv_h *rh, tcp_close_h *ch, void *arg)
67 {
68 	struct tcp_conn *tc = NULL;
69 	int err;
70 
71 	if (!tcp || !peer)
72 		return EINVAL;
73 
74 	err = tcp_conn_alloc(&tc, peer, eh,rh, ch, arg);
75 	if (err)
76 		goto out;
77 
78 	err = tcp_conn_connect(tc, peer);
79 	if (err)
80 		goto out;
81 
82  out:
83 	if (err)
84 		tc = mem_deref(tc);
85 	else
86 		*tcp = tc;
87 
88 	return err;
89 }
90 
91 
92 /**
93  * Get local network address of TCP Socket
94  *
95  * @param ts    TCP Socket
96  * @param local Returned local network address
97  *
98  * @return 0 if success, otherwise errorcode
99  */
tcp_local_get(const struct tcp_sock * ts,struct sa * local)100 int tcp_local_get(const struct tcp_sock *ts, struct sa *local)
101 {
102 	return tcp_sock_local_get(ts, local);
103 }
104