gator: Version 5.18
[firefly-linux-kernel-4.4.55.git] / tools / gator / daemon / OlySocket.cpp
1 /**
2  * Copyright (C) ARM Limited 2010-2014. All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  */
8
9 #include "OlySocket.h"
10
11 #include <stdio.h>
12 #ifdef WIN32
13 #include <Winsock2.h>
14 #include <ws2tcpip.h>
15 #else
16 #include <netinet/in.h>
17 #include <sys/socket.h>
18 #include <sys/un.h>
19 #include <unistd.h>
20 #include <netdb.h>
21 #endif
22
23 #include "Logging.h"
24
25 #ifdef WIN32
26 #define CLOSE_SOCKET(x) closesocket(x)
27 #define SHUTDOWN_RX_TX SD_BOTH
28 #define snprintf       _snprintf
29 #else
30 #define CLOSE_SOCKET(x) close(x)
31 #define SHUTDOWN_RX_TX SHUT_RDWR
32 #endif
33
34 OlyServerSocket::OlyServerSocket(int port) {
35 #ifdef WIN32
36   WSADATA wsaData;
37   if (WSAStartup(0x0202, &wsaData) != 0) {
38     logg->logError(__FILE__, __LINE__, "Windows socket initialization failed");
39     handleException();
40   }
41 #endif
42
43   createServerSocket(port);
44 }
45
46 OlySocket::OlySocket(int port, const char* host) {
47   createClientSocket(host, port);
48 }
49
50 OlySocket::OlySocket(int socketID) : mSocketID(socketID) {
51 }
52
53 #ifndef WIN32
54
55 OlyServerSocket::OlyServerSocket(const char* path) {
56   // Create socket
57   mFDServer = socket(PF_UNIX, SOCK_STREAM, 0);
58   if (mFDServer < 0) {
59     logg->logError(__FILE__, __LINE__, "Error creating server socket");
60     handleException();
61   }
62
63   unlink(path);
64
65   // Create sockaddr_in structure, ensuring non-populated fields are zero
66   struct sockaddr_un sockaddr;
67   memset((void*)&sockaddr, 0, sizeof(sockaddr));
68   sockaddr.sun_family = AF_UNIX;
69   strncpy(sockaddr.sun_path, path, sizeof(sockaddr.sun_path) - 1);
70   sockaddr.sun_path[sizeof(sockaddr.sun_path) - 1] = '\0';
71
72   // Bind the socket to an address
73   if (bind(mFDServer, (const struct sockaddr*)&sockaddr, sizeof(sockaddr)) < 0) {
74     logg->logError(__FILE__, __LINE__, "Binding of server socket failed.");
75     handleException();
76   }
77
78   // Listen for connections on this socket
79   if (listen(mFDServer, 1) < 0) {
80     logg->logError(__FILE__, __LINE__, "Listening of server socket failed");
81     handleException();
82   }
83 }
84
85 OlySocket::OlySocket(const char* path) {
86   mSocketID = socket(PF_UNIX, SOCK_STREAM, 0);
87   if (mSocketID < 0) {
88     return;
89   }
90
91   // Create sockaddr_in structure, ensuring non-populated fields are zero
92   struct sockaddr_un sockaddr;
93   memset((void*)&sockaddr, 0, sizeof(sockaddr));
94   sockaddr.sun_family = AF_UNIX;
95   strncpy(sockaddr.sun_path, path, sizeof(sockaddr.sun_path) - 1);
96   sockaddr.sun_path[sizeof(sockaddr.sun_path) - 1] = '\0';
97
98   if (connect(mSocketID, (const struct sockaddr*)&sockaddr, sizeof(sockaddr)) < 0) {
99     close(mSocketID);
100     mSocketID = -1;
101     return;
102   }
103 }
104
105 #endif
106
107 OlySocket::~OlySocket() {
108   if (mSocketID > 0) {
109     CLOSE_SOCKET(mSocketID);
110   }
111 }
112
113 OlyServerSocket::~OlyServerSocket() {
114   if (mFDServer > 0) {
115     CLOSE_SOCKET(mFDServer);
116   }
117 }
118
119 void OlySocket::shutdownConnection() {
120   // Shutdown is primarily used to unblock other threads that are blocking on send/receive functions
121   shutdown(mSocketID, SHUTDOWN_RX_TX);
122 }
123
124 void OlySocket::closeSocket() {
125   // Used for closing an accepted socket but keeping the server socket active
126   if (mSocketID > 0) {
127     CLOSE_SOCKET(mSocketID);
128     mSocketID = -1;
129   }
130 }
131
132 void OlyServerSocket::closeServerSocket() {
133   if (CLOSE_SOCKET(mFDServer) != 0) {
134     logg->logError(__FILE__, __LINE__, "Failed to close server socket.");
135     handleException();
136   }
137   mFDServer = 0;
138 }
139
140 void OlySocket::createClientSocket(const char* hostname, int portno) {
141 #ifdef WIN32
142   // TODO: Implement for Windows
143 #else
144   char buf[32];
145   struct addrinfo hints, *res, *res0;
146
147   snprintf(buf, sizeof(buf), "%d", portno);
148   mSocketID = -1;
149   memset((void*)&hints, 0, sizeof(hints));
150   hints.ai_family = PF_UNSPEC;
151   hints.ai_socktype = SOCK_STREAM;
152
153   if (getaddrinfo(hostname, buf, &hints, &res0)) {
154     logg->logError(__FILE__, __LINE__, "Client socket failed to get address info for %s", hostname);
155     handleException();
156   }
157   for (res=res0; res!=NULL; res = res->ai_next) {
158     if ( res->ai_family != PF_INET || res->ai_socktype != SOCK_STREAM ) {
159       continue;
160     }
161     mSocketID = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
162     if (mSocketID < 0) {
163       continue;
164     }
165     if (connect(mSocketID, res->ai_addr, res->ai_addrlen) < 0) {
166       close(mSocketID);
167       mSocketID = -1;
168     }
169     if (mSocketID > 0) {
170       break;
171     }
172   }
173   freeaddrinfo(res0);
174   if (mSocketID <= 0) {
175     logg->logError(__FILE__, __LINE__, "Could not connect to client socket. Ensure ARM Streamline is running.");
176     handleException();
177   }
178 #endif
179 }
180
181 void OlyServerSocket::createServerSocket(int port) {
182   int family = AF_INET6;
183
184   // Create socket
185   mFDServer = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
186   if (mFDServer < 0) {
187     family = AF_INET;
188     mFDServer = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
189     if (mFDServer < 0) {
190       logg->logError(__FILE__, __LINE__, "Error creating server socket");
191       handleException();
192     }
193   }
194
195   // Enable address reuse, another solution would be to create the server socket once and only close it when the object exits
196   int on = 1;
197   if (setsockopt(mFDServer, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) != 0) {
198     logg->logError(__FILE__, __LINE__, "Setting server socket options failed");
199     handleException();
200   }
201
202   // Create sockaddr_in structure, ensuring non-populated fields are zero
203   struct sockaddr_in6 sockaddr;
204   memset((void*)&sockaddr, 0, sizeof(sockaddr));
205   sockaddr.sin6_family = family;
206   sockaddr.sin6_port = htons(port);
207   sockaddr.sin6_addr = in6addr_any;
208
209   // Bind the socket to an address
210   if (bind(mFDServer, (const struct sockaddr*)&sockaddr, sizeof(sockaddr)) < 0) {
211     logg->logError(__FILE__, __LINE__, "Binding of server socket failed.\nIs an instance already running?");
212     handleException();
213   }
214
215   // Listen for connections on this socket
216   if (listen(mFDServer, 1) < 0) {
217     logg->logError(__FILE__, __LINE__, "Listening of server socket failed");
218     handleException();
219   }
220 }
221
222 // mSocketID is always set to the most recently accepted connection
223 // The user of this class should maintain the different socket connections, e.g. by forking the process
224 int OlyServerSocket::acceptConnection() {
225   int socketID;
226   if (mFDServer <= 0) {
227     logg->logError(__FILE__, __LINE__, "Attempting multiple connections on a single connection server socket or attempting to accept on a client socket");
228     handleException();
229   }
230
231   // Accept a connection, note that this call blocks until a client connects
232   socketID = accept(mFDServer, NULL, NULL);
233   if (socketID < 0) {
234     logg->logError(__FILE__, __LINE__, "Socket acceptance failed");
235     handleException();
236   }
237   return socketID;
238 }
239
240 void OlySocket::send(const char* buffer, int size) {
241   if (size <= 0 || buffer == NULL) {
242     return;
243   }
244
245   while (size > 0) {
246     int n = ::send(mSocketID, buffer, size, 0);
247     if (n < 0) {
248       logg->logError(__FILE__, __LINE__, "Socket send error");
249       handleException();
250     }
251     size -= n;
252     buffer += n;
253   }
254 }
255
256 // Returns the number of bytes received
257 int OlySocket::receive(char* buffer, int size) {
258   if (size <= 0 || buffer == NULL) {
259     return 0;
260   }
261
262   int bytes = recv(mSocketID, buffer, size, 0);
263   if (bytes < 0) {
264     logg->logError(__FILE__, __LINE__, "Socket receive error");
265     handleException();
266   } else if (bytes == 0) {
267     logg->logMessage("Socket disconnected");
268     return -1;
269   }
270   return bytes;
271 }
272
273 // Receive exactly size bytes of data. Note, this function will block until all bytes are received
274 int OlySocket::receiveNBytes(char* buffer, int size) {
275   int bytes = 0;
276   while (size > 0 && buffer != NULL) {
277     bytes = recv(mSocketID, buffer, size, 0);
278     if (bytes < 0) {
279       logg->logError(__FILE__, __LINE__, "Socket receive error");
280       handleException();
281     } else if (bytes == 0) {
282       logg->logMessage("Socket disconnected");
283       return -1;
284     }
285     buffer += bytes;
286     size -= bytes;
287   }
288   return bytes;
289 }
290
291 // Receive data until a carriage return, line feed, or null is encountered, or the buffer fills
292 int OlySocket::receiveString(char* buffer, int size) {
293   int bytes_received = 0;
294   bool found = false;
295
296   if (buffer == 0) {
297     return 0;
298   }
299
300   while (!found && bytes_received < size) {
301     // Receive a single character
302     int bytes = recv(mSocketID, &buffer[bytes_received], 1, 0);
303     if (bytes < 0) {
304       logg->logError(__FILE__, __LINE__, "Socket receive error");
305       handleException();
306     } else if (bytes == 0) {
307       logg->logMessage("Socket disconnected");
308       return -1;
309     }
310
311     // Replace carriage returns and line feeds with zero
312     if (buffer[bytes_received] == '\n' || buffer[bytes_received] == '\r' || buffer[bytes_received] == '\0') {
313       buffer[bytes_received] = '\0';
314       found = true;
315     }
316
317     bytes_received++;
318   }
319
320   return bytes_received;
321 }