Updated license
[anna.git] / source / comm / ServerSocket.cpp
1 // ANNA - Anna is Not Nothingness Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #include <anna/core/tracing/Logger.hpp>
38 #include <anna/core/tracing/TraceMethod.hpp>
39 #include <anna/config/defines.hpp>
40 #include <anna/core/functions.hpp>
41
42 #include <anna/xml/Node.hpp>
43 #include <anna/xml/Attribute.hpp>
44
45 #include <anna/comm/ServerSocket.hpp>
46 #include <anna/comm/internal/BinderSocket.hpp>
47 #include <anna/comm/ClientSocket.hpp>
48
49 using namespace std;
50 using namespace anna;
51
52 //static
53 const Millisecond comm::ServerSocket::DefaultBindDelay(200);
54
55 comm::ServerSocket::~ServerSocket() {
56    delete a_binderSocket;
57 }
58
59 void comm::ServerSocket::prepare()
60 throw(RuntimeException) {
61    if (::listen(Socket::a_fd, a_backlog) == -1) {
62       const int xerrno(errno);
63       std::string msg(asString());
64       msg += " | listen";
65       throw RuntimeException(msg, xerrno, ANNA_FILE_LOCATION);
66    }
67 }
68
69 int comm::ServerSocket::do_bind(const struct sockaddr* s, const int len)
70 throw(RuntimeException) {
71    if (a_sharedBind == false)
72       return Socket::do_bind(s, len);
73
74    if (a_binderSocket == NULL)
75       a_binderSocket = new BinderSocket(this);
76
77    a_binderSocket->requestBind(s, len);
78    return 0;
79 }
80 /*
81  * (1) Se invoca desde [Tx], pero hay que evitar que el .create se invoque a la misma vez que algún [Tz] este invocando
82  * al ServerSocket::release porque ha cerrado la conexión.
83  */
84 comm::LocalConnection* comm::ServerSocket::accept()
85 throw(RuntimeException) {
86    LOGMETHOD(TraceMethod traceMethod(Logger::Local7, "comm::ServerSocket", "accept", ANNA_FILE_LOCATION));
87    LocalConnection* result(NULL);
88    sockaddr_in sourceAddress;
89    socklen_t len(sizeof(sockaddr_in));
90    anna_memset(&sourceAddress, 0, sizeof(sockaddr_in));
91    int newSocket = ::accept(Socket::a_fd, (sockaddr*) & sourceAddress, &len);
92
93    if (newSocket < 0) {
94       const int xerrno = errno;
95
96       if (xerrno != EWOULDBLOCK && xerrno != EINTR)
97          throw RuntimeException(asString(), xerrno, ANNA_FILE_LOCATION);
98    } else {
99       result = a_localConnections.create();              // (1)
100
101       try {
102          result->setServerSocket(this);
103          ClientSocket* clientSocket;
104
105          if ((clientSocket = result->getClientSocket()) == NULL) {
106             clientSocket = allocateClientSocket();
107             result->setClientSocket(clientSocket);
108             LOGDEBUG(
109                string msg("comm::ServerSocket::accept | New ClientSocket: ");
110                msg += functions::asHexString(anna_ptrnumber_cast(clientSocket));
111                msg += functions::asText(" | fd: ", newSocket);
112                Logger::debug(msg, ANNA_FILE_LOCATION);
113             );
114          } else {
115             LOGDEBUG(
116                string msg("comm::ServerSocket::accept | Reuse ClientSocket: ");
117                msg += functions::asHexString(anna_ptrnumber_cast(clientSocket));
118                msg += functions::asText(" | fd: ", newSocket);
119                Logger::debug(msg, ANNA_FILE_LOCATION);
120             );
121          }
122
123          clientSocket->setfd(newSocket);
124          clientSocket->setCategory(getCategory());
125          clientSocket->setReceiverFactory(*getReceiverFactory());
126          LOGDEBUG(
127             string msg("comm::ServerSocket::accept | ");
128             msg += asString();
129             msg += " | ";
130             msg += result->asString();
131             Logger::debug(msg, ANNA_FILE_LOCATION);
132          );
133       } catch (RuntimeException&) {
134          ::close(newSocket);
135          release(result);
136          throw;
137       }
138    }
139
140    return result;
141 }
142
143 comm::ClientSocket* comm::ServerSocket::allocateClientSocket() const
144 throw() {
145    return new ClientSocket(getTransportFactory(), Socket::Domain::Inet, Socket::Type::Stream);
146 }
147
148 /*
149  * Se invoca desde el [Tz] = LocalConnection:[Tx] -> Communicator
150  * De forma que hay que bloquear esta instancia para que SU [Tx] no vaya a crear en este momento una nueva conexión.
151  *
152  *
153  * Se invoca desde comm::handler::ServerSocket::apply::[Tx] -> <null>
154  */
155 void comm::ServerSocket::release(LocalConnection* localConnection)
156 throw(RuntimeException) {
157    if (localConnection == NULL)
158       return;
159
160    if (localConnection != NULL)
161       localConnection->setServerSocket(NULL);
162
163    a_localConnections.release(localConnection);
164 }
165
166 std::string comm::ServerSocket::asString() const
167 throw() {
168    std::string msg("comm::ServerSocket { ");
169    msg += comm::Socket::asString();
170    msg += " | Bind: ";
171
172    if (a_sharedBind == true) {
173       msg += "Shared | ";
174       msg += functions::asString(a_binderSocket);
175    } else
176       msg += "Exclusive";
177
178    return msg += " }";
179 }
180
181 xml::Node* comm::ServerSocket::asXML(xml::Node* parent) const
182 throw(RuntimeException) {
183    xml::Node* result = parent->createChild("comm.ServerSocket");
184    comm::Socket::asXML(result);
185    result->createAttribute("Bind", (a_sharedBind) ? "Shared" : "Exclusive");
186
187    if (a_sharedBind == true && a_binderSocket != NULL)
188       a_binderSocket->asXML(result);
189
190    return result;
191 }