aboutsummaryrefslogtreecommitdiff
path: root/daemon/OlySocket.cpp
blob: 499f68cd1866e198dfc3f42d7f50674af6843aa6 (plain)
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
/**
 * Copyright (C) ARM Limited 2010-2013. 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 <stdio.h>
#ifdef WIN32
#include <Winsock2.h>
#else
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#endif
#include "OlySocket.h"
#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

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

  if (multiple) {
    createServerSocket(port);
  } else {
    createSingleServerConnection(port);
  }
}

OlySocket::OlySocket(int port, char* host) {
  mFDServer = 0;
  createClientSocket(host, port);
}

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

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 OlySocket::closeServerSocket() {
  if (CLOSE_SOCKET(mFDServer) != 0) {
    logg->logError(__FILE__, __LINE__, "Failed to close server socket.");
    handleException();
  }
  mFDServer = 0;
}

void OlySocket::createClientSocket(char* hostname, int portno) {
#ifdef WIN32
  // TODO: Implement for Windows
#else
  char buf[32];
  struct addrinfo hints, *res, *res0;

  snprintf(buf, sizeof(buf), "%d", portno);
  mSocketID = -1;
  memset((void*)&hints, 0, sizeof(hints));
  hints.ai_family = PF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;

  if (getaddrinfo(hostname, buf, &hints, &res0)) {
    logg->logError(__FILE__, __LINE__, "Client socket failed to get address info for %s", hostname);
    handleException();
  }
  for (res=res0; res!=NULL; res = res->ai_next) {
    if ( res->ai_family != PF_INET || res->ai_socktype != SOCK_STREAM ) {
      continue;
    }
    mSocketID = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (mSocketID < 0) {
      continue;
    }
    if (connect(mSocketID, res->ai_addr, res->ai_addrlen) < 0) {
      close(mSocketID);
      mSocketID = -1;
    }
    if (mSocketID > 0) {
      break;
    }
  }
  freeaddrinfo(res0);
  if (mSocketID <= 0) {
    logg->logError(__FILE__, __LINE__, "Could not connect to client socket. Ensure ARM Streamline is running.");
    handleException();
  }
#endif
}

void OlySocket::createSingleServerConnection(int port) {
  createServerSocket(port);

  mSocketID = acceptConnection();
  closeServerSocket();
}

void OlySocket::createServerSocket(int port) {
  // Create socket
  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_in sockaddr;
  memset((void*)&sockaddr, 0, sizeof(struct sockaddr_in));
  sockaddr.sin_family = AF_INET;
  sockaddr.sin_port   = htons(port);
  sockaddr.sin_addr.s_addr = INADDR_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 OlySocket::acceptConnection() {
  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
  mSocketID = accept(mFDServer, NULL, NULL);
  if (mSocketID < 0) {
    logg->logError(__FILE__, __LINE__, "Socket acceptance failed");
    handleException();
  }
  return mSocketID;
}

void OlySocket::send(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;
}