forked from rileytestut/AltServer-Windows
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathConnectionManager.cpp
More file actions
executable file
·367 lines (292 loc) · 9.84 KB
/
ConnectionManager.cpp
File metadata and controls
executable file
·367 lines (292 loc) · 9.84 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
//
// ConnectionManager.cpp
// AltServer-Windows
//
// Created by Riley Testut on 8/13/19.
// Copyright © 2019 Riley Testut. All rights reserved.
//
#include "ConnectionManager.hpp"
#include <iostream>
#include <thread>
//#include <netinet/in.h>
#include <stddef.h>
/*
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/socket.h>
*/
#include <WinSock2.h>
#include <WS2tcpip.h>
#include "dns_sd.h"
#include "AltServerApp.h"
#include "WirelessConnection.h"
#include "DeviceManager.hpp"
#include "Error.hpp"
#include <memory>
#include <thread>
#include <chrono>
#define WIRED_SERVER_CONNECTION_AVAILABLE_REQUEST "io.altstore.Request.WiredServerConnectionAvailable"
#define WIRED_SERVER_CONNECTION_AVAILABLE_RESPONSE "io.altstore.Response.WiredServerConnectionAvailable"
#define WIRED_SERVER_CONNECTION_START_REQUEST "io.altstore.Request.WiredServerConnectionStart"
#define odslog(msg) { std::wstringstream ss; ss << msg << std::endl; OutputDebugStringW(ss.str().c_str()); }
void DNSSD_API ConnectionManagerBonjourRegistrationFinished(DNSServiceRef service, DNSServiceFlags flags, DNSServiceErrorType errorCode, const char *name, const char *regtype, const char *domain, void *context)
{
std::cout << "Registered service: " << name << " (Error: " << errorCode << ")" << std::endl;
}
void ConnectionManagerConnectedDevice(std::shared_ptr<Device> device)
{
ConnectionManager::instance()->StartNotificationConnection(device);
}
void ConnectionManagerDisconnectedDevice(std::shared_ptr<Device> device)
{
ConnectionManager::instance()->StopNotificationConnection(device);
}
ConnectionManager* ConnectionManager::_instance = nullptr;
ConnectionManager* ConnectionManager::instance()
{
if (_instance == 0)
{
_instance = new ConnectionManager();
}
return _instance;
}
ConnectionManager::ConnectionManager()
{
DeviceManager::instance()->setConnectedDeviceCallback(ConnectionManagerConnectedDevice);
DeviceManager::instance()->setDisconnectedDeviceCallback(ConnectionManagerDisconnectedDevice);
}
void ConnectionManager::Start()
{
WSADATA wsaData;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return;
}
auto listenFunction = [](void) {
ConnectionManager::instance()->Listen();
};
_listeningThread = std::thread(listenFunction);
}
void ConnectionManager::Disconnect(std::shared_ptr<ClientConnection> connection)
{
connection->Disconnect();
_connections.erase(connection);
}
void ConnectionManager::StartAdvertising(int socketPort)
{
DNSServiceRef service = NULL;
uint16_t port = htons(socketPort);
auto serverID = AltServerApp::instance()->serverID();
std::string txtValue("serverID=" + serverID);
char size = txtValue.size();
std::vector<char> txtData;
txtData.reserve(size + 1);
txtData.push_back(size);
for (auto& byte : txtValue)
{
txtData.push_back(byte);
}
DNSServiceErrorType registrationResult = DNSServiceRegister(&service, 0, 0, NULL, "_altserver._tcp", NULL, NULL, port, txtData.size(), txtData.data(), ConnectionManagerBonjourRegistrationFinished, NULL);
if (registrationResult != kDNSServiceErr_NoError)
{
std::cout << "Bonjour Registration Error: " << registrationResult << std::endl;
return;
}
int dnssd_socket = DNSServiceRefSockFD(service);
if (dnssd_socket == -1)
{
std::cout << "Failed to retrieve mDNSResponder socket." << std::endl;
}
this->_mDNSResponderSocket = dnssd_socket;
}
void ConnectionManager::Listen()
{
int socket4 = socket(AF_INET, SOCK_STREAM, 0);
if (socket4 == 0)
{
std::cout << "Failed to create socket." << std::endl;
return;
}
struct sockaddr_in address4;
memset(&address4, 0, sizeof(address4));
//address4.sin_len = sizeof(address4);
address4.sin_family = AF_INET;
address4.sin_port = 0; // Choose for us.
address4.sin_addr.s_addr = INADDR_ANY;
if (bind(socket4, (struct sockaddr *)&address4, sizeof(address4)) < 0)
{
std::cout << "Failed to bind socket." << std::endl;
return;
}
if (listen(socket4, 0) != 0)
{
std::cout << "Failed to prepare listening socket." << std::endl;
}
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(socket4, (struct sockaddr *)&sin, &len) == -1)
{
std::cout << "Failed to get socket name." << std::endl;
}
int port4 = ntohs(sin.sin_port);
this->StartAdvertising(port4);
fd_set input_set;
fd_set copy_set;
while (true)
{
struct timeval tv;
tv.tv_sec = 1; /* 1 second timeout */
tv.tv_usec = 0; /* no microseconds. */
/* Selection */
FD_ZERO(&input_set ); /* Empty the FD Set */
FD_SET(socket4, &input_set); /* Listen to the input descriptor */
FD_ZERO(©_set ); /* Empty the FD Set */
FD_SET(socket4, ©_set); /* Listen to the input descriptor */
int ready_for_reading = select(socket4 + 1, &input_set, ©_set, NULL, &tv);
/* Selection handling */
if (ready_for_reading > 0)
{
struct sockaddr_in clientAddress;
memset(&clientAddress, 0, sizeof(clientAddress));
int addrlen = sizeof(clientAddress);
int other_socket = accept(socket4, (SOCKADDR*)&clientAddress, &addrlen);
char *ipaddress = inet_ntoa(((struct sockaddr_in)clientAddress).sin_addr);
int port2 = ntohs(((struct sockaddr_in)clientAddress).sin_port);
int error = WSAGetLastError();
odslog("Other Socket:" << other_socket << ". Port: " << port2 << ". Error: " << error);
std::shared_ptr<ClientConnection> clientConnection(new WirelessConnection(other_socket));
this->HandleRequest(clientConnection);
}
else if (ready_for_reading == -1)
{
/* Handle the error */
std::cout << "Uh-oh" << std::endl;
}
else
{
// Do nothing
}
}
}
void ConnectionManager::StartNotificationConnection(std::shared_ptr<Device> device)
{
odslog("Starting notification connection to device: " << device->name().c_str());
DeviceManager::instance()->StartNotificationConnection(device)
.then([=](pplx::task<std::shared_ptr<NotificationConnection>> task) {
std::vector<std::string> notifications = { WIRED_SERVER_CONNECTION_AVAILABLE_REQUEST, WIRED_SERVER_CONNECTION_START_REQUEST };
try
{
auto connection = task.get();
connection->StartListening(notifications);
connection->setReceivedNotificationHandler([=](std::string notification) {
this->HandleNotification(notification, connection);
});
this->_notificationConnectionsLock.lock();
this->_notificationConnections[device->identifier()] = connection;
this->_notificationConnectionsLock.unlock();
}
catch (Error& e)
{
odslog("Failed to start notification connection. " << e.localizedDescription().c_str());
}
catch (std::exception& e)
{
odslog("Failed to start notification connection. " << e.what());
}
});
}
void ConnectionManager::StopNotificationConnection(std::shared_ptr<Device> device)
{
this->_notificationConnectionsLock.lock();
if (this->notificationConnections().count(device->identifier()) == 0)
{
this->_notificationConnectionsLock.unlock();
return;
}
auto connection = this->notificationConnections()[device->identifier()];
if (connection == NULL)
{
this->_notificationConnectionsLock.unlock();
return;
}
connection->Disconnect();
this->_notificationConnections.erase(device->identifier());
this->_notificationConnectionsLock.unlock();
}
void ConnectionManager::HandleNotification(std::string notification, std::shared_ptr<NotificationConnection> connection)
{
if (notification == WIRED_SERVER_CONNECTION_AVAILABLE_REQUEST)
{
try
{
connection->SendNotification(WIRED_SERVER_CONNECTION_AVAILABLE_RESPONSE);
odslog("Sent wired server connection available response!");
}
catch (Error& e)
{
odslog("Error sending wired server connection response. " << e.localizedDescription().c_str());
}
catch (std::exception& e)
{
odslog("Error sending wired server connection response. " << e.what());
}
}
else if (notification == WIRED_SERVER_CONNECTION_START_REQUEST)
{
DeviceManager::instance()->StartWiredConnection(connection->device())
.then([=](pplx::task<std::shared_ptr<WiredConnection>> task) {
try
{
auto wiredConnection = task.get();
auto connection = std::dynamic_pointer_cast<ClientConnection>(wiredConnection);
odslog("Started wired server connection!");
this->HandleRequest(wiredConnection);
}
catch (Error& e)
{
odslog("Error starting wired server connection. " << e.localizedDescription().c_str());
}
catch (std::exception& e)
{
odslog("Error starting wired server connection. " << e.what());
}
});
}
}
void ConnectionManager::HandleRequest(std::shared_ptr<ClientConnection> clientConnection)
{
this->_connections.insert(clientConnection);
clientConnection->ProcessAppRequest().then([=](pplx::task<void> task) {
try
{
task.get();
odslog("Finished handling request!");
}
catch (Error& e)
{
odslog("Failed to handle request: " << e.localizedDescription().c_str());
}
catch (std::exception& e)
{
odslog("Failed to handle request: " << e.what());
}
// Add short delay to prevent us from dropping connection too quickly.
std::this_thread::sleep_for(std::chrono::seconds(1));
this->Disconnect(clientConnection);
});
}
int ConnectionManager::mDNSResponderSocket() const
{
return _mDNSResponderSocket;
}
std::set<std::shared_ptr<ClientConnection>> ConnectionManager::connections() const
{
return _connections;
}
std::map<std::string, std::shared_ptr<NotificationConnection>> ConnectionManager::notificationConnections() const
{
return _notificationConnections;
}