libt2n: (tomj) disable recently added unit test: it won't work as is
[libt2n] / src / socket_client.cpp
1 /***************************************************************************
2  *   Copyright (C) 2006 by Gerd v. Egidy                                   *
3  *   gve@intra2net.com                                                     *
4  *                                                                         *
5  *   This library is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU Lesser General Public License version   *
7  *   2.1 as published by the Free Software Foundation.                     *
8  *                                                                         *
9  *   This library is distributed in the hope that it will be useful,       *
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
12  *   GNU Lesser General Public License for more details.                   *
13  *                                                                         *
14  *   You should have received a copy of the GNU Lesser General Public      *
15  *   License along with this program; if not, write to the                 *
16  *   Free Software Foundation, Inc.,                                       *
17  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
18  ***************************************************************************/
19
20 #include <stdio.h>
21 #include <errno.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <sys/types.h>
25 #include <sys/socket.h>
26 #include <sys/un.h>
27 #include <sys/time.h>
28 #include <arpa/inet.h>
29 #include <netinet/in.h>
30 #include <netdb.h>
31 #include <fcntl.h>
32 #include <time.h>
33 #include <pwd.h>
34 #include <grp.h>
35
36 #include <sstream>
37
38 #include "socket_client.hxx"
39 #include "t2n_exception.hxx"
40 #include "log.hxx"
41
42 using namespace std;
43
44 namespace libt2n
45 {
46
47 /// returns a closed connection if connection could not be established, call get_last_error_msg() for details
48 socket_client_connection::socket_client_connection(int _port, const std::string& _server, 
49             long long _connect_timeout_usec, int _max_retries,
50             std::ostream *_logstream, log_level_values _log_level)
51     : client_connection(), socket_handler(0,tcp_s)
52 {
53     max_retries=_max_retries;
54     connect_timeout_usec=_connect_timeout_usec;
55
56     server=_server;
57     port=_port;
58
59     set_logging(_logstream,_log_level);
60
61     try
62     {
63         tcp_connect(max_retries);
64     }
65     catch (t2n_communication_error &e)
66     {
67         lastErrorMsg=e.what();
68         LOGSTREAM(debug,"tcp connect error: " << lastErrorMsg);
69         close();
70     }
71
72     if (!connection::is_closed())
73         do_callbacks(new_connection);
74 }
75
76 /// returns a closed connection if connection could not be established, call get_last_error_msg() for details
77 socket_client_connection::socket_client_connection(const std::string& _path,
78             long long _connect_timeout_usec, int _max_retries,
79             std::ostream *_logstream, log_level_values _log_level)
80     : client_connection(), socket_handler(0,unix_s)
81 {
82     max_retries=_max_retries;
83     connect_timeout_usec=_connect_timeout_usec;
84
85     path=_path;
86
87     set_logging(_logstream,_log_level);
88
89     try
90     {
91         unix_connect(max_retries);
92     }
93     catch (t2n_communication_error &e)
94     {
95         lastErrorMsg=e.what();
96         LOGSTREAM(debug,"unix connect error: " << lastErrorMsg);
97         close();
98     }
99
100     if (!connection::is_closed())
101         do_callbacks(new_connection);
102 }
103
104 /// establish a connection via tcp
105 void socket_client_connection::tcp_connect(int max_retries)
106 {
107     struct sockaddr_in sock_addr;
108
109     sock_addr.sin_family = AF_INET;
110     sock_addr.sin_port = htons(port);
111
112     // find the target ip
113     if (inet_aton(server.c_str(),&sock_addr.sin_addr)==0)
114     {
115         struct hostent *server_hent;
116         server_hent=gethostbyname(server.c_str());
117         if (server_hent == NULL)
118             throw t2n_connect_error(string("can't find server ")+server);
119
120         memcpy(&sock_addr.sin_addr,server_hent->h_addr_list[0],sizeof(sock_addr.sin_addr));
121     }
122
123     sock = socket(PF_INET, SOCK_STREAM, 0);
124     if (!sock)
125         throw t2n_connect_error(string("socket() error: ")+strerror(errno));
126
127     try
128     {
129         connect_with_timeout((struct sockaddr *) &sock_addr,sizeof(sock_addr));
130     }
131     catch (t2n_connect_error &e)
132     {
133         // recurse if retries left
134         if (max_retries > 0)
135         {
136             LOGSTREAM(debug,"retrying connect after connect error");
137             tcp_connect(max_retries-1);
138         }
139         else
140             throw t2n_connect_error("no more retries left after connect error");
141     }
142 }
143
144 /// establish a connection via unix-socket
145 void socket_client_connection::unix_connect(int max_retries)
146 {
147     struct sockaddr_un unix_addr;
148
149     unix_addr.sun_family = AF_UNIX;
150     strcpy (unix_addr.sun_path, path.c_str());
151
152     sock = socket(PF_UNIX, SOCK_STREAM, 0);
153     if (!sock)
154         throw t2n_connect_error(string("socket() error: ")+strerror(errno));
155
156     try
157     {
158         connect_with_timeout((struct sockaddr *) &unix_addr, sizeof(unix_addr));
159     }
160     catch (t2n_connect_error &e)
161     {
162         // recurse if retries left
163         if (max_retries > 0)
164         {
165             LOGSTREAM(debug,"retrying connect after connect error");
166             unix_connect(max_retries-1);
167         }
168         else
169             throw t2n_connect_error("no more retries left after connect error");
170     }
171 }
172
173 /// execute a connect on a prepared socket (tcp or unix) respecting timeouts
174 void socket_client_connection::connect_with_timeout(struct sockaddr *sock_addr,unsigned int sockaddr_size)
175 {
176     set_socket_options(sock);
177
178    /* non-blocking mode */
179     int flflags;
180     flflags=fcntl(sock,F_GETFL,0);
181     if (flflags < 0)
182         EXCEPTIONSTREAM(error,t2n_communication_error,"fcntl error on socket: " << strerror(errno));
183
184     flflags &= (O_NONBLOCK ^ 0xFFFF);
185     if (fcntl(sock,F_SETFL,flflags) < 0)
186         EXCEPTIONSTREAM(error,t2n_communication_error,"fcntl error on socket: " << strerror(errno));
187
188
189     LOGSTREAM(debug,"connect_with_timeout()");
190     int ret=::connect(sock,sock_addr, sockaddr_size);
191
192     if (ret < 0)
193     {
194         if (errno==EINPROGRESS)
195         {
196             LOGSTREAM(debug,"connect_with_timeout(): EINPROGRESS");
197
198             /* set timeout */
199             struct timeval tval;
200             struct timeval *timeout_ptr;
201
202             if (connect_timeout_usec == -1)
203                 timeout_ptr = NULL;
204             else
205             {
206                 timeout_ptr = &tval;
207
208                 // convert timeout from long long usec to int sec + int usec
209                 tval.tv_sec = connect_timeout_usec / 1000000;
210                 tval.tv_usec = connect_timeout_usec % 1000000;
211             }
212
213             fd_set connect_socket_set;
214             FD_ZERO(&connect_socket_set);
215             FD_SET(sock,&connect_socket_set);
216
217             int ret;
218             while ((ret=select(FD_SETSIZE, NULL, &connect_socket_set, NULL, timeout_ptr)) &&
219                     ret < 0 && errno==EINTR);
220
221             if (ret < 0)
222                 throw t2n_connect_error(string("connect() error (select): ")+strerror(errno));
223
224             socklen_t sopt=sizeof(int);
225             int valopt;
226             ret=getsockopt(sock, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &sopt);
227             if (ret < 0 || valopt)
228                 throw t2n_connect_error(string("connect() error (getsockopt): ")+strerror(errno));
229         }
230         else
231             throw t2n_connect_error(string("connect() error: ")+strerror(errno));
232     }
233
234     LOGSTREAM(debug,"connect_with_timeout(): success");
235 }
236
237 void socket_client_connection::close()
238 {
239     if (!client_connection::is_closed())
240     {
241         socket_handler::close();
242         client_connection::close();
243     }
244 }
245
246 /** @brief try to reconnect the current connection with the same connection credentials (host and port or path)
247
248     @note will throw an exeption if reconnecting not possible
249 */
250 void socket_client_connection::reconnect()
251 {
252     LOGSTREAM(debug,"reconnect()");
253
254     // close the current connection if still open
255     close();
256
257     socket_type_value type=get_type();
258
259     if (type == tcp_s)
260         tcp_connect(max_retries);
261     else if (type == unix_s)
262         unix_connect(max_retries);
263
264     // connection is open now, otherwise an execption would have been thrown
265     reopen();
266
267     LOGSTREAM(debug,"reconnect() done, client_connection::is_closed() now " << client_connection::is_closed());
268 }
269
270 }