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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
|
/*
* Copyright (c) 2011 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
extern "C" {
#include "sluift.h"
#include <lauxlib.h>
}
#include <iostream>
#include <string>
#include <deque>
#include <boost/assign/list_of.hpp>
#include <Swiften/Swiften.h>
#include "Watchdog.h"
#include "SluiftException.h"
#include "ResponseSink.h"
#include "Lua/Value.h"
using namespace Swift;
#define SLUIFT_CLIENT "SluiftClient*"
/*******************************************************************************
* Forward declarations
******************************************************************************/
bool debug = false;
/*******************************************************************************
* Helper classes
******************************************************************************/
SimpleEventLoop eventLoop;
BoostNetworkFactories networkFactories(&eventLoop);
class SluiftClient {
public:
SluiftClient(const JID& jid, const std::string& password) : tracer(NULL) {
client = new Client(jid, password, &networkFactories);
client->setAlwaysTrustCertificates();
client->onDisconnected.connect(boost::bind(&SluiftClient::handleDisconnected, this, _1));
client->onMessageReceived.connect(boost::bind(&SluiftClient::handleIncomingEvent, this, _1));
client->onPresenceReceived.connect(boost::bind(&SluiftClient::handleIncomingEvent, this, _1));
client->getRoster()->onInitialRosterPopulated.connect(boost::bind(&SluiftClient::handleInitialRosterPopulated, this));
if (debug) {
tracer = new ClientXMLTracer(client);
}
}
~SluiftClient() {
delete tracer;
delete client;
}
Client* getClient() {
return client;
}
void connect() {
rosterReceived = false;
client->connect();
}
void waitConnected() {
while (client->isActive() && !client->isAvailable()) {
eventLoop.runUntilEvents();
}
}
bool isConnected() const {
return client->isAvailable();
}
void sendMessage(const JID& to, const std::string& body) {
Message::ref message = boost::make_shared<Message>();
message->setTo(to);
message->setBody(body);
client->sendMessage(message);
}
void sendPresence(const std::string& status) {
client->sendPresence(boost::make_shared<Presence>(status));
}
std::string sendQuery(const JID& jid, IQ::Type type, const std::string& data) {
rawRequestResponse.reset();
RawRequest::ref request = RawRequest::create(type, jid, data, client->getIQRouter());
request->onResponse.connect(boost::bind(&SluiftClient::handleRawRequestResponse, this, _1));
request->send();
while (!rawRequestResponse) {
eventLoop.runUntilEvents();
}
return *rawRequestResponse;
}
void disconnect() {
client->disconnect();
while (client->isActive()) {
eventLoop.runUntilEvents();
}
}
void setSoftwareVersion(const std::string& name, const std::string& version, const std::string& os) {
client->setSoftwareVersion(name, version, os);
}
Stanza::ref getNextEvent(int timeout) {
if (!pendingEvents.empty()) {
Stanza::ref event = pendingEvents.front();
pendingEvents.pop_front();
return event;
}
Watchdog watchdog(timeout, networkFactories.getTimerFactory());
while (!watchdog.getTimedOut() && pendingEvents.empty()) {
eventLoop.runUntilEvents();
}
if (watchdog.getTimedOut()) {
return Stanza::ref();
}
else {
Stanza::ref event = pendingEvents.front();
pendingEvents.pop_front();
return event;
}
}
std::vector<XMPPRosterItem> getRoster() {
if (!rosterReceived) {
// If we haven't requested it yet, request it for the first time
client->requestRoster();
}
while (!rosterReceived) {
eventLoop.runUntilEvents();
}
return client->getRoster()->getItems();
}
private:
void handleIncomingEvent(Stanza::ref stanza) {
pendingEvents.push_back(stanza);
}
void handleInitialRosterPopulated() {
rosterReceived = true;
}
void handleRawRequestResponse(const std::string& response) {
rawRequestResponse = response;
}
void handleDisconnected(const boost::optional<ClientError>& error) {
if (error) {
throw SluiftException(*error);
}
}
private:
Client* client;
ClientXMLTracer* tracer;
bool rosterReceived;
std::deque<Stanza::ref> pendingEvents;
boost::optional<std::string> rawRequestResponse;
};
/*******************************************************************************
* Client functions.
******************************************************************************/
static inline SluiftClient* getClient(lua_State* L) {
return *reinterpret_cast<SluiftClient**>(luaL_checkudata(L, 1, SLUIFT_CLIENT));
}
static int sluift_client_connect(lua_State *L) {
try {
SluiftClient* client = getClient(L);
client->connect();
client->waitConnected();
return 1;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_client_async_connect(lua_State *L) {
try {
getClient(L)->connect();
return 1;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_client_wait_connected(lua_State *L) {
try {
getClient(L)->waitConnected();
return 1;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_client_is_connected(lua_State *L) {
lua_pushboolean(L, getClient(L)->isConnected());
return 1;
}
static int sluift_client_disconnect(lua_State *L) {
try {
getClient(L)->disconnect();
return 1;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_client_set_version(lua_State *L) {
SluiftClient* client = getClient(L);
luaL_checktype(L, 2, LUA_TTABLE);
lua_getfield(L, 2, "name");
const char* rawName = lua_tostring(L, -1);
lua_getfield(L, 2, "version");
const char* rawVersion = lua_tostring(L, -1);
lua_getfield(L, 2, "os");
const char* rawOS = lua_tostring(L, -1);
client->setSoftwareVersion(rawName ? rawName : "", rawVersion ? rawVersion : "", rawOS ? rawOS : "");
lua_pop(L, 3);
lua_pushvalue(L, 1);
return 1;
}
static int sluift_client_get_roster(lua_State *L) {
try {
SluiftClient* client = getClient(L);
Lua::Table rosterTable;
foreach(const XMPPRosterItem& item, client->getRoster()) {
std::string subscription;
switch(item.getSubscription()) {
case RosterItemPayload::None: subscription = "none"; break;
case RosterItemPayload::To: subscription = "to"; break;
case RosterItemPayload::From: subscription = "from"; break;
case RosterItemPayload::Both: subscription = "both"; break;
case RosterItemPayload::Remove: subscription = "remove"; break;
}
Lua::Value groups(std::vector<Lua::Value>(item.getGroups().begin(), item.getGroups().end()));
Lua::Table itemTable = boost::assign::map_list_of
("jid", boost::make_shared<Lua::Value>(item.getJID().toString()))
("name", boost::make_shared<Lua::Value>(item.getName()))
("subscription", boost::make_shared<Lua::Value>(subscription))
("groups", boost::make_shared<Lua::Value>(std::vector<Lua::Value>(item.getGroups().begin(), item.getGroups().end())));
rosterTable[item.getJID().toString()] = boost::make_shared<Lua::Value>(itemTable);
}
pushValue(L, rosterTable);
return 1;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_client_get_version(lua_State *L) {
try {
SluiftClient* client = getClient(L);
ResponseSink<SoftwareVersion> sink;
GetSoftwareVersionRequest::ref request = GetSoftwareVersionRequest::create(std::string(luaL_checkstring(L, 2)), client->getClient()->getIQRouter());
request->onResponse.connect(boost::ref(sink));
request->send();
while (!sink.hasResponse()) {
eventLoop.runUntilEvents();
}
if (ErrorPayload::ref error = sink.getResponseError()) {
lua_pushnil(L);
// TODO
if (error->getCondition() == ErrorPayload::RemoteServerNotFound) {
lua_pushstring(L, "Remote server not found");
}
else {
lua_pushstring(L, "Error");
}
return 2;
}
else if (SoftwareVersion::ref version = sink.getResponsePayload()) {
Lua::Table result = boost::assign::map_list_of
("name", boost::make_shared<Lua::Value>(version->getName()))
("version", boost::make_shared<Lua::Value>(version->getVersion()))
("os", boost::make_shared<Lua::Value>(version->getOS()));
Lua::pushValue(L, result);
}
else {
lua_pushnil(L);
}
return 1;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_client_send_message(lua_State *L) {
getClient(L)->sendMessage(std::string(luaL_checkstring(L, 2)), luaL_checkstring(L, 3));
lua_pushvalue(L, 1);
return 1;
}
static int sluift_client_send_presence(lua_State *L) {
getClient(L)->sendPresence(std::string(luaL_checkstring(L, 2)));
lua_pushvalue(L, 1);
return 0;
}
static int sluift_client_get(lua_State *L) {
SluiftClient* client = getClient(L);
JID jid;
std::string data;
if (lua_type(L, 3) != LUA_TNONE) {
jid = JID(std::string(luaL_checkstring(L, 2)));
data = std::string(luaL_checkstring(L, 3));
}
else {
data = std::string(luaL_checkstring(L, 2));
}
std::string result = client->sendQuery(jid, IQ::Get, data);
lua_pushstring(L, result.c_str());
return 1;
}
static int sluift_client_set(lua_State *L) {
SluiftClient* client = getClient(L);
JID jid;
std::string data;
if (lua_type(L, 3) != LUA_TNONE) {
jid = JID(std::string(luaL_checkstring(L, 2)));
data = std::string(luaL_checkstring(L, 3));
}
else {
data = std::string(luaL_checkstring(L, 2));
}
std::string result = client->sendQuery(jid, IQ::Set, data);
lua_pushstring(L, result.c_str());
return 1;
}
static int sluift_client_send(lua_State *L) {
getClient(L)->getClient()->sendData(std::string(luaL_checkstring(L, 2)));
lua_pushvalue(L, 1);
return 0;
}
static int sluift_client_set_options(lua_State* L) {
SluiftClient* client = getClient(L);
luaL_checktype(L, 2, LUA_TTABLE);
lua_getfield(L, 2, "compress");
if (!lua_isnil(L, -1)) {
client->getClient()->setUseStreamCompression(lua_toboolean(L, -1));
}
lua_getfield(L, 2, "tls");
if (!lua_isnil(L, -1)) {
bool useTLS = lua_toboolean(L, -1);
client->getClient()->setUseTLS(useTLS ? Client::UseTLSWhenAvailable : Client::NeverUseTLS);
}
lua_pushvalue(L, 1);
return 0;
}
static void pushEvent(lua_State* L, Stanza::ref event) {
if (Message::ref message = boost::dynamic_pointer_cast<Message>(event)) {
Lua::Table result = boost::assign::map_list_of
("type", boost::make_shared<Lua::Value>("message"))
("from", boost::make_shared<Lua::Value>(message->getFrom().toString()))
("body", boost::make_shared<Lua::Value>(message->getBody()));
Lua::pushValue(L, result);
}
else if (Presence::ref presence = boost::dynamic_pointer_cast<Presence>(event)) {
Lua::Table result = boost::assign::map_list_of
("type", boost::make_shared<Lua::Value>("presence"))
("from", boost::make_shared<Lua::Value>(presence->getFrom().toString()))
("status", boost::make_shared<Lua::Value>(presence->getStatus()));
Lua::pushValue(L, result);
}
else {
lua_pushnil(L);
}
}
static int sluift_client_for_event(lua_State *L) {
try {
eventLoop.runOnce();
SluiftClient* client = getClient(L);
luaL_checktype(L, 2, LUA_TFUNCTION);
int timeout = -1;
if (lua_type(L, 3) != LUA_TNONE) {
timeout = lua_tonumber(L, 3);
}
while (true) {
Stanza::ref event = client->getNextEvent(timeout);
if (!event) {
// We got a timeout
lua_pushnil(L);
return 1;
}
else {
// Push the function and event on the stack
lua_pushvalue(L, 2);
pushEvent(L, event);
int oldTop = lua_gettop(L) - 2;
lua_call(L, 1, LUA_MULTRET);
int returnValues = lua_gettop(L) - oldTop;
if (returnValues > 0) {
lua_remove(L, -1 - returnValues);
return returnValues;
}
}
}
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_client_get_next_event(lua_State *L) {
try {
eventLoop.runOnce();
SluiftClient* client = getClient(L);
int timeout = -1;
if (lua_type(L, 2) != LUA_TNONE) {
timeout = lua_tonumber(L, 2);
}
pushEvent(L, client->getNextEvent(timeout));
return 1;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_client_add_contact(lua_State* L) {
try {
eventLoop.runOnce();
SluiftClient* client = getClient(L);
JID jid(luaL_checkstring(L, 2));
client->getRoster();
if (!client->getClient()->getRoster()->containsJID(jid)) {
RosterItemPayload item;
item.setJID(jid);
RosterPayload::ref roster = boost::make_shared<RosterPayload>();
roster->addItem(item);
ResponseSink<RosterPayload> sink;
SetRosterRequest::ref request = SetRosterRequest::create(roster, client->getClient()->getIQRouter());
request->onResponse.connect(boost::ref(sink));
request->send();
while (!sink.hasResponse()) {
eventLoop.runUntilEvents();
}
if (sink.getResponseError()) {
lua_pushboolean(L, false);
return 1;
}
}
client->getClient()->getSubscriptionManager()->requestSubscription(jid);
lua_pushboolean(L, true);
return 1;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_client_remove_contact(lua_State* L) {
try {
eventLoop.runOnce();
SluiftClient* client = getClient(L);
JID jid(luaL_checkstring(L, 2));
RosterPayload::ref roster = boost::make_shared<RosterPayload>();
roster->addItem(RosterItemPayload(JID(luaL_checkstring(L, 2)), "", RosterItemPayload::Remove));
ResponseSink<RosterPayload> sink;
SetRosterRequest::ref request = SetRosterRequest::create(roster, client->getClient()->getIQRouter());
request->onResponse.connect(boost::ref(sink));
request->send();
while (!sink.hasResponse()) {
eventLoop.runUntilEvents();
}
lua_pushboolean(L, !sink.getResponseError());
return 1;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_client_confirm_subscription(lua_State* L) {
try {
eventLoop.runOnce();
SluiftClient* client = getClient(L);
JID jid(luaL_checkstring(L, 2));
client->getClient()->getSubscriptionManager()->confirmSubscription(jid);
return 0;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_client_cancel_subscription(lua_State* L) {
try {
eventLoop.runOnce();
SluiftClient* client = getClient(L);
JID jid(luaL_checkstring(L, 2));
client->getClient()->getSubscriptionManager()->cancelSubscription(jid);
return 0;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_client_gc (lua_State *L) {
SluiftClient* client = getClient(L);
delete client;
return 0;
}
static const luaL_reg sluift_client_functions[] = {
{"connect", sluift_client_connect},
{"async_connect", sluift_client_async_connect},
{"wait_connected", sluift_client_wait_connected},
{"is_connected", sluift_client_is_connected},
{"disconnect", sluift_client_disconnect},
{"send_message", sluift_client_send_message},
{"send_presence", sluift_client_send_presence},
{"get", sluift_client_get},
{"set", sluift_client_set},
{"send", sluift_client_send},
{"set_version", sluift_client_set_version},
{"get_roster", sluift_client_get_roster},
{"get_version", sluift_client_get_version},
{"set_options", sluift_client_set_options},
{"for_event", sluift_client_for_event},
{"get_next_event", sluift_client_get_next_event},
{"add_contact", sluift_client_add_contact},
{"remove_contact", sluift_client_remove_contact},
{"confirm_subscription", sluift_client_confirm_subscription},
{"cancel_subscription", sluift_client_cancel_subscription},
{"__gc", sluift_client_gc},
{NULL, NULL}
};
/*******************************************************************************
* Module functions
******************************************************************************/
static int sluift_new_client(lua_State *L) {
try {
JID jid(std::string(luaL_checkstring(L, 1)));
std::string password(luaL_checkstring(L, 2));
SluiftClient** client = reinterpret_cast<SluiftClient**>(lua_newuserdata(L, sizeof(SluiftClient*)));
luaL_getmetatable(L, SLUIFT_CLIENT);
lua_setmetatable(L, -2);
*client = new SluiftClient(jid, password);
return 1;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_sleep(lua_State *L) {
try {
eventLoop.runOnce();
int timeout = luaL_checknumber(L, 1);
Watchdog watchdog(timeout, networkFactories.getTimerFactory());
while (!watchdog.getTimedOut()) {
Swift::sleep(std::min(100, timeout));
eventLoop.runOnce();
}
return 0;
}
catch (const SluiftException& e) {
return luaL_error(L, e.getReason().c_str());
}
}
static int sluift_index(lua_State *L) {
luaL_checkstring(L, 2);
if (std::string(lua_tostring(L, 2)) == "debug") {
lua_pushboolean(L, debug);
return 1;
}
else {
return luaL_error(L, "Invalid index");
}
}
static int sluift_newindex(lua_State *L) {
luaL_checkstring(L, 2);
if (std::string(lua_tostring(L, 2)) == "debug") {
debug = lua_toboolean(L, 3);
return 0;
}
else {
return luaL_error(L, "Invalid index");
}
}
static const luaL_reg sluift_functions[] = {
{"new_client", sluift_new_client},
{"sleep", sluift_sleep},
{NULL, NULL}
};
/*******************************************************************************
* Module registration
******************************************************************************/
SLUIFT_API int luaopen_sluift(lua_State *L) {
// Register functions
luaL_register(L, "sluift", sluift_functions);
lua_createtable(L, 0, 0);
lua_pushcclosure(L, sluift_index, 0);
lua_setfield(L, -2, "__index");
lua_pushcclosure(L, sluift_newindex, 0);
lua_setfield(L, -2, "__newindex");
lua_setmetatable(L, -2);
// Register the client metatable
luaL_newmetatable(L, SLUIFT_CLIENT);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_register(L, NULL, sluift_client_functions);
return 1;
}
|