summaryrefslogtreecommitdiffstats
path: root/servers/fpga_programming_server_lin/src/fpga_conn.cpp
blob: 330e747e0726292b75ac9c1a15d0950ba06a61a6 (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
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
/*
 * Remote Laboratory FPGA Server
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * (c) 2012 Timothy Pearson
 * Raptor Engineering
 * http://www.raptorengineeringinc.com
 */

#include <stdio.h>                /* perror() */
#include <stdlib.h>               /* atoi() */
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>               /* read() */
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <sys/signal.h>
#include <sys/types.h>

#include <tqtimer.h>
#include <tqfile.h>

#include <klocale.h>

#include "fpga_conn.h"

#define ABORT_SOCKET(s) 		s->close();						\
					s->disconnect();					\
					delete s;						\
					s = NULL;

//#define NETWORK_COMM_TIMEOUT_MS 2000
#define NETWORK_COMM_TIMEOUT_MS 4000

/* exception handling */
struct exit_exception {
	int c;
	exit_exception(int c):c(c) { }
};

/*
  The FPGASocket class provides a socket that is connected with a client.
  For every client that connects to the server, the server creates a new
  instance of this class.
*/
FPGASocket::FPGASocket(int sock, TQObject *parent, const char *name) :
	TDEKerberosServerSocket(parent, name), m_criticalSection(0), m_loopTimer(NULL), m_config(static_cast<FPGAServer*>(parent)->m_config), m_commandLoopState(0) {

	// Initialize timers
	m_kerberosInitTimer = new TQTimer();
	connect(m_kerberosInitTimer, SIGNAL(timeout()), this, SLOT(finishKerberosHandshake()));
	m_servClientTimeout = new TQTimer();

	setServiceName("remotefpga");

	line = 0;
	connect(this, SIGNAL(connectionClosed()), SLOT(connectionClosedHandler()));
	connect(this, SIGNAL(connectionClosed()), parent, SLOT(remoteConnectionClosed()));
	setSocket(sock);
}

FPGASocket::~FPGASocket() {
	if (m_servClientTimeout) {
		m_servClientTimeout->stop();
		delete m_servClientTimeout;
		m_servClientTimeout = NULL;
	}
	if (m_kerberosInitTimer) {
		m_kerberosInitTimer->stop();
		delete m_kerberosInitTimer;
		m_kerberosInitTimer = NULL;
	}
	if (m_loopTimer) {
		m_loopTimer->stop();
		delete m_loopTimer;
		m_loopTimer = NULL;
	}
}

void FPGASocket::close() {
	if (state() == TQSocket::Connected) {
		TDEKerberosServerSocket::close();
		connectionClosedHandler();
		TQTimer::singleShot(0, parent(), SLOT(remoteConnectionClosed()));
	}
}

void FPGASocket::connectionClosedHandler() {
	printf("[DEBUG] Connection from %s closed\n\r", m_remoteHost.ascii());

	if (m_criticalSection > 0) {
		throw exit_exception(-1);
	}
}

void FPGASocket::initiateKerberosHandshake() {
	setUsingKerberos(true);
	m_kerberosInitTimer->start(100, TRUE);
}

void FPGASocket::finishKerberosHandshake() {
	if (kerberosStatus() == TDEKerberosServerSocket::KerberosInitializing) {
		m_kerberosInitTimer->start(100, TRUE);
		return;
	}
	if (kerberosStatus() == TDEKerberosServerSocket::KerberosInUse) {
		m_config->setGroup("Security");
		TQString masterUser = m_config->readEntry("masteruser");
		TQString masterRealm = m_config->readEntry("masterrealm");
		if (masterRealm == "") {
			masterRealm = "(NULL)";
		}
		if ((m_authenticatedUserName != masterUser) || (m_authenticatedRealmName != masterRealm)) {
			printf("[DEBUG] Connection from %s closed due to authentication failure (attempted connection as user %s@%s)\n\r", m_remoteHost.ascii(), masterUser.ascii(), masterRealm.ascii());
			close();
			return;
		}

		setDataTimeout(NETWORK_COMM_TIMEOUT_MS);

		TQDataStream ds(this);
		ds << TQString("OK");

		enterCommandLoop();
		return;
	}
	else {
		printf("[DEBUG] Connection from %s closed due to Kerberos failure\n\r", m_remoteHost.ascii()); fflush(stdout);
		close();
		return;
	}
}

void FPGASocket::commandLoop() {
	bool transferred_data;

	m_criticalSection++;
	try {
		transferred_data = false;
		if (state() == TQSocket::Connected) {
			if (m_commandLoopState == 0) {
printf("[RAJA DEBUG 499.0] Waiting for command...\n\r"); fflush(stdout);
				if (canReadLine()) {
printf("[RAJA DEBUG 499.1] Processing pending data (buffer: %d)...\n\r", bytesAvailable()); fflush(stdout);
					processPendingData();
				}
				if (bytesAvailable() > 0) {
					TQDataStream ds(this);
					TQString command;
					ds >> command;
					printf("[DEBUG] Received command '%s'\n\r", command.ascii());
					if (command == "STATUS") {
						ds << TQString("IDLE");
					}
					else if (command == "FILE") {
						m_commandLoopState = 1;
					}
					else {
						printf("[WARNING] Received unknown command '%s'\n\r", command.ascii());
					}
					transferred_data = true;
				}
			}
			else if (m_commandLoopState == 1) {
				if (canReadLine()) {
					processPendingData();
				}
printf("[RAJA DEBUG 500.0] Waiting for file...\n\r"); fflush(stdout);
				if (bytesAvailable() > 0) {
printf("[RAJA DEBUG 500.1] Waiting for file (buffer: %d)...\n\r", bytesAvailable()); fflush(stdout);
					TQDataStream ds(this);
					ds >> m_programmingFileSize;
					m_servClientTimeout->start(NETWORK_COMM_TIMEOUT_MS, TRUE);
					m_commandLoopState = 2;
				}
			}
			else if (m_commandLoopState == 2) {
				if (canReadLine()) {
printf("[RAJA DEBUG 500.2] Processing pending data (buffer: %d)...\n\r", bytesAvailable()); fflush(stdout);
					m_servClientTimeout->start(NETWORK_COMM_TIMEOUT_MS, TRUE);
					processPendingData();
				}
printf("[RAJA DEBUG 500.3] Waiting for file contents (buffer: %d)...\n\r", bytesAvailable()); fflush(stdout);
				if (bytesAvailable() >= m_programmingFileSize) {
					TQByteArray fileContents(m_programmingFileSize);
					readBlock(fileContents.data(), fileContents.size());
printf("[RAJA DEBUG 500.4] Received file!\n\r"); fflush(stdout);
printf("[RAJA DEBUG 500.5] fileContents size: %d\n\r", fileContents.size()); fflush(stdout);
					m_programmingFileName = TQString("/tmp/%1#%2.dat").arg(m_remoteHost).arg(port());
					TQFile outputFile(m_programmingFileName);
					if (outputFile.open(IO_ReadWrite)) {
						outputFile.writeBlock(fileContents);
						outputFile.flush();
						outputFile.close();
					}
					transferred_data = true;
					m_commandLoopState = 0;
				}
				else {
					if (!m_servClientTimeout->isActive()) {
						TQDataStream ds(this);
						ds << TQString("ERROR");
						transferred_data = true;
						m_commandLoopState = 0;
					}
				}
			}
		}
		m_criticalSection--;
		if (transferred_data) {
			if (m_loopTimer) m_loopTimer->start(0, TRUE);
		}
		else {
			if (m_loopTimer) m_loopTimer->start(100, TRUE);
		}
		return;
	}
	catch (...) {
		m_criticalSection--;
		return;
	}
}

int FPGASocket::enterCommandLoop() {
	m_commandLoopState = 0;
	if (!m_loopTimer) {
		m_loopTimer = new TQTimer();
		connect(m_loopTimer, SIGNAL(timeout()), this, SLOT(commandLoop()));
	}
	if (m_loopTimer) m_loopTimer->start(0, TRUE);
	return 0;
}

/*
  The FPGAServer class handles new connections to the server. For every
  client that connects, it creates a new FPGASocket -- that instance is now
  responsible for the communication with that client.
*/
FPGAServer::FPGAServer(TQObject* parent, int port, KSimpleConfig* config) :
	TQServerSocket( port, 1, parent ), m_config(config), m_numberOfConnections(0) {

	if ( !ok() ) {
		printf("[ERROR] Failed to bind to port %d\n\r", port);
		exit(1);
	}

	printf("[INFO] Server started on port %d\n\r", port); fflush(stdout);
}

FPGAServer::~FPGAServer() {
	//
}

void FPGAServer::newConnection(int socket) {
	FPGASocket *s = new FPGASocket(socket, this);
	s->m_remoteHost = s->peerAddress().toString();
	printf("[DEBUG] New connection from %s\n\r", s->m_remoteHost.ascii());
	if (m_numberOfConnections > 0) {
		printf("[DEBUG] Connection from %s closed due to multiple access attempt\n\r", s->m_remoteHost.ascii());
		ABORT_SOCKET(s)
		return;
	}
	connect(s, SIGNAL(connectionClosed()), s, SLOT(deleteLater()));
	s->initiateKerberosHandshake();
	emit newConnect(s);
}

void FPGAServer::remoteConnectionClosed() {
	m_numberOfConnections--;
}