summaryrefslogtreecommitdiff
path: root/distfoldd/serveragent.cc
blob: 3f133bd91ccd08c894eed3164e02e372c670e27c (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
#include <QtCore/QDebug>

#include "serveragent.h"

ServerAgent::ServerAgent(QSslSocket *socket, const QDir& local_dir, const QString& passwd, SyncFlags flags, QObject *parent) :
    Agent(socket, local_dir, passwd, flags, parent),
    _challenge(generateChallenge()), _authAttempted(false), _authOk(false)
{
	qDebug() << "Starting server agent at" << QDateTime::currentDateTime();
}

void ServerAgent::handleMessage(MessageType msg, const QByteArray& data)
{
	qDebug() << "Server::handleMessage" << msg << data.size();
	switch (msg) {
	case MSG_HELLO:
		if (decodeHelloMessage(data, &_clientChallenge) == PROTO_BAD) {
			qWarning() << "Invalid protocol version";
			_socket->close();
		}
		sendMessage(MSG_HELLO_REPLY, _challenge);
		break;
	case MSG_AUTH:
		handleAuth(data);
		break;
	case MSG_FILE_LIST:
		if (!checkAuth()) return;
		handleClientFileList(decodeFileInfoList(data));
		break;
	case MSG_PULL_FILE:
		if (!checkAuth()) return;
		handlePullFile(decodeFileName(data));
		break;
	case MSG_PUSH_FILE:
		if (!checkAuth()) return;
		handlePushedFile(data);
		break;
	case MSG_PUSH_FILE_METADATA:
		if (!checkAuth()) return;
		handlePushedMetadata(decodeFileInfoList(data));
		break;
	case MSG_DELETE_FILE:
		if (!checkAuth()) return;
		handleDeleteFile(decodeFileName(data));
		break;
	case MSG_BYE:
		if (!checkAuth()) return;
		qDebug() << "Got Bye";
		emit finished();
		_socket->close();
		break;
	default:
		qWarning() << "Unknown message";
		break;
	}
}

bool ServerAgent::checkAuth()
{
	if (_authOk) {
		return true;
	} else {
		sendMessage(MSG_AUTH_REPLY, encodeAuthReply(AUTH_FAILED));
		return false;
	}
}

void ServerAgent::handleAuth(const QByteArray &response)
{
	if (_authAttempted) {
		qWarning() << "Too many auth attempts";
		sendMessage(MSG_AUTH_REPLY, encodeAuthReply(AUTH_FAILED));
		_socket->flush();
		_socket->close();
		return;
	}
	_authAttempted = true;

	qDebug() << "Server Handling client auth";

	if (response == generateChallengeResponse(_challenge, _clientChallenge)) {
		_authOk = true;
		qDebug() << "Authentication successful";
	} else {
		_authOk = false;
		qDebug() << "Authentication failed";
	}

	sendMessage(MSG_AUTH_REPLY, encodeAuthReply(_authOk ? AUTH_OK : AUTH_FAILED));
}

void ServerAgent::handleClientFileList(const RemoteFileInfoList& list)
{
	QFileInfoList files = scanFiles(QDir(wireToLocalPath(_subPath)));
	ActionInfoList actions_create_dirs, actions_with_files, actions_remove_dirs, actions_update_dirs;
	QHash<QString, QFileInfo> local_files;
	QHash<QString, RemoteFileInfo> remote_files;
	QSet<QString> new_local_files;

	foreach (const QFileInfo& file, files) {
		const QString wire_path = localToWirePath(file.absoluteFilePath());
		local_files[wire_path] = file;
		new_local_files.insert(wire_path);
	}
	foreach (const RemoteFileInfo& file, list) {
		remote_files[file.name()] = file;
	}

	foreach (const RemoteFileInfo& remote, list) {
		// Main synchronization logic goes here
		QString wire_path = remote.name();
		qDebug() << "Server Handling file" << wire_path;
		new_local_files.remove(wire_path);
		if (local_files.contains(wire_path)) {
			// Both remote and local have the file
			QFileInfo local = local_files[wire_path];
			QString parent_name = wireParentPath(wire_path);
			QFileInfo parent_local = local_files[parent_name];
			RemoteFileInfo parent_remote = remote_files[parent_name];
			Q_ASSERT(local.exists());
			if (remote.isDir() && local.isDir()) {
				if (equalDateTime(remote.lastModified(), local.lastModified())) {
					if (local.lastModified().toTime_t() == 0) {
						// Workaround an issue if the local folder is a mountpoint
						actions_update_dirs += ActionInfo(ACTION_PULL_METADATA, local);
					}
				     // Nothing to do
				} else if (remote.lastModified() > local.lastModified()) {
					actions_update_dirs += ActionInfo(ACTION_PUSH_METADATA, local);
				} else {
					actions_update_dirs += ActionInfo(ACTION_PULL_METADATA, local);
				}
			} else if (remote.isDir() == local.isDir() &&
			    equalDateTime(remote.lastModified(), local.lastModified()) &&
			    remote.size() == local.size()) {
				// Nothing to do
			} else if (remote.isDir() != local.isDir()) {
				// Dir to file transformation, delete the most recent file
				if (parent_remote.lastModified() > parent_local.lastModified()) {
					if (local.isDir()) {
						actions_remove_dirs += ActionInfo(ACTION_PUSH_DELETE, local);
					} else {
						actions_with_files += ActionInfo(ACTION_PUSH_DELETE, local);
					}
				} else {
					if (remote.isDir()) {
						actions_remove_dirs += ActionInfo(ACTION_PULL_DELETE, local);
					} else {
						actions_with_files += ActionInfo(ACTION_PULL_DELETE, local);
					}
				}
			} else if (remote.lastModified() > local.lastModified()) {
				if (remote.isDir()) {
					actions_create_dirs += ActionInfo(ACTION_PUSH, local);
				} else {
					actions_with_files += ActionInfo(ACTION_PUSH, local);
				}
			} else {
				if (remote.isDir()) {
					actions_create_dirs += ActionInfo(ACTION_PULL, local);
				} else {
					actions_with_files += ActionInfo(ACTION_PULL, local);
				}
			}
		} else {
			// File is in remote, but not in local
			qDebug() << " file deleted";
			QString parent_name = findExistingCommonAncestor(wire_path, local_files, remote_files);
			QFileInfo local(wireToLocalPath(wire_path)); // Create invalid QFileInfo
			QFileInfo parent_local = local_files[parent_name];
			RemoteFileInfo parent_remote = remote_files[parent_name];
			if (parent_remote.lastModified() > parent_local.lastModified()) {
				if (remote.isDir()) {
					actions_create_dirs += ActionInfo(ACTION_PUSH, local);
					actions_update_dirs += ActionInfo(ACTION_PUSH_METADATA, local);
				} else {
					actions_with_files += ActionInfo(ACTION_PUSH, local);
				}
			} else {
				if (remote.isDir()) {
					actions_remove_dirs += ActionInfo(ACTION_PULL_DELETE, local);
				} else {
					actions_with_files += ActionInfo(ACTION_PULL_DELETE, local);
				}
			}
		}
	}

	foreach (const QString& path, new_local_files) {
		// File is in local, but not in remote
		QString parent_name = findExistingCommonAncestor(path, local_files, remote_files);
		QFileInfo local = local_files[path];
		QFileInfo parent_local = local_files[parent_name];
		RemoteFileInfo parent_remote = remote_files[parent_name];
		if (parent_remote.lastModified() > parent_local.lastModified()) {
			if (local.isDir()) {
				actions_remove_dirs += ActionInfo(ACTION_PUSH_DELETE, local);
			} else {
				actions_with_files += ActionInfo(ACTION_PUSH_DELETE, local);
			}
		} else {
			if (local.isDir()) {
				actions_create_dirs += ActionInfo(ACTION_PULL, local);
				actions_update_dirs += ActionInfo(ACTION_PULL_METADATA, local);
			} else {
				actions_with_files += ActionInfo(ACTION_PULL, local);
			}
		}
	}

	qSort(actions_create_dirs.begin(), actions_create_dirs.end(),
	      static_cast<bool (*)(const ActionInfo&, const ActionInfo&)>(lessPathDepthThan));
	qSort(actions_remove_dirs.begin(), actions_remove_dirs.end(),
	      static_cast<bool (*)(const ActionInfo&, const ActionInfo&)>(morePathDepthThan));
	qSort(actions_update_dirs.begin(), actions_update_dirs.end(),
	      static_cast<bool (*)(const ActionInfo&, const ActionInfo&)>(morePathDepthThan));

	ActionInfoList actions = actions_create_dirs +
	        actions_with_files + actions_remove_dirs +
	        actions_update_dirs;
	sendMessage(MSG_FILE_ACTIONS_REPLY, encodeActionInfoList(actions));
}

void ServerAgent::handlePullFile(const QString &path)
{
	QFile file(wireToLocalPath(path));
	if (file.open(QIODevice::ReadOnly)) {
		QByteArray ba = file.readAll();
		if (_flags & SYNC_COMPRESS) {
			int old_size = ba.size();
			ba = Compressor::compress(ba);
			qDebug() << "Compress" << old_size << "->" << ba.size();
		}
		file.close();
		sendMessage(MSG_PULL_FILE_REPLY, ba);
	} else {
		qWarning() << "Failed to open file" << file.fileName() << "for reading";
	}
}

void ServerAgent::handlePushedFile(const QByteArray &ba)
{
	if (_flags & SYNC_READ_ONLY) return;
	int len;
	QString wire_path = decodeFileNameItem(ba, &len);
	QByteArray file_data = Compressor::decompress(ba.mid(len));

	QFile file(wireToLocalPath(wire_path));
	if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
		file.write(file_data);
		file.close();
	} else {
		qWarning() << "Failed to open file" << file.fileName() << "for writing";
	}
}

void ServerAgent::handlePushedMetadata(const RemoteFileInfoList& list)
{
	if (_flags & SYNC_READ_ONLY) return;
	foreach (const RemoteFileInfo& remote, list) {
		QString local_path = wireToLocalPath(remote.name());
		setLocalFileDateTime(local_path, remote.lastModified());
	}
}

void ServerAgent::handleDeleteFile(const QString &path)
{
	if (_flags & SYNC_READ_ONLY) return;
	QString local_path = wireToLocalPath(path);
	if (!QDir().remove(local_path)) {
		qWarning() << "Failed to remove file" << local_path;
	}
}