-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathp3msgservice.cc
More file actions
2996 lines (2388 loc) · 96.6 KB
/
p3msgservice.cc
File metadata and controls
2996 lines (2388 loc) · 96.6 KB
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* libretroshare/src/services: p3msgservice.cc *
* *
* libretroshare: retroshare core library *
* *
* Copyright (C) 2004-2008 Robert Fernie <retroshare@lunamutt.com> *
* Copyright (C) 2016-2019 Gioacchino Mazzurco <gio@eigenlab.org> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
// Messaging system
// ================
//
//
//
// sendMail()
// |
// +---- for each to/cc --- sendDistantMessage(RsMsgItem *,GxsId from) // sends from GxsId to GxsId
// | |
// messageSend() +--- store in msgOutgoing[]
// | |
// +-----for each to/cc --- sendMessage(RsMsgItem *) // sends from node to node
//
// tick()
// |
// +----- checkOutgoingMessages()
// | |
// | +----- sendDistantMsgItem()
// | |
// | +-- p3Grouter::sendData()
// | |
// | +-- p3GxsTrans::sendData()
// |
// +----- manageDistantPeers()
// | |
// | +----- p3GRouter::register/unregisterKey() // adds remove peers
// |
// +----- incomingMsg()
// | |
// | ...
// | |
// | +--- processIncomingMsg()
// | |
// | +--- store in mReceivedMessages[]
// | |
// | +--- store in mRecentlyReceivedMessageHashes[]
// |
// +----- cleanListOfReceivedMessageHashes()
//
#include "retroshare/rsiface.h"
#include "retroshare/rspeers.h"
#include "retroshare/rsidentity.h"
#include "pqi/pqibin.h"
#include "pqi/p3linkmgr.h"
#include "pqi/authgpg.h"
#include "pqi/p3cfgmgr.h"
#include "gxs/gxssecurity.h"
#include "services/p3idservice.h"
#include "services/p3msgservice.h"
#include "pgp/pgpkeyutil.h"
#include "rsserver/p3face.h"
#include "rsitems/rsconfigitems.h"
#include "grouter/p3grouter.h"
#include "grouter/groutertypes.h"
#include "util/rsdebug.h"
#include "util/rsdir.h"
#include "util/rsstring.h"
#include "util/radix64.h"
#include "util/rsrandom.h"
#include "util/rsmemory.h"
#include "util/rsprint.h"
#include "util/rsthreads.h"
#include <unistd.h>
#include <iomanip>
#include <map>
#include <sstream>
using namespace Rs::Mail;
RsMail *rsMail = nullptr; // extern
//#define DEBUG_DISTANT_MSG
/// keep msg hashes for 2 months to avoid re-sent msgs
static constexpr uint32_t RS_MSG_DISTANT_MESSAGE_HASH_KEEP_TIME = 2*30*86400;
/* Another little hack ..... unique message Ids
* will be handled in this class.....
* These are unique within this run of the server,
* and are not stored long term....
*
* Only 3 entry points:
* (1) from network....
* (2) from local send
* (3) from storage...
*/
p3MsgService::p3MsgService( p3ServiceControl *sc, p3IdService *id_serv,
p3GxsTrans& gxsMS )
: p3Service(), p3Config(),
gxsOngoingMutex("p3MsgService Gxs Outgoing Mutex"), mIdService(id_serv),
mServiceCtrl(sc), mMsgMtx("p3MsgService"),
recentlyReceivedMutex("p3MsgService recently received hash mutex"),
mGxsTransServ(gxsMS)
{
/* this serialiser is used for services. It's not the same than the one
* returned by setupSerialiser(). We need both!! */
_serialiser = new RsMsgSerialiser();
addSerialType(_serialiser);
/* MsgIds are not transmitted, but only used locally as a storage index.
* As such, thay do not need to be different at friends nodes. */
mShouldEnableDistantMessaging = true;
mDistantMessagingEnabled = false;
mDistantMessagePermissions = RS_DISTANT_MESSAGING_CONTACT_PERMISSION_FLAG_FILTER_NONE;
if(sc) initStandardTagTypes(); // Initialize standard tag types
mGxsTransServ.registerGxsTransClient( GxsTransSubServices::P3_MSG_SERVICE, this );
}
const std::string MSG_APP_NAME = "msg";
const uint16_t MSG_APP_MAJOR_VERSION = 1;
const uint16_t MSG_APP_MINOR_VERSION = 0;
const uint16_t MSG_MIN_MAJOR_VERSION = 1;
const uint16_t MSG_MIN_MINOR_VERSION = 0;
RsServiceInfo p3MsgService::getServiceInfo()
{
return RsServiceInfo(RS_SERVICE_TYPE_MSG,
MSG_APP_NAME,
MSG_APP_MAJOR_VERSION,
MSG_APP_MINOR_VERSION,
MSG_MIN_MAJOR_VERSION,
MSG_MIN_MINOR_VERSION);
}
p3MsgService::~p3MsgService()
{
RS_STACK_MUTEX(mMsgMtx); /********** STACK LOCKED MTX ******/
for(auto tag:mTags) delete tag.second;
for(auto img:mReceivedMessages) delete img.second;
for(auto img:mSentMessages) delete img.second;
for(auto mpend:_pendingPartialIncomingMessages) delete mpend.second;
}
uint32_t p3MsgService::getNewUniqueMsgId()
{
RS_STACK_MUTEX(mMsgMtx); /********** STACK LOCKED MTX ******/
uint32_t res;
do { res = RsRandom::random_u32(); } while(mAllMessageIds.find(res)!= mAllMessageIds.end());
mAllMessageIds.insert(res);
return res;
}
int p3MsgService::tick()
{
/* don't worry about increasing tick rate!
* (handled by p3service)
*/
incomingMsgs();
static rstime_t last_management_time = 0 ;
rstime_t now = time(NULL) ;
if(now > last_management_time + 5)
{
manageDistantPeers();
checkOutgoingMessages();
cleanListOfReceivedMessageHashes();
last_management_time = now;
#ifdef DEBUG_DISTANT_MSG
debug_dump();
#endif
}
return 0;
}
void p3MsgService::cleanListOfReceivedMessageHashes()
{
RS_STACK_MUTEX(recentlyReceivedMutex);
rstime_t now = time(nullptr);
for( auto it = mRecentlyReceivedMessageHashes.begin();
it != mRecentlyReceivedMessageHashes.end(); )
if( now > RS_MSG_DISTANT_MESSAGE_HASH_KEEP_TIME + it->second )
{
std::cerr << "p3MsgService(): cleanListOfReceivedMessageHashes(). "
<< "Removing old hash " << it->first << ", aged "
<< now - it->second << " secs ago" << std::endl;
it = mRecentlyReceivedMessageHashes.erase(it);
}
else ++it;
}
void p3MsgService::processIncomingMsg(RsMsgItem *mi,const MsgAddress& from,const MsgAddress& to)
{
mi -> recvTime = static_cast<uint32_t>(time(nullptr));
mi -> msgId = getNewUniqueMsgId();
{
RS_STACK_MUTEX(mMsgMtx);
/* from a peer */
mi->msgFlags &= (RS_MSG_FLAGS_DISTANT | RS_MSG_FLAGS_SYSTEM); // remove flags except those
mi->msgFlags |= RS_MSG_FLAGS_NEW;
if (rsEvents)
{
auto ev = std::make_shared<RsMailStatusEvent>();
ev->mMailStatusEventCode = RsMailStatusEventCode::NEW_MESSAGE;
ev->mChangedMsgIds.insert(std::to_string(mi->msgId));
rsEvents->postEvent(ev);
}
RsMailStorageItem * msi = new RsMailStorageItem;
msi->msg = *mi;
msi->from = from;
msi->to = to;
mReceivedMessages[mi->msgId] = msi;
IndicateConfigChanged(RsConfigMgr::CheckPriority::SAVE_NOW); /**** INDICATE MSG CONFIG CHANGED! *****/
/**** STACK UNLOCKED ***/
}
// If the peer is allowed to push files, then auto-download the recommended files.
RsIdentityDetails id_details;
if(rsIdentity->getIdDetails(RsGxsId(mi->PeerId()),id_details) && !id_details.mPgpId.isNull() && (rsPeers->servicePermissionFlags(id_details.mPgpId) & RS_NODE_PERM_ALLOW_PUSH))
{
std::list<RsPeerId> srcIds;
srcIds.push_back(mi->PeerId());
for(std::list<RsTlvFileItem>::const_iterator it(mi->attachment.items.begin());it!=mi->attachment.items.end();++it)
rsFiles->FileRequest((*it).name,(*it).hash,(*it).filesize,std::string(),RS_FILE_REQ_ANONYMOUS_ROUTING,srcIds) ;
}
}
bool p3MsgService::checkAndRebuildPartialMessage(RsMsgItem *ci)
{
// Check is the item is ending an incomplete item.
//
std::map<RsPeerId,RsMsgItem*>::iterator it = _pendingPartialIncomingMessages.find(ci->PeerId()) ;
bool ci_is_partial = ci->msgFlags & RS_MSG_FLAGS_PARTIAL ;
if(it != _pendingPartialIncomingMessages.end())
{
#ifdef MSG_DEBUG
std::cerr << "Pending message found. Appending it." << std::endl;
#endif
// Yes, there is. Append the item to ci.
ci->message = it->second->message + ci->message ;
ci->msgFlags |= it->second->msgFlags ;
delete it->second ;
if(!ci_is_partial)
_pendingPartialIncomingMessages.erase(it) ;
}
if(ci_is_partial)
{
#ifdef MSG_DEBUG
std::cerr << "Message is partial, storing for later." << std::endl;
#endif
// The item is a partial message. Push it, and wait for the rest.
//
_pendingPartialIncomingMessages[ci->PeerId()] = ci ;
return false ;
}
else
{
#ifdef MSG_DEBUG
std::cerr << "Message is complete, using it now." << std::endl;
#endif
return true ;
}
}
int p3MsgService::incomingMsgs() // direct node-to-node messages
{
RsMsgItem *mi;
int i = 0;
while((mi = (RsMsgItem *) recvItem()) != NULL)
{
handleIncomingItem(mi,
Rs::Mail::MsgAddress(mi->PeerId(), Rs::Mail::MsgAddress::MSG_ADDRESS_MODE_TO),
Rs::Mail::MsgAddress(mServiceCtrl->getOwnId(),Rs::Mail::MsgAddress::MSG_ADDRESS_MODE_TO));
++i ;
}
return i;
}
void p3MsgService::handleIncomingItem(RsMsgItem *mi,const Rs::Mail::MsgAddress& from,const Rs::Mail::MsgAddress& to)
{
// only returns true when a msg is complete.
if(checkAndRebuildPartialMessage(mi))
{
processIncomingMsg(mi,from,to);
delete mi;
}
}
void p3MsgService::statusChange(const std::list<pqiServicePeer> &plist)
{
/* should do it properly! */
/* only do this when a new peer is connected */
bool newPeers = false;
std::list<pqiServicePeer>::const_iterator it;
for(it = plist.begin(); it != plist.end(); ++it)
{
if (it->actions & RS_SERVICE_PEER_CONNECTED)
{
newPeers = true;
}
}
if (newPeers)
checkOutgoingMessages();
}
void p3MsgService::checkSizeAndSendMessage(RsMsgItem *msg,const RsPeerId& destination)
{
// We check the message item, and possibly split it into multiple messages, if the message is too big.
msg->PeerId(destination);
static const uint32_t MAX_STRING_SIZE = 15000 ;
std::cerr << "Msg is size " << msg->message.size() << std::endl;
while(msg->message.size() > MAX_STRING_SIZE)
{
// chop off the first 15000 wchars
RsMsgItem *item = new RsMsgItem(*msg) ;
item->message = item->message.substr(0,MAX_STRING_SIZE) ;
msg->message = msg->message.substr(MAX_STRING_SIZE,msg->message.size()-MAX_STRING_SIZE) ;
#ifdef DEBUG_DISTANT_MSG
std::cerr << " Chopped off msg of size " << item->message.size() << std::endl;
#endif
// Indicate that the message is to be continued.
//
item->msgFlags |= RS_MSG_FLAGS_PARTIAL ;
sendItem(item) ;
}
#ifdef DEBUG_DISTANT_MSG
std::cerr << " Chopped off msg of size " << msg->message.size() << std::endl;
#endif
sendItem(msg) ;
}
int p3MsgService::checkOutgoingMessages()
{
auto pEvent = std::make_shared<RsMailStatusEvent>();
pEvent->mMailStatusEventCode = RsMailStatusEventCode::MESSAGE_SENT;
{
RS_STACK_MUTEX(mMsgMtx); /********** STACK LOCKED MTX ******/
const RsPeerId& ownId = mServiceCtrl->getOwnId();
std::list<uint32_t>::iterator it;
std::list<uint32_t> toErase;
for(auto mit = msgOutgoing.begin();mit!= msgOutgoing.end();)
{
// 1 - find the original message this entry refers to.
auto message_data_identifier = mit->first;
auto sit = mSentMessages.find(message_data_identifier);
if(sit == mSentMessages.end())
{
RsErr() << "Cannot find original copy of message to be sent: id=" << message_data_identifier << ", removing all outgoing messages." ;
auto tmp = mit;
++tmp;
msgOutgoing.erase(mit);
mit = tmp;
continue;
}
// 2 - for each copy (i.e. destination), update the status, send, etc.
for(auto fit=mit->second.begin();fit!=mit->second.end();)
{
auto& minfo(fit->second); // MessageOutgoingInfo
MsgAddress to(minfo.destination);
MsgAddress from(minfo.origin);
if( to.type()==MsgAddress::MSG_ADDRESS_TYPE_RSPEERID )
{
if(to.toRsPeerId() == ownId || mServiceCtrl->isPeerConnected(getServiceInfo().mServiceType, to.toRsPeerId()) )
{
auto msg_item = createOutgoingMessageItem(*sit->second,to);
// Use the msg_id of the outgoing message copy.
msg_item->msgId = mit->first;
Dbg3() << __PRETTY_FUNCTION__ << " Sending out message" << std::endl;
checkSizeAndSendMessage(msg_item,to.toRsPeerId());
pEvent->mChangedMsgIds.insert(std::to_string(mit->first));
// now remove the entry
auto tmp = fit;
++tmp;
mit->second.erase(fit);
fit = tmp;
continue;
}
else
{
#ifdef DEBUG_DISTANT_MSG
Dbg3() << __PRETTY_FUNCTION__ << " Delaying until available..." << std::endl;
#endif
++fit;
continue;
}
}
else if( to.type()==MsgAddress::MSG_ADDRESS_TYPE_RSGXSID && !(minfo.flags & RS_MSG_FLAGS_ROUTED))
{
minfo.flags |= RS_MSG_FLAGS_ROUTED;
minfo.flags |= RS_MSG_FLAGS_DISTANT;
#ifdef DEBUG_DISTANT_MSG
RsDbg() << "Message id " << mit->first << " is distant: kept in outgoing, and marked as ROUTED" << std::endl;
#endif
Dbg3() << __PRETTY_FUNCTION__ << " Sending out message" << std::endl;
auto msg_item = createOutgoingMessageItem(*sit->second,to);
// Use the msg_id of the outgoing message copy.
msg_item->msgId = mit->first;
locked_sendDistantMsgItem(msg_item,from.toGxsId(),fit->first);
pEvent->mChangedMsgIds.insert(std::to_string(mit->first));
// Check if the msg is sent to ourselves. It happens that GRouter/GxsMail do not
// acknowledge receipt of these messages. If the msg is not routed, then it's received.
if(rsIdentity->isOwnId(to.toGxsId()))
{
auto tmp = fit;
++tmp;
mit->second.erase(fit);
fit = tmp;
continue;
}
else
++fit;
}
else
++fit;
}
// cleanup.
if(mit->second.empty())
{
sit->second->msg.msgFlags &= ~RS_MSG_FLAGS_PENDING;
auto tmp = mit;
++tmp;
msgOutgoing.erase(mit);
mit=tmp;
}
else
++mit;
}
}
if(rsEvents && !pEvent->mChangedMsgIds.empty())
rsEvents->postEvent(pEvent);
IndicateConfigChanged(RsConfigMgr::CheckPriority::SAVE_NOW);
return 0;
}
bool p3MsgService::saveList(bool& cleanup, std::list<RsItem*>& itemList)
{
RsMsgGRouterMap* gxsmailmap = new RsMsgGRouterMap;
{
RS_STACK_MUTEX(gxsOngoingMutex);
gxsmailmap->ongoing_msgs = gxsOngoingMessages;
}
itemList.push_front(gxsmailmap);
cleanup = true;
mMsgMtx.lock();
for(auto mit:mReceivedMessages) itemList.push_back(new RsMailStorageItem(*mit.second));
for(auto mit:mSentMessages) itemList.push_back(new RsMailStorageItem(*mit.second));
for(auto mit:mTrashMessages) itemList.push_back(new RsMailStorageItem(*mit.second));
for(auto mit:mDraftMessages) itemList.push_back(new RsMailStorageItem(*mit.second));
RsMsgOutgoingMapStorageItem *out_map_item = new RsMsgOutgoingMapStorageItem ;
out_map_item->outgoing_map = msgOutgoing;
itemList.push_back(out_map_item);
for(auto mit2:mTags)
itemList.push_back(new RsMsgTagType(*mit2.second));
RsMsgGRouterMap *grmap = new RsMsgGRouterMap ;
grmap->ongoing_msgs = _grouter_ongoing_messages ;
itemList.push_back(grmap) ;
RsMsgDistantMessagesHashMap *ghm = new RsMsgDistantMessagesHashMap;
{
RS_STACK_MUTEX(recentlyReceivedMutex);
ghm->hash_map = mRecentlyReceivedMessageHashes;
}
itemList.push_back(ghm);
RsConfigKeyValueSet *vitem = new RsConfigKeyValueSet ;
RsTlvKeyValue kv;
kv.key = "DISTANT_MESSAGES_ENABLED" ;
kv.value = mShouldEnableDistantMessaging?"YES":"NO" ;
vitem->tlvkvs.pairs.push_back(kv) ;
kv.key = "DISTANT_MESSAGE_PERMISSION_FLAGS" ;
kv.value = RsUtil::NumberToString(mDistantMessagePermissions) ;
vitem->tlvkvs.pairs.push_back(kv) ;
itemList.push_back(vitem);
return true;
}
void p3MsgService::saveDone()
{
// unlocks mutex which has been locked by savelist
mMsgMtx.unlock();
}
RsSerialiser* p3MsgService::setupSerialiser() // this serialiser is used for config. So it adds somemore info in the serialised items
{
RsSerialiser *rss = new RsSerialiser ;
rss->addSerialType(new RsMsgSerialiser(RsSerializationFlags::CONFIG));
rss->addSerialType(new RsGeneralConfigSerialiser());
return rss;
}
// build list of standard tag types
static void getStandardTagTypes(MsgTagType &tags)
{
/* create standard tag types, the text must be translated in the GUI */
tags.types [RS_MSGTAGTYPE_IMPORTANT] = std::pair<std::string, uint32_t> ("Important", 0xFF0000);
tags.types [RS_MSGTAGTYPE_WORK] = std::pair<std::string, uint32_t> ("Work", 0xFF9900);
tags.types [RS_MSGTAGTYPE_PERSONAL] = std::pair<std::string, uint32_t> ("Personal", 0x009900);
tags.types [RS_MSGTAGTYPE_TODO] = std::pair<std::string, uint32_t> ("Todo", 0x3333FF);
tags.types [RS_MSGTAGTYPE_LATER] = std::pair<std::string, uint32_t> ("Later", 0x993399);
}
// Initialize the standard tag types after load
void p3MsgService::initStandardTagTypes()
{
bool bChanged = false;
const RsPeerId& ownId = mServiceCtrl->getOwnId();
MsgTagType tags;
getStandardTagTypes(tags);
std::map<uint32_t, std::pair<std::string, uint32_t> >::iterator tit;
for (tit = tags.types.begin(); tit != tags.types.end(); ++tit) {
std::map<uint32_t, RsMsgTagType*>::iterator mit = mTags.find(tit->first);
if (mit == mTags.end()) {
RsMsgTagType* tagType = new RsMsgTagType();
tagType->PeerId (ownId);
tagType->tagId = tit->first;
tagType->text = tit->second.first;
tagType->rgb_color = tit->second.second;
mTags.insert(std::pair<uint32_t, RsMsgTagType*>(tit->first, tagType));
bChanged = true;
}
}
if (bChanged) {
IndicateConfigChanged(RsConfigMgr::CheckPriority::SAVE_NOW); /**** INDICATE MSG CONFIG CHANGED! *****/
}
}
bool p3MsgService::parseList_backwardCompatibility(std::list<RsItem*>& load)
{
if(!load.empty())
RsInfo() << "p3MsgService: Loading messages with old format. " ;
// 1 - load all old-format data pieces
std::map<uint32_t,RsMailStorageItem*> msg_map;
std::list<RsMsgTags *> msg_tags;
std::list<RsMsgSrcId *> msg_srcids;
std::list<RsMsgParentId *> msg_parentids;
for(auto it:load)
{
RsMsgTags* mti;
RsMsgSrcId* msi;
RsMsgParentId* msp;
RsMsgItem *mitem;
if (nullptr != (mitem = dynamic_cast<RsMsgItem *>(it)))
{
auto msi = new RsMailStorageItem();
msi->msg = *mitem;
msg_map[mitem->msgId] = msi;
}
else if(nullptr != (mti = dynamic_cast<RsMsgTags *>(it)))
msg_tags.push_back(mti);
else if(nullptr != (msi = dynamic_cast<RsMsgSrcId *>(it)))
msg_srcids.push_back(msi);
else if(nullptr != (msp = dynamic_cast<RsMsgParentId *>(it)))
msg_parentids.push_back(msp);
}
RsInfo() << " Current Msg map:" ;
for(auto m:msg_map)
RsInfo() << " id=" << m.first << " pointer=" << m.second ;
// 2 - process all tags and set them to the proper message
for(auto ptag:msg_tags)
{
auto mit = msg_map.find(ptag->msgId);
std::string tagstr;
for(auto t:ptag->tagIds) tagstr += std::to_string(t) + ",";
if(!tagstr.empty())
tagstr.pop_back();
if(mit == msg_map.end())
{
RsErr() << "Found message tag (msg=" << ptag->msgId << ", tag=" << tagstr << ") that belongs to no specific message";
continue;
}
RsInfo() << " Loading msg tag pair (msg=" << ptag->msgId << ", tag=" << tagstr << ")" ;
mit->second->tagIds = std::set<uint32_t>(ptag->tagIds.begin(),ptag->tagIds.end());
}
// 3 - process all parent ids and set them to the proper message
for(auto pparent:msg_parentids)
{
auto mit = msg_map.find(pparent->msgId);
if(mit == msg_map.end())
{
RsErr() << "Found message parent (msg=" << pparent->msgId << ", parent=" << pparent->msgParentId << ") that belongs to no specific message";
continue;
}
auto mit2 = msg_map.find(pparent->msgParentId);
if(mit2 == msg_map.end())
{
RsErr() << "Found message parent (msg=" << pparent->msgId << ", parent=" << pparent->msgParentId << ") that refers to an unknown parent message";
continue;
}
RsInfo() << " Loading parent id pair (msg=" << pparent->msgId << ", parent=" << pparent->msgParentId << ") ";
mit->second->parentId = pparent->msgParentId;
}
// 3 - process all parent ids and set them to the proper message
for(auto psrc:msg_srcids)
{
auto mit = msg_map.find(psrc->msgId);
if(mit == msg_map.end())
{
RsErr() << "Found message parent (msg=" << psrc->msgId << ", src_id=" << psrc->srcId << ") that belongs to no specific message";
continue;
}
RsErr() << " Loaded msg source pair (msg=" << psrc->msgId << ", src_id=" << psrc->srcId << ")";
if(mit->second->msg.msgFlags & RS_MSG_FLAGS_DISTANT)
mit->second->from = Rs::Mail::MsgAddress(RsGxsId(psrc->srcId),Rs::Mail::MsgAddress::MSG_ADDRESS_MODE_TO);
else
mit->second->from = Rs::Mail::MsgAddress(psrc->srcId,Rs::Mail::MsgAddress::MSG_ADDRESS_MODE_TO);
}
// 4 - store each message in the appropriate map.
std::list<RsMailStorageItem*> pending_msg;
for(auto mit:msg_map)
{
// Early detect "outgoing" list, and keep them for later.
if (mit.second->msg.msgFlags & RS_MSG_FLAGS_PENDING)
{
RsInfo() << "Ignoring pending message " << mit.first << " as the destination of pending msgs is not saved in old format.";
continue;
}
// Fix up destination. Try to guess it, as it wasn't actually stored originally.
if(mit.second->msg.msgFlags & RS_MSG_FLAGS_DISTANT)
{
for(auto d:mit.second->msg.rsgxsid_msgto.ids)
if(rsIdentity->isOwnId(d))
{
mit.second->to = MsgAddress(d,Rs::Mail::MsgAddress::MSG_ADDRESS_MODE_TO);
break;
}
for(auto d:mit.second->msg.rsgxsid_msgcc.ids)
if(rsIdentity->isOwnId(d))
{
mit.second->to = MsgAddress(d,Rs::Mail::MsgAddress::MSG_ADDRESS_MODE_CC);
break;
}
for(auto d:mit.second->msg.rsgxsid_msgbcc.ids)
if(rsIdentity->isOwnId(d))
{
mit.second->to = MsgAddress(d,Rs::Mail::MsgAddress::MSG_ADDRESS_MODE_BCC);
break;
}
}
else
{
if(mit.second->msg.rspeerid_msgto.ids.find(rsPeers->getOwnId()) != mit.second->msg.rspeerid_msgto.ids.end())
mit.second->to = MsgAddress(rsPeers->getOwnId(),Rs::Mail::MsgAddress::MSG_ADDRESS_MODE_TO);
else if(mit.second->msg.rspeerid_msgcc.ids.find(rsPeers->getOwnId()) != mit.second->msg.rspeerid_msgcc.ids.end())
mit.second->to = MsgAddress(rsPeers->getOwnId(),Rs::Mail::MsgAddress::MSG_ADDRESS_MODE_CC);
else
mit.second->to = MsgAddress(rsPeers->getOwnId(),Rs::Mail::MsgAddress::MSG_ADDRESS_MODE_BCC);
}
RsInfo() << " Storing message " << mit.first << ", possible destination: " << mit.second->to << ", MsgFlags: " << std::hex << mit.second->msg.msgFlags << std::dec ;
if(mit.second->msg.msgFlags & RS_MSG_FLAGS_TRASH)
mTrashMessages.insert(mit);
else if (mit.second->msg.msgFlags & RS_MSG_FLAGS_DRAFT)
mDraftMessages.insert(mit);
else if (mit.second->msg.msgFlags & RS_MSG_FLAGS_OUTGOING)
mSentMessages.insert(mit);
else
mReceivedMessages.insert(mit);
}
return true;
}
bool p3MsgService::loadList(std::list<RsItem*>& load)
{
RS_STACK_MUTEX(mMsgMtx); // lock ere, because we need to load, then check for duplicates, and this needs to be done in the same lock.
auto gxsmIt = load.begin();
RsMsgGRouterMap* gxsmailmap = dynamic_cast<RsMsgGRouterMap*>(*gxsmIt);
if(gxsmailmap)
{
{
RS_STACK_MUTEX(gxsOngoingMutex);
gxsOngoingMessages = gxsmailmap->ongoing_msgs;
}
delete *gxsmIt; load.erase(gxsmIt);
}
std::list<RsItem*> unhandled_items;
// load items and calculate next unique msgId
for(auto it = load.begin(); it != load.end(); ++it)
{
RsConfigKeyValueSet *vitem = nullptr ;
RsMsgTagType* mtt;
RsMsgGRouterMap* grm;
RsMsgDistantMessagesHashMap *ghm;
RsMailStorageItem *msi;
RsMsgOutgoingMapStorageItem *mom;
if (NULL != (grm = dynamic_cast<RsMsgGRouterMap *>(*it)))
{
typedef std::map<GRouterMsgPropagationId,uint32_t> tT;
for( tT::const_iterator bit = grm->ongoing_msgs.begin(); bit != grm->ongoing_msgs.end(); ++bit )
_grouter_ongoing_messages.insert(*bit);
delete *it;
}
else if(NULL != (ghm = dynamic_cast<RsMsgDistantMessagesHashMap*>(*it)))
{
{
RS_STACK_MUTEX(recentlyReceivedMutex);
mRecentlyReceivedMessageHashes = ghm->hash_map;
}
#ifdef DEBUG_DISTANT_MSG
std::cerr << " loaded recently received message map: " << std::endl;
for(std::map<Sha1CheckSum,uint32_t>::const_iterator it(mRecentlyReceivedMessageHashes.begin());it!=mRecentlyReceivedMessageHashes.end();++it)
std::cerr << " " << it->first << " received " << time(NULL)-it->second << " secs ago." << std::endl;
#endif
delete *it;
}
else if(NULL != (mtt = dynamic_cast<RsMsgTagType *>(*it)))
{
// delete standard tags as they are now save in config
std::map<uint32_t,RsMsgTagType*>::const_iterator tagIt;
if(mTags.end() == (tagIt = mTags.find(mtt->tagId)))
mTags.insert(std::pair<uint32_t, RsMsgTagType* >(mtt->tagId, mtt));
else
{
delete mTags[mtt->tagId];
mTags.erase(tagIt);
mTags.insert(std::pair<uint32_t, RsMsgTagType* >(mtt->tagId, mtt));
}
// no delete here because the item is stored.
}
else if(NULL != (vitem = dynamic_cast<RsConfigKeyValueSet*>(*it)))
{
for(std::list<RsTlvKeyValue>::const_iterator kit = vitem->tlvkvs.pairs.begin(); kit != vitem->tlvkvs.pairs.end(); ++kit)
{
if(kit->key == "DISTANT_MESSAGES_ENABLED")
{
#ifdef MSG_DEBUG
std::cerr << "Loaded config default nick name for distant chat: " << kit->value << std::endl ;
#endif
mShouldEnableDistantMessaging = (kit->value == "YES") ;
}
if(kit->key == "DISTANT_MESSAGE_PERMISSION_FLAGS")
{
#ifdef MSG_DEBUG
std::cerr << "Loaded distant message permission flags: " << kit->value << std::endl ;
#endif
if (!kit->value.empty())
{
std::istringstream is(kit->value) ;
uint32_t tmp ;
is >> tmp ;
if(tmp < 3)
mDistantMessagePermissions = tmp ;
else
std::cerr << "(EE) Invalid value read for DistantMessagePermission flags in config: " << tmp << std::endl;
}
}
}
delete *it;
}
else if(nullptr != (msi = dynamic_cast<RsMailStorageItem*>(*it)))
{
RsErr() << "Loaded msg with msg.to=" << msi->to ;
/* STORE MsgID */
if (msi->msg.msgId != 0)
{
/* switch depending on the PENDING
* flags
*/
if (msi->msg.msgFlags & RS_MSG_FLAGS_TRASH)
mTrashMessages[msi->msg.msgId] = msi;
else if (msi->msg.msgFlags & RS_MSG_FLAGS_OUTGOING)
mSentMessages[msi->msg.msgId] = msi;
else if (msi->msg.msgFlags & RS_MSG_FLAGS_DRAFT)
mDraftMessages[msi->msg.msgId] = msi;
else
mReceivedMessages[msi->msg.msgId] = msi;
}
else
{
RsErr() << "Found Message item without an ID. This is an error. Item will be dropped." ;
delete *it;
}
// no delete here because the item is stored.
}
else if(nullptr != (mom = dynamic_cast<RsMsgOutgoingMapStorageItem*>(*it)))
{
msgOutgoing = mom->outgoing_map;
delete *it;
}
else
unhandled_items.push_back(*it);
}
parseList_backwardCompatibility(unhandled_items);
// clean up
for(auto m:unhandled_items)
delete m;
load.clear();
#ifdef MSG_DEBUG
// list all the msg Ids
auto print_msgids = [](const std::map<uint32_t,RsMailStorageItem*>& mp,const std::string& name) {
std::cerr << "Message ids in box " << name << " : " << std::endl;
for(auto it:mp)
std::cerr << " " << it.first << " " << it.second->msg.msgId << std::endl;
};
print_msgids(mSentMessages,"Sent");
print_msgids(mTrashMessages,"Trash");
print_msgids(mDraftMessages,"Drafts");
print_msgids(mReceivedMessages,"Received");
std::cerr << "Outgoing messages: " << std::endl;
for(auto m:msgOutgoing)
{
std::cerr << " parent " << m.first << " : " << std::endl;
for(auto p:m.second)
std::cerr << " " << p.first << std::endl;
}
#endif
// This was added on Sept 20, 2024. It is here to fix errors following a bug that caused duplication of
// some message ids. This should be kept because it also creates the list that is stored in mAllMessageIds,
// that is further used by getNewUniqueId() to create unique message Ids in a more robust way than before.
locked_checkForDuplicates();
return true;
}
// Two generic methods to replace elements in a map, when the first (resp. second) element matches an id to substitute.
template<class T> void replace_first(std::map<uint32_t,T>& mp,uint32_t old_id,uint32_t new_id)
{
auto tt = mp.find(old_id);
if(tt == mp.end())
return;
auto sec = tt->second;
mp.erase(tt);
mp[new_id] = sec;
}
template<class T> void replace_second(std::map<T,uint32_t>& mp,uint32_t old_id,uint32_t new_id)
{
for(auto& it:mp)
if(it.second == old_id)
it.second = new_id;
}
void p3MsgService::locked_checkForDuplicates()
{
std::set<uint32_t> already_known_ids;
std::set<RsMailMessageId> changed_msg_ids;
auto replace_parent = [](std::map<uint32_t,RsMailStorageItem*>& mp,uint32_t old_id,uint32_t new_id)
{
for(auto& it:mp)
if(it.second->parentId == old_id)
{
RsWarn() << "Replacing parent ID " << old_id << " of message " << it.first << " with new parent " << new_id << std::endl;
it.second->parentId = new_id;
}