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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
|
#include <QtCrypto>
#include "agent.h"
#ifdef Q_OS_UNIX
#include <sys/time.h>
#include <utime.h>
#endif
Agent::Agent(QSslSocket *socket, const QDir& dir, const QString& passwd, SyncFlags flags, QObject *parent) :
QObject(parent), _dir(dir), _subPath("/"), _passwd(passwd), _flags(flags), _socket(socket)
{
connect(_socket, SIGNAL(readyRead()), SLOT(handleDataAvailable()));
connect(_socket, SIGNAL(sslErrors(QList<QSslError>)), SLOT(handleSslErrors(QList<QSslError>)));
connect(_socket, SIGNAL(disconnected()), SLOT(handleDisconnected()));
}
Agent::RemoteFileInfo::RemoteFileInfo() :
_name(), _type(FILE_TYPE_NONE), _mtime(), _size(0)
{
}
Agent::RemoteFileInfo::RemoteFileInfo(const QString &name, FileType type, const QDateTime &mtime, qint64 size) :
_name(name), _type(type), _mtime(mtime), _size(size)
{
}
Agent::ActionInfo::ActionInfo(FileAction action, const QFileInfo &fileInfo) :
_action(action), _info(fileInfo)
{
}
Agent::RemoteActionInfo::RemoteActionInfo(FileAction action, const QString &name, FileType type, const QDateTime &mtime, qint64 size) :
_action(action), _info(name, type, mtime, size)
{
}
void Agent::sendMessage(MessageType msg, const QByteArray &content)
{
const int header_len = sizeof(MessageHeader);
QByteArray ba(header_len + content.size(), '\0');
MessageHeader *h = reinterpret_cast<MessageHeader*>(ba.data());
h->msg = msg;
h->len = content.size();
if (h->len > 0) {
ba.replace(header_len, content.size(), content);
}
Q_ASSERT(ba.size() == header_len + content.size());
qDebug() << "Sending " << msg << content.size();
_socket->write(ba);
}
int Agent::inBufRequiredData() const
{
const int header_len = sizeof(MessageHeader);
if (_inBuf.size() < header_len) {
return header_len;
} else {
const MessageHeader *h;
h = reinterpret_cast<const MessageHeader*>(_inBuf.data());
return header_len + h->len;
}
}
bool Agent::equalDateTime(const QDateTime& dt1, const QDateTime& dt2)
{
const qint64 threshold = 5 * 1000;
qint64 msecs = dt1.msecsTo(dt2);
return msecs > -threshold && msecs < threshold;
}
void Agent::setLocalFileDateTime(const QString &path, const QDateTime &dt)
{
#if defined(Q_OS_UNIX)
const char *filename = path.toLocal8Bit().constData();
struct utimbuf times;
times.actime = dt.toTime_t();
times.modtime = dt.toTime_t();
int rc = utime(filename, ×);
if (rc != 0) {
qWarning() << "Could not set local mtime of" << path;
}
#elif defined(Q_OS_WIN32)
// TODO SetFileAttributes, SetFileTime
#endif
}
QString Agent::wireToLocalPath(const QString &path)
{
return _dir.absolutePath() + _subPath + path;
}
QString Agent::localToWirePath(const QString& path)
{
const QString& basePath = _dir.absolutePath() + _subPath;
Q_ASSERT(_subPath.endsWith('/'));
QString wire_path(path);
if (path.startsWith(basePath)) {
wire_path.remove(0, basePath.size());
} else if (path + '/' == basePath) {
wire_path = QString(); // This is the root dir.
} else {
qWarning() << "Where does this come from?" << path;
}
return wire_path;
}
QString Agent::wireParentPath(const QString &path)
{
int index = path.lastIndexOf('/');
if (index == -1) return QString("");
else return path.left(index);
}
QString Agent::findExistingCommonAncestor(const QString& path,
const QHash<QString, QFileInfo>& local_files,
const QHash<QString, RemoteFileInfo>& remote_files)
{
QString ancestor = path;
do {
ancestor = wireParentPath(ancestor);
} while (!local_files.contains(ancestor) || !remote_files.contains(ancestor));
return ancestor;
}
bool Agent::lessPathDepthThan(const QString& s1, const QString& s2)
{
int d1 = s1.count('/'), d2 = s2.count('/');
return d1 < d2;
}
bool Agent::morePathDepthThan(const QString& s1, const QString& s2)
{
int d1 = s1.count('/'), d2 = s2.count('/');
return d1 > d2;
}
QByteArray Agent::encodeHelloMessage(const QByteArray& client_challenge)
{
QByteArray ba(sizeof(quint32), '\0');
quint32 *p = reinterpret_cast<quint32*>(ba.data());
*p = PROTO_CURRENT;
ba.append(client_challenge);
return ba;
}
Agent::ProtoVersion Agent::decodeHelloMessage(const QByteArray& ba, QByteArray *client_challenge)
{
if (ba.size() < static_cast<int>(sizeof(quint32))) return PROTO_BAD;
const quint32 *p = reinterpret_cast<const quint32*>(ba.constData());
switch (*p) {
case PROTO_1:
*client_challenge = ba.mid(sizeof(quint32));
return PROTO_1;
default:
return PROTO_BAD;
}
}
QByteArray Agent::hmacSha1(const QByteArray& key, const QByteArray& message)
{
QCA::MessageAuthenticationCode mac("hmac(sha1)", QCA::SymmetricKey(key));
mac.update(message);
return mac.final().toByteArray();
}
QByteArray Agent::generateChallenge()
{
const int challenge_size = 10;
return QCA::Random::randomArray(challenge_size).toByteArray();
}
QByteArray Agent::generateChallengeResponse(const QByteArray& server_challenge, const QByteArray& client_challenge, const QSslCertificate& server_cert, const QSslCertificate& client_cert)
{
QByteArray server_digest = server_cert.digest(QCryptographicHash::Sha1);
QByteArray client_digest = client_cert.digest(QCryptographicHash::Sha1);
return hmacSha1(_passwd.toUtf8(), server_challenge + server_digest +
client_challenge + client_digest);
}
QByteArray Agent::encodeAuthReply(AuthResult result)
{
QByteArray ba(sizeof(quint8), static_cast<char>(result));
return ba;
}
Agent::AuthResult Agent::decodeAuthReply(const QByteArray& ba)
{
if (ba.size() != 1) return AUTH_FAILED;
const quint8 *p = reinterpret_cast<const quint8*>(ba.constData());
return static_cast<AuthResult>(*p);
}
QFileInfoList Agent::scanFiles(const QDir& dir)
{
QFileInfoList all;
QFileInfoList sub = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);
all << QFileInfo(dir, ".");
foreach (const QFileInfo &info, sub) {
if (info.isDir()) {
all << scanFiles(QDir(info.absoluteFilePath()));
} else {
all << info;
}
}
return all;
}
QByteArray Agent::encodeFileInfoList(const QFileInfoList& list)
{
QByteArray ba;
if (list.empty()) return ba;
ba.reserve(list.size() * (sizeof(FileListItem) + 10));
foreach (const QFileInfo& info, list) {
QString path = localToWirePath(info.absoluteFilePath());
FileListItem item;
item.size = info.size();
if (info.isDir() && _flags & SYNC_PULL) {
// If we are pulling, then simulate all of our local directories being old,
// so that we get all the new file creations
// Existing files should be compared with the proper mtimes though.
item.mtime = 0;
} else {
item.mtime = info.lastModified().toTime_t();
}
if (info.isDir()) {
item.type = FILE_TYPE_DIR;
} else if (info.isFile()) {
item.type = FILE_TYPE_FILE;
} else {
qWarning() << "What is this?" << path;
continue;
}
QByteArray utfPath = encodeFileName(path);
item.name_len = utfPath.size();
ba.append(reinterpret_cast<char*>(&item), sizeof(FileListItem));
ba.append(utfPath.constData());
}
return ba;
}
Agent::RemoteFileInfoList Agent::decodeFileInfoList(const QByteArray& ba)
{
RemoteFileInfoList list;
int pos = 0;
while (pos < ba.size()) {
const FileListItem *item;
item = reinterpret_cast<const FileListItem*>(&(ba.data()[pos]));
list.append(RemoteFileInfo(QString::fromUtf8(&item->name[0],
item->name_len),
static_cast<FileType>(item->type),
QDateTime::fromTime_t(item->mtime),
item->size));
pos += sizeof(FileListItem) + item->name_len;
}
return list;
}
QByteArray Agent::encodeActionInfoList(const ActionInfoList &list)
{
QByteArray ba;
ba.reserve(list.size() * (sizeof(ActionItem) + 10));
foreach (const ActionInfo& info, list) {
const QFileInfo fileInfo = info.fileInfo();
QString path = localToWirePath(fileInfo.absoluteFilePath());
ActionItem item;
item.action = info.action();
item.size = fileInfo.size();
item.mtime = fileInfo.lastModified().toTime_t();
if (fileInfo.isDir()) {
item.type = FILE_TYPE_DIR;
} else if (fileInfo.isFile()) {
item.type = FILE_TYPE_FILE;
} else {
item.type = FILE_TYPE_NONE; // Actions might refer to no-longer existing files
}
QByteArray utfPath = path.toUtf8();
item.name_len = utfPath.size();
ba.append(reinterpret_cast<char*>(&item), sizeof(item));
ba.append(utfPath.constData());
}
return ba;
}
Agent::RemoteActionInfoList Agent::decodeActionInfoList(const QByteArray& ba)
{
RemoteActionInfoList list;
int pos = 0;
while (pos < ba.size()) {
const ActionItem *item;
item = reinterpret_cast<const ActionItem*>(&(ba.data()[pos]));
list.append(RemoteActionInfo(static_cast<FileAction>(item->action),
QString::fromUtf8(&item->name[0],
item->name_len),
static_cast<FileType>(item->type),
QDateTime::fromTime_t(item->mtime),
item->size));
pos += sizeof(ActionItem) + item->name_len;
}
return list;
}
bool Agent::lessPathDepthThan(const ActionInfo& a1, const ActionInfo& a2)
{
return lessPathDepthThan(a1.fileInfo().absoluteFilePath(),
a2.fileInfo().absoluteFilePath());
}
bool Agent::morePathDepthThan(const ActionInfo& a1, const ActionInfo& a2)
{
return morePathDepthThan(a1.fileInfo().absoluteFilePath(),
a2.fileInfo().absoluteFilePath());
}
QByteArray Agent::encodeFileName(const QString& wire_path)
{
return wire_path.toUtf8();
}
QString Agent::decodeFileName(const QByteArray& ba)
{
return QString::fromUtf8(ba);
}
QByteArray Agent::encodeFileNameItem(const QString& wire_path)
{
QByteArray utf8 = encodeFileName(wire_path);
QByteArray ba(sizeof(FileNameItem), 0);
FileNameItem *item = reinterpret_cast<FileNameItem*>(ba.data());
item->name_len = utf8.length();
ba.append(utf8);
return ba;
}
QString Agent::decodeFileNameItem(const QByteArray& ba, int* length)
{
const FileNameItem *item = reinterpret_cast<const FileNameItem*>(ba.data());
*length = sizeof(FileNameItem) + item->name_len;
QString wire_path = decodeFileName(ba.mid(sizeof(FileNameItem), item->name_len));
return wire_path;
}
void Agent::handleDataAvailable()
{
do {
_inBuf.append(_socket->readAll());
while (_inBuf.size() >= inBufRequiredData()) {
MessageHeader *h = reinterpret_cast<MessageHeader*>(_inBuf.data());
QByteArray data;
if (h->len > 0) {
data = _inBuf.mid(sizeof(MessageHeader), h->len);
}
handleMessage(static_cast<MessageType>(h->msg), data);
_inBuf.remove(0, inBufRequiredData());
}
} while (_socket->bytesAvailable() > 0);
}
void Agent::handleSslErrors(const QList<QSslError> &errors)
{
qDebug() << "SSL errors:" << errors;
_socket->ignoreSslErrors(); // TODO For now
}
void Agent::handleDisconnected()
{
qDebug() << "Disconnected at" << QDateTime::currentDateTime();
deleteLater();
}
|