Debian Codegraph @

src/ConnectDialog.cpp

raw symbols SCIP
1 #include "ConnectDialog.h"
2 #include "ranges.h"
3 #include <QProcess>
4 #include <QString>
5 #include <QDir>
6 #include <QFileInfo>
7 #include <QTcpSocket>
8 #include <QtAlgorithms>
9 #include <cassert>
10
11 #ifdef _WIN32
12 #include "SspiNegotiateClient.h"
13 #include "QAbstractSocketStreamWrapper.h"
14 #include <QHostAddress>
15 #include <fstream>
16 #include <winsock2.h>
17 using namespace openmsx;
18 #else
19 #include <pwd.h>
20 #include <sys/socket.h>
21 #include <sys/un.h>
22 #include <cstring>
23 #include <unistd.h>
24 #endif
25
26
27 // Helper functions to setup a connection
28
29 static QString getUserName()
30 {
31 #ifdef _WIN32
32 return "default";
33 #else
34 struct passwd* pw = getpwuid(getuid());
35 return pw->pw_name ? pw->pw_name : "";
36 #endif
37 }
38
39 static bool checkSocketDir(const QDir& dir)
40 {
41 if (!dir.exists()) {
42 return false;
43 }
44 #ifndef _WIN32
45 // only do permission and owner checks on *nix
46 QFileInfo info(dir.absolutePath());
47 if (info.ownerId() != getuid()) {
48 return false;
49 }
50 int all = QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner |
51 QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup |
52 QFile::ReadOther | QFile::WriteOther | QFile::ExeOther;
53 QFile::Permissions needed = QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner;
54 if ((info.permissions() & all) != needed) {
55 return false;
56 }
57 #endif
58 return true;
59 }
60
61 static bool checkSocket(const QFileInfo& info)
62 {
63 if (!info.fileName().startsWith("socket.")) {
64 // wrong name
65 return false;
66 }
67 #ifndef _WIN32
68 // only do permission and owner checks on *nix
69 int all = QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner |
70 QFile::ReadGroup | QFile::WriteGroup | QFile::ExeGroup |
71 QFile::ReadOther | QFile::WriteOther | QFile::ExeOther;
72 QFile::Permissions needed = QFile::ReadOwner | QFile::WriteOwner;
73 if ((info.permissions() & all) != needed) {
74 return false;
75 }
76 if (info.ownerId() != getuid()) {
77 return false;
78 }
79 #endif
80 return true;
81 }
82
83 static void deleteSocket(const QFileInfo& info)
84 {
85 QFile::remove(info.absoluteFilePath()); // ignore errors
86 QDir dir;
87 dir.rmdir(info.absolutePath()); // ignore errors
88 }
89
90 static std::unique_ptr<OpenMSXConnection> createConnection(const QDir& dir, const QString& socketName)
91 {
92 QFileInfo info(dir, socketName);
93 if (!checkSocket(info)) {
94 // invalid socket
95 return nullptr;
96 }
97
98 QAbstractSocket* socket = nullptr;
99 #ifdef _WIN32
100 int port = -1;
101 std::ifstream in(info.absoluteFilePath().toLatin1().data());
102 in >> port;
103 if (port != -1) {
104 QHostAddress localhost(QHostAddress::LocalHost);
105 socket = new QTcpSocket();
106 socket->connectToHost(localhost, port);
107
108 QAbstractSocketStreamWrapper stream(socket);
109 SspiNegotiateClient client(stream);
110
111 if (!socket->waitForConnected(1000) ||
112 !client.Authenticate()) {
113 delete socket;
114 socket = nullptr;
115 }
116 }
117 #else
118 int sd = ::socket(AF_UNIX, SOCK_STREAM, 0);
119 if (sd != -1) {
120 sockaddr_un addr;
121 addr.sun_family = AF_UNIX;
122 strcpy(addr.sun_path, info.absoluteFilePath().toLatin1().data());
123 if (connect(sd, (sockaddr*)&addr, sizeof(addr)) != -1) {
124 socket = new QTcpSocket();
125 if (!socket->setSocketDescriptor(sd)) {
126 // failed to wrap socket in QTcpSocket
127 delete socket;
128 socket = nullptr;
129 close(sd);
130 }
131 } else {
132 // failed to connect to UNIX socket
133 close(sd);
134 }
135 }
136
137 #endif
138 if (socket) {
139 return std::make_unique<OpenMSXConnection>(socket);
140 } else {
141 // cannot connect, must be a stale socket, try to clean it up
142 deleteSocket(socketName);
143 return {};
144 }
145 }
146
147 static std::vector<std::unique_ptr<OpenMSXConnection>> collectServers()
148 {
149 #ifdef _WIN32
150 DWORD len = GetTempPathW(0, nullptr);
151 assert(len > 0); // nothing we can do to recover this
152 //VLA(wchar_t, bufW, (len+1));
153 //wchar_t bufW[len+1];
154 auto bufW = static_cast<wchar_t*>(_alloca(sizeof(wchar_t) * (len+1)));
155
156 len = GetTempPathW(len, bufW);
157 assert(len > 0); // nothing we can do to recover this
158 QDir dir(QString::fromWCharArray(bufW, len));
159 #else
160 QDir dir((getenv("TMPDIR")) ? getenv("TMPDIR") : QDir::tempPath());
161 #endif
162 dir.cd("openmsx-" + getUserName());
163 if (!checkSocketDir(dir)) {
164 // no correct socket directory
165 return {};
166 }
167 QDir::Filters filters =
168 #ifdef _WIN32
169 QDir::Files; // regular files for win32
170 #else
171 QDir::System; // sockets for *nix
172 #endif
173 std::vector<std::unique_ptr<OpenMSXConnection>> servers;
174 for (const auto& name : dir.entryList(filters)) {
175 if (auto connection = createConnection(dir, name)) {
176 servers.push_back(std::move(connection));
177 }
178 }
179 return servers;
180 }
181
182
183 // ConnectionInfoRequest class
184
185 ConnectionInfoRequest::ConnectionInfoRequest(
186 ConnectDialog& dialog_, OpenMSXConnection& connection_)
187 : dialog(dialog_), connection(connection_)
188 {
189 state = GET_MACHINE;
190 connection.sendCommand(this);
191 }
192
193 QString ConnectionInfoRequest::getCommand() const
194 {
195 switch (state) {
196 case GET_MACHINE:
197 return "machine_info config_name";
198 case GET_TITLE:
199 return "guess_title";
200 default:
201 assert(false);
202 return "";
203 }
204 }
205
206 void ConnectionInfoRequest::replyOk(const QString& message)
207 {
208 switch (state) {
209 case GET_MACHINE:
210 title = message;
211 state = GET_TITLE;
212 connection.sendCommand(this);
213 break;
214 case GET_TITLE: {
215 if (!message.isEmpty()) {
216 title += " (" + message + ")";
217 }
218 dialog.connectionOk(connection, title);
219 state = DONE;
220 connect(&connection, &OpenMSXConnection::disconnected,
221 this, &ConnectionInfoRequest::terminate);
222 break;
223 }
224 default:
225 assert(false);
226 }
227 }
228
229 void ConnectionInfoRequest::replyNok(const QString& /*message*/)
230 {
231 cancel();
232 }
233
234 void ConnectionInfoRequest::cancel()
235 {
236 dialog.connectionBad(connection);
237 }
238
239 void ConnectionInfoRequest::terminate()
240 {
241 cancel();
242 }
243
244 // class ConnectDialog
245
246 std::unique_ptr<OpenMSXConnection> ConnectDialog::getConnection(QWidget* parent)
247 {
248 ConnectDialog dialog(parent);
249
250 // delay for at most 500ms while checking the connections
251 dialog.delay = 1;
252 dialog.startTimer(500);
253 while (!dialog.pendingConnections.empty() && dialog.delay) {
254 qApp->processEvents(QEventLoop::AllEvents, 200);
255 }
256
257 // if there is only one valid connection, use it immediately,
258 // otherwise execute the dialog.
259 if (dialog.pendingConnections.empty() && dialog.confirmedConnections.size() == 1) {
260 dialog.on_connectButton_clicked();
261 } else {
262 dialog.exec();
263 }
264 return std::move(dialog.result);
265 }
266
267 ConnectDialog::ConnectDialog(QWidget* parent)
268 : QDialog(parent)
269 , result(nullptr)
270 {
271 ui.setupUi(this);
272 connect(ui.connectButton, &QPushButton::clicked, this, &ConnectDialog::on_connectButton_clicked);
273 connect(ui.rescanButton, &QPushButton::clicked, this, &ConnectDialog::on_rescanButton_clicked);
274 on_rescanButton_clicked();
275 }
276
277 ConnectDialog::~ConnectDialog()
278 {
279 clear();
280 }
281
282 void ConnectDialog::timerEvent(QTimerEvent* event)
283 {
284 killTimer(event->timerId());
285 delay = 0;
286 }
287
288 void ConnectDialog::clear()
289 {
290 ui.listConnections->clear();
291
292 // First kill the infos. That will remove the disconnect signals.
293 qDeleteAll(connectionInfos);
294 connectionInfos.clear();
295 pendingConnections.clear();
296 confirmedConnections.clear();
297 }
298
299 void ConnectDialog::on_connectButton_clicked()
300 {
301 if (int row = ui.listConnections->currentRow();
302 row != -1) {
303 assert((0 <= row) && (row < int(confirmedConnections.size())));
304 result = std::move(confirmedConnections[row]);
305 confirmedConnections.erase(confirmedConnections.begin() + row);
306 }
307 accept();
308 }
309
310 void ConnectDialog::on_rescanButton_clicked()
311 {
312 clear();
313 pendingConnections = collectServers();
314 for (auto& connection : pendingConnections) {
315 connectionInfos.append(new ConnectionInfoRequest(*this, *connection));
316 }
317 }
318
319 void ConnectDialog::connectionOk(OpenMSXConnection& connection,
320 const QString& title)
321 {
322 auto it = ranges::find(pendingConnections, &connection, [](auto& e) { return e.get(); });
323 if (it == pendingConnections.end()) {
324 // connection is already being destoyed
325 return;
326 }
327 confirmedConnections.push_back(std::move(*it));
328 pendingConnections.erase(it);
329
330 new QListWidgetItem(title, ui.listConnections);
331
332 if (ui.listConnections->count() == 1) {
333 // automatically select first row
334 ui.listConnections->setCurrentRow(0);
335 }
336 }
337
338 void ConnectDialog::connectionBad(OpenMSXConnection& connection)
339 {
340 auto find = [](auto& coll, auto& conn) {
341 return ranges::find(coll, &conn, [](auto& e) { return e.get(); });
342 };
343
344 if (auto it = find(pendingConnections, connection);
345 it != pendingConnections.end()) {
346 pendingConnections.erase(it);
347 } else if (auto it2 = find(confirmedConnections, connection);
348 it2 != confirmedConnections.end()) {
349 // Was this connection established but terminated?
350 int id = std::distance(confirmedConnections.begin(), it2);
351 QListWidgetItem* item = ui.listConnections->takeItem(id);
352 delete item;
353
354 confirmedConnections.erase(it2);
355 }
356 }