summaryrefslogtreecommitdiffstats
blob: 28774e36e5102dfee04832e9066b7c3b295753a6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/**
 * Copyright (C) ARM Limited 2010-2014. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */

#include "OlySocket.h"

#include <stdio.h>
#include <string.h>
#ifdef WIN32
#include <Winsock2.h>
#include <ws2tcpip.h>
#else
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <netdb.h>
#endif

#include "Logging.h"

#ifdef WIN32
#define CLOSE_SOCKET(x) closesocket(x)
#define SHUTDOWN_RX_TX SD_BOTH
#define snprintf       _snprintf
#else
#define CLOSE_SOCKET(x) close(x)
#define SHUTDOWN_RX_TX SHUT_RDWR
#endif

OlyServerSocket::OlyServerSocket(int port) {
#ifdef WIN32
  WSADATA wsaData;
  if (WSAStartup(0x0202, &wsaData) != 0) {
    logg->logError(__FILE__, __LINE__, "Windows socket initialization failed");
    handleException();
  }
#endif

  createServerSocket(port);
}

OlySocket::OlySocket(int socketID) : mSocketID(socketID) {
}

#ifndef WIN32

#define MIN(A, B) ({ \
  const __typeof__(A) __a = A; \
  const __typeof__(B) __b = B; \
  __a > __b ? __b : __a; \
})

OlyServerSocket::OlyServerSocket(const char* path, const size_t pathSize) {
  // Create socket
  mFDServer = socket(PF_UNIX, SOCK_STREAM, 0);
  if (mFDServer < 0) {
    logg->logError(__FILE__, __LINE__, "Error creating server socket");
    handleException();
  }

  // Create sockaddr_in structure, ensuring non-populated fields are zero
  struct sockaddr_un sockaddr;
  memset((void*)&sockaddr, 0, sizeof(sockaddr));
  sockaddr.sun_family = AF_UNIX;
  memcpy(sockaddr.sun_path, path, MIN(pathSize, sizeof(sockaddr.sun_path)));
  sockaddr.sun_path[sizeof(sockaddr.sun_path) - 1] = '\0';

  // Bind the socket to an address
  if (bind(mFDServer, (const struct sockaddr*)&sockaddr, sizeof(sockaddr)) < 0) {
    logg->logError(__FILE__, __LINE__, "Binding of server socket failed.");
    handleException();
  }

  // Listen for connections on this socket
  if (listen(mFDServer, 1) < 0) {
    logg->logError(__FILE__, __LINE__, "Listening of server socket failed");
    handleException();
  }
}

int OlySocket::connect(const char* path, const size_t pathSize) {
  int fd = socket(PF_UNIX, SOCK_STREAM, 0);
  if (fd < 0) {
    return -1;
  }

  // Create sockaddr_in structure, ensuring non-populated fields are zero
  struct sockaddr_un sockaddr;
  memset((void*)&sockaddr, 0, sizeof(sockaddr));
  sockaddr.sun_family = AF_UNIX;
  memcpy(sockaddr.sun_path, path, MIN(pathSize, sizeof(sockaddr.sun_path)));
  sockaddr.sun_path[sizeof(sockaddr.sun_path) - 1] = '\0';

  if (::connect(fd, (const struct sockaddr*)&sockaddr, sizeof(sockaddr)) < 0) {
    close(fd);
    return -1;
  }

  return fd;
}

#endif

OlySocket::~OlySocket() {
  if (mSocketID > 0) {
    CLOSE_SOCKET(mSocketID);
  }
}

OlyServerSocket::~OlyServerSocket() {
  if (mFDServer > 0) {
    CLOSE_SOCKET(mFDServer);
  }
}

void OlySocket::shutdownConnection() {
  // Shutdown is primarily used to unblock other threads that are blocking on send/receive functions
  shutdown(mSocketID, SHUTDOWN_RX_TX);
}

void OlySocket::closeSocket() {
  // Used for closing an accepted socket but keeping the server socket active
  if (mSocketID > 0) {
    CLOSE_SOCKET(mSocketID);
    mSocketID = -1;
  }
}

void OlyServerSocket::closeServerSocket() {
  if (CLOSE_SOCKET(mFDServer) != 0) {
    logg->logError(__FILE__, __LINE__, "Failed to close server socket.");
    handleException();
  }
  mFDServer = 0;
}

void OlyServerSocket::createServerSocket(int port) {
  int family = AF_INET6;

  // Create socket
  mFDServer = socket(PF_INET6, SOCK_STREAM, IPPROTO_TCP);
  if (mFDServer < 0) {
    family = AF_INET;
    mFDServer = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (mFDServer < 0) {
      logg->logError(__FILE__, __LINE__, "Error creating server socket");
      handleException();
    }
  }

  // Enable address reuse, another solution would be to create the server socket once and only close it when the object exits
  int on = 1;
  if (setsockopt(mFDServer, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)) != 0) {
    logg->logError(__FILE__, __LINE__, "Setting server socket options failed");
    handleException();
  }

  // Create sockaddr_in structure, ensuring non-populated fields are zero
  struct sockaddr_in6 sockaddr;
  memset((void*)&sockaddr, 0, sizeof(sockaddr));
  sockaddr.sin6_family = family;
  sockaddr.sin6_port = htons(port);
  sockaddr.sin6_addr = in6addr_any;

  // Bind the socket to an address
  if (bind(mFDServer, (const struct sockaddr*)&sockaddr, sizeof(sockaddr)) < 0) {
    logg->logError(__FILE__, __LINE__, "Binding of server socket failed.\nIs an instance already running?");
    handleException();
  }

  // Listen for connections on this socket
  if (listen(mFDServer, 1) < 0) {
    logg->logError(__FILE__, __LINE__, "Listening of server socket failed");
    handleException();
  }
}

// mSocketID is always set to the most recently accepted connection
// The user of this class should maintain the different socket connections, e.g. by forking the process
int OlyServerSocket::acceptConnection() {
  int socketID;
  if (mFDServer <= 0) {
    logg->logError(__FILE__, __LINE__, "Attempting multiple connections on a single connection server socket or attempting to accept on a client socket");
    handleException();
  }

  // Accept a connection, note that this call blocks until a client connects
  socketID = accept(mFDServer, NULL, NULL);
  if (socketID < 0) {
    logg->logError(__FILE__, __LINE__, "Socket acceptance failed");
    handleException();
  }
  return socketID;
}

void OlySocket::send(const char* buffer, int size) {
  if (size <= 0 || buffer == NULL) {
    return;
  }

  while (size > 0) {
    int n = ::send(mSocketID, buffer, size, 0);
    if (n < 0) {
      logg->logError(__FILE__, __LINE__, "Socket send error");
      handleException();
    }
    size -= n;
    buffer += n;
  }
}

// Returns the number of bytes received
int OlySocket::receive(char* buffer, int size) {
  if (size <= 0 || buffer == NULL) {
    return 0;
  }

  int bytes = recv(mSocketID, buffer, size, 0);
  if (bytes < 0) {
    logg->logError(__FILE__, __LINE__, "Socket receive error");
    handleException();
  } else if (bytes == 0) {
    logg->logMessage("Socket disconnected");
    return -1;
  }
  return bytes;
}

// Receive exactly size bytes of data. Note, this function will block until all bytes are received
int OlySocket::receiveNBytes(char* buffer, int size) {
  int bytes = 0;
  while (size > 0 && buffer != NULL) {
    bytes = recv(mSocketID, buffer, size, 0);
    if (bytes < 0) {
      logg->logError(__FILE__, __LINE__, "Socket receive error");
      handleException();
    } else if (bytes == 0) {
      logg->logMessage("Socket disconnected");
      return -1;
    }
    buffer += bytes;
    size -= bytes;
  }
  return bytes;
}

// Receive data until a carriage return, line feed, or null is encountered, or the buffer fills
int OlySocket::receiveString(char* buffer, int size) {
  int bytes_received = 0;
  bool found = false;

  if (buffer == 0) {
    return 0;
  }

  while (!found && bytes_received < size) {
    // Receive a single character
    int bytes = recv(mSocketID, &buffer[bytes_received], 1, 0);
    if (bytes < 0) {
      logg->logError(__FILE__, __LINE__, "Socket receive error");
      handleException();
    } else if (bytes == 0) {
      logg->logMessage("Socket disconnected");
      return -1;
    }

    // Replace carriage returns and line feeds with zero
    if (buffer[bytes_received] == '\n' || buffer[bytes_received] == '\r' || buffer[bytes_received] == '\0') {
      buffer[bytes_received] = '\0';
      found = true;
    }

    bytes_received++;
  }

  return bytes_received;
}