updated to upstream/master

This commit is contained in:
csoler 2016-01-13 20:27:08 -05:00
commit fd04f0b3bb
1804 changed files with 1568 additions and 745 deletions

View file

@ -202,7 +202,7 @@ bool DistributedChatService::handleRecvChatLobbyMsgItem(RsChatMsgItem *ci)
//name = cli->nick;
//popupChatFlag = RS_POPUP_CHATLOBBY;
RsServer::notify()->AddPopupMessage(RS_POPUP_CHATLOBBY, virtual_peer_id.toStdString(), cli->signature.keyId.toStdString(), cli->message); /* notify private chat message */
RsServer::notify()->AddPopupMessage(RS_POPUP_CHATLOBBY, ChatId(cli->lobby_id).toStdString(), cli->signature.keyId.toStdString(), cli->message); /* notify private chat message */
return true ;
}
@ -319,11 +319,6 @@ void DistributedChatService::locked_printDebugInfo() const
}
std::cerr << "Recorded lobby names: " << std::endl;
for( std::map<RsPeerId,ChatLobbyId>::const_iterator it(_lobby_ids.begin()) ;it!=_lobby_ids.end();++it)
std::cerr << " \"" << it->first << "\" id = " << std::hex << it->second << std::dec << std::endl;
std::cerr << "Visible public lobbies: " << std::endl;
for( std::map<ChatLobbyId,VisibleChatLobbyRecord>::const_iterator it(_visible_lobbies.begin()) ;it!=_visible_lobbies.end();++it)
@ -339,21 +334,6 @@ void DistributedChatService::locked_printDebugInfo() const
std::cerr << " \"" << std::hex << it->first << "\" flags = " << it->second << std::dec << std::endl;
}
bool DistributedChatService::isLobbyId(const RsPeerId& virtual_peer_id,ChatLobbyId& lobby_id)
{
RsStackMutex stack(mDistributedChatMtx); /********** STACK LOCKED MTX ******/
std::map<ChatLobbyVirtualPeerId,ChatLobbyId>::const_iterator it(_lobby_ids.find(virtual_peer_id)) ;
if(it != _lobby_ids.end())
{
lobby_id = it->second ;
return true ;
}
lobby_id = 0;
return false ;
}
bool DistributedChatService::locked_bouncingObjectCheck(RsChatLobbyBouncingObject *obj,const RsPeerId& peer_id,uint32_t lobby_count)
{
static std::map<std::string, std::list<time_t> > message_counts ;
@ -1368,7 +1348,6 @@ bool DistributedChatService::acceptLobbyInvite(const ChatLobbyId& lobby_id,const
entry.last_connexion_challenge_time = now ;
entry.last_keep_alive_packet_time = now ;
_lobby_ids[entry.virtual_peer_id] = lobby_id ;
_chat_lobbys[lobby_id] = entry ;
_lobby_invites_queue.erase(it) ; // remove the invite from cache.
@ -1487,8 +1466,6 @@ bool DistributedChatService::joinVisibleChatLobby(const ChatLobbyId& lobby_id,co
entry.last_connexion_challenge_time = now ;
entry.last_keep_alive_packet_time = now ;
_lobby_ids[entry.virtual_peer_id] = lobby_id ;
for(std::set<RsPeerId>::const_iterator it2(it->second.participating_friends.begin());it2!=it->second.participating_friends.end();++it2)
{
invited_friends.push_back(*it2) ;
@ -1537,7 +1514,6 @@ ChatLobbyId DistributedChatService::createChatLobby(const std::string& lobby_nam
entry.last_connexion_challenge_time = now ;
entry.last_keep_alive_packet_time = now ;
_lobby_ids[entry.virtual_peer_id] = lobby_id ;
_chat_lobbys[lobby_id] = entry ;
}
@ -1619,13 +1595,6 @@ void DistributedChatService::unsubscribeChatLobby(const ChatLobbyId& id)
// remove lobby information
_chat_lobbys.erase(it) ;
for(std::map<ChatLobbyVirtualPeerId,ChatLobbyId>::iterator it2(_lobby_ids.begin());it2!=_lobby_ids.end();++it2)
if(it2->second == id)
{
_lobby_ids.erase(it2) ;
break ;
}
}
RsServer::notify()->notifyListChange(NOTIFY_LIST_CHAT_LOBBY_LIST, NOTIFY_TYPE_DEL) ;

View file

@ -60,7 +60,6 @@ class DistributedChatService
// Interface part to communicate with
//
bool getVirtualPeerId(const ChatLobbyId& lobby_id, RsPeerId& virtual_peer_id) ;
bool isLobbyId(const RsPeerId& virtual_peer_id, ChatLobbyId& lobby_id) ;
void getChatLobbyList(std::list<ChatLobbyId>& clids) ;
bool getChatLobbyInfo(const ChatLobbyId& id,ChatLobbyInfo& clinfo) ;
bool acceptLobbyInvite(const ChatLobbyId& id,const RsGxsId& identity) ;
@ -149,7 +148,6 @@ class DistributedChatService
std::map<ChatLobbyId,ChatLobbyEntry> _chat_lobbys ;
std::map<ChatLobbyId,ChatLobbyInvite> _lobby_invites_queue ;
std::map<ChatLobbyId,VisibleChatLobbyRecord> _visible_lobbies ;
std::map<ChatLobbyVirtualPeerId,ChatLobbyId> _lobby_ids ;
std::map<ChatLobbyId,ChatLobbyFlags> _known_lobbies_flags ; // flags for all lobbies, including the ones that are not known. So we can't
std::map<ChatLobbyId,std::vector<RsChatLobbyMsgItem*> > _pendingPartialLobbyMessages ; // store them in _chat_lobbies (subscribed lobbies) nor _visible_lobbies.
// Known flags:

View file

@ -29,6 +29,7 @@
#include "rsserver/p3face.h"
#include "dbase/fimonitor.h"
#include "util/rsdir.h"
#include "util/rsmemory.h"
#include "pqi/authssl.h"
#include "serialiser/rsserviceids.h"
#include "retroshare/rsiface.h"
@ -128,13 +129,11 @@ HashCache::HashCache(const std::string& path)
// read the binary stream into memory.
//
void *buffer = malloc(file_size) ;
void *buffer = rs_malloc(file_size) ;
if(buffer == NULL)
{
std::cerr << "Cannot allocate memory for reading encrypted file cache, bytes=" << file_size << std::endl;
return ;
}
FILE *F = fopen( (_path+".bin").c_str(),"rb") ;
if (!F)
{

View file

@ -39,6 +39,7 @@
#include "util/rsstring.h"
#endif
#include "util/rsdiscspace.h"
#include "util/rsmemory.h"
#include "ft/ftcontroller.h"
@ -747,8 +748,14 @@ bool ftController::copyFile(const std::string& source,const std::string& dest)
size_t T=0;
static const int BUFF_SIZE = 10485760 ; // 10 MB buffer to speed things up.
void *buffer = malloc(BUFF_SIZE) ;
void *buffer = rs_malloc(BUFF_SIZE) ;
if(buffer == NULL)
{
fclose (in);
fclose (out);
return false ;
}
bool bRet = true;
while( (s = fread(buffer,1,BUFF_SIZE,in)) > 0)

View file

@ -35,6 +35,7 @@
#include "ft/ftfileprovider.h"
#include "ft/ftsearch.h"
#include "util/rsdir.h"
#include "util/rsmemory.h"
#include <retroshare/rsturtle.h>
#include <time.h>
@ -878,13 +879,11 @@ bool ftDataMultiplex::locked_handleServerRequest(ftFileProvider *provider, const
std::cerr << "Warning: peer " << peerId << " is asking a large chunk (s=" << chunksize << ") for hash " << hash << ", filesize=" << size << ". This is unexpected." << std::endl ;
return false ;
}
void *data = malloc(chunksize);
void *data = rs_malloc(chunksize);
if(data == NULL)
{
std::cerr << "WARNING: Could not allocate data for a chunksize of " << chunksize << std::endl ;
return false ;
}
#ifdef MPLEX_DEBUG
std::cerr << "ftDataMultiplex::locked_handleServerRequest()";
std::cerr << "\t peer: " << peerId << " hash: " << hash;

View file

@ -465,6 +465,8 @@ RsTurtleGenericTunnelItem *ftServer::deserialiseItem(void *data,uint32_t size) c
return NULL; /* wrong type */
}
try
{
switch(getRsItemSubType(rstype))
{
case RS_TURTLE_SUBTYPE_FILE_REQUEST : return new RsTurtleFileRequestItem(data,size) ;
@ -477,6 +479,13 @@ RsTurtleGenericTunnelItem *ftServer::deserialiseItem(void *data,uint32_t size) c
default:
return NULL ;
}
}
catch(std::exception& e)
{
std::cerr << "(EE) deserialisation error in " << __PRETTY_FUNCTION__ << ": " << e.what() << std::endl;
return NULL ;
}
}
void ftServer::addVirtualPeer(const TurtleFileHash& hash,const TurtleVirtualPeerId& virtual_peer_id,RsTurtleGenericTunnelItem::Direction dir)
@ -1093,11 +1102,10 @@ bool ftServer::sendData(const RsPeerId& peerId, const RsFileHash& hash, uint64_t
item->chunk_offset = offset+baseoffset ;
item->chunk_size = chunk;
item->chunk_data = malloc(chunk) ;
item->chunk_data = rs_malloc(chunk) ;
if(item->chunk_data == NULL)
{
std::cerr << "p3turtle: Warning: failed malloc of " << chunk << " bytes for sending data packet." << std::endl ;
delete item;
return false;
}

View file

@ -26,6 +26,7 @@
#include <iostream>
#include <stdexcept>
#include <util/rsmemory.h>
#include <serialiser/itempriorities.h>
#include <ft/ftturtlefiletransferitem.h>
@ -422,14 +423,24 @@ RsTurtleFileDataItem::RsTurtleFileDataItem(void *data,uint32_t pktsize)
uint32_t offset = 8; // skip the header
uint32_t rssize = getRsItemSize(data);
/* add mandatory parts first */
bool ok = true ;
if(rssize > pktsize)
ok = false ;
/* add mandatory parts first */
ok &= getRawUInt32(data, pktsize, &offset, &tunnel_id) ;
ok &= getRawUInt64(data, pktsize, &offset, &chunk_offset);
ok &= getRawUInt32(data, pktsize, &offset, &chunk_size);
chunk_data = (void*)malloc(chunk_size) ;
if(chunk_size > rssize || rssize - chunk_size < offset)
throw std::runtime_error("RsTurtleFileDataItem::() error while deserializing.") ;
chunk_data = (void*)rs_malloc(chunk_size) ;
if(chunk_data == NULL)
throw std::runtime_error("RsTurtleFileDataItem::() cannot allocate memory.") ;
memcpy(chunk_data,(void*)((unsigned char*)data+offset),chunk_size) ;
offset += chunk_size ;

View file

@ -66,6 +66,12 @@ RsGRouterTransactionChunkItem *RsGRouterSerialiser::deserialise_RsGRouterTransac
uint32_t rssize = getRsItemSize(data);
bool ok = true ;
if(tlvsize < rssize)
{
std::cerr << __PRETTY_FUNCTION__ << ": wrong encoding of item size. Serialisation error!" << std::endl;
return NULL ;
}
RsGRouterTransactionChunkItem *item = new RsGRouterTransactionChunkItem() ;
/* add mandatory parts first */
@ -74,15 +80,14 @@ RsGRouterTransactionChunkItem *RsGRouterSerialiser::deserialise_RsGRouterTransac
ok &= getRawUInt32(data, tlvsize, &offset, &item->chunk_size);
ok &= getRawUInt32(data, tlvsize, &offset, &item->total_size);
if( NULL == (item->chunk_data = (uint8_t*)malloc(item->chunk_size)))
if(item->chunk_size > rssize || offset > rssize - item->chunk_size) // better than if(item->chunk_size + offset > rssize)
{
std::cerr << __PRETTY_FUNCTION__ << ": Cannot allocate memory for chunk " << item->chunk_size << std::endl;
std::cerr << __PRETTY_FUNCTION__ << ": Cannot read beyond item size. Serialisation error!" << std::endl;
delete item;
return NULL ;
}
if(item->chunk_size + offset > rssize)
if( NULL == (item->chunk_data = (uint8_t*)rs_malloc(item->chunk_size)))
{
std::cerr << __PRETTY_FUNCTION__ << ": Cannot read beyond item size. Serialisation error!" << std::endl;
delete item;
return NULL ;
}
@ -125,36 +130,40 @@ RsGRouterGenericDataItem *RsGRouterSerialiser::deserialise_RsGRouterGenericDataI
uint32_t rssize = getRsItemSize(data);
bool ok = true ;
if(pktsize < rssize)
{
std::cerr << __PRETTY_FUNCTION__ << ": wrong encoding of item size. Serialisation error!" << std::endl;
return NULL ;
}
RsGRouterGenericDataItem *item = new RsGRouterGenericDataItem() ;
ok &= getRawUInt64(data, pktsize, &offset, &item->routing_id);
ok &= item->destination_key.deserialise(data, pktsize, offset) ;
ok &= getRawUInt32(data, pktsize, &offset, &item->service_id);
ok &= getRawUInt32(data, pktsize, &offset, &item->data_size);
ok &= getRawUInt32(data, pktsize, &offset, &item->service_id);
ok &= getRawUInt32(data, pktsize, &offset, &item->data_size);
if( NULL == (item->data_bytes = (uint8_t*)malloc(item->data_size)))
if(item->data_size > rssize || offset > rssize - item->data_size) // better than if(item->data_size + offset > rssize)
{
std::cerr << __PRETTY_FUNCTION__ << ": Cannot allocate memory for chunk " << item->data_size << std::endl;
std::cerr << __PRETTY_FUNCTION__ << ": Cannot read beyond item size. Serialisation error!" << std::endl;
delete item;
return NULL ;
}
if(item->data_size + offset > rssize)
{
std::cerr << __PRETTY_FUNCTION__ << ": Cannot read beyond item size. Serialisation error!" << std::endl;
delete item;
return NULL ;
}
if( NULL == (item->data_bytes = (uint8_t*)rs_malloc(item->data_size)))
{
delete item;
return NULL ;
}
memcpy(item->data_bytes,&((uint8_t*)data)[offset],item->data_size) ;
memcpy(item->data_bytes,&((uint8_t*)data)[offset],item->data_size) ;
offset += item->data_size ;
ok &= item->signature.GetTlv(data, pktsize, &offset) ;
ok &= item->signature.GetTlv(data, pktsize, &offset) ;
ok &= getRawUInt32(data, pktsize, &offset, &item->randomized_distance);
ok &= getRawUInt32(data, pktsize, &offset, &item->flags);
ok &= getRawUInt32(data, pktsize, &offset, &item->randomized_distance);
ok &= getRawUInt32(data, pktsize, &offset, &item->flags);
if (offset != rssize || !ok)
if (offset != rssize || !ok)
{
std::cerr << __PRETTY_FUNCTION__ << ": error while deserialising! Item will be dropped." << std::endl;
delete item;
@ -337,8 +346,19 @@ RsGRouterGenericDataItem *RsGRouterGenericDataItem::duplicate() const
// then duplicate the memory chunk
item->data_bytes = (uint8_t*)malloc(data_size) ;
memcpy(item->data_bytes,data_bytes,data_size) ;
if(data_size > 0)
{
item->data_bytes = (uint8_t*)rs_malloc(data_size) ;
if(item->data_bytes == NULL)
{
delete item ;
return NULL ;
}
memcpy(item->data_bytes,data_bytes,data_size) ;
}
else
item->data_bytes = NULL ;
return item ;
}

View file

@ -25,6 +25,8 @@
#pragma once
#include "util/rsmemory.h"
#include "serialiser/rsserial.h"
#include "serialiser/rstlvkeys.h"
#include "serialiser/rsserviceids.h"
@ -194,7 +196,11 @@ class RsGRouterTransactionChunkItem: public RsGRouterTransactionItem, public RsG
{
RsGRouterTransactionChunkItem *item = new RsGRouterTransactionChunkItem ;
*item = *this ; // copy all fields
item->chunk_data = (uint8_t*)malloc(chunk_size) ; // deep copy memory chunk
item->chunk_data = (uint8_t*)rs_malloc(chunk_size) ; // deep copy memory chunk
if(item->chunk_data == NULL)
return NULL ;
memcpy(item->chunk_data,chunk_data,chunk_size) ;
return item ;
}

View file

@ -1121,13 +1121,11 @@ bool p3GRouter::locked_sendTransactionData(const RsPeerId& pid,const RsGRouterTr
std::cerr << " sending to tunnel vpid " << pid << std::endl;
#endif
uint32_t turtle_data_size = trans_item.serial_size() ;
uint8_t *turtle_data = (uint8_t*)malloc(turtle_data_size) ;
uint8_t *turtle_data = (uint8_t*)rs_malloc(turtle_data_size) ;
if(turtle_data == NULL)
{
std::cerr << " ERROR: Cannot allocate turtle data memory for size " << turtle_data_size << std::endl;
return false ;
}
if(!trans_item.serialise(turtle_data,turtle_data_size))
{
std::cerr << " ERROR: cannot serialise RsGRouterTransactionChunkItem." << std::endl;
@ -1184,16 +1182,18 @@ void p3GRouter::autoWash()
#ifdef GROUTER_DEBUG
grouter_debug() << " Removing cached item " << std::hex << it->first << std::dec << std::endl;
#endif
GRouterClientService *client = NULL ;
GRouterServiceId service_id = 0;
//GRouterClientService *client = NULL ;
//GRouterServiceId service_id = 0;
if( it->second.data_status != RS_GROUTER_DATA_STATUS_DONE )
{
if(!locked_getClientAndServiceId(it->second.tunnel_hash,it->second.data_item->destination_key,client,service_id))
std::cerr << " ERROR: cannot find client for cancelled message " << it->first << std::endl;
else
failed_msgs[it->first] = client;
}
{
GRouterClientService *client = NULL;
if(locked_getLocallyRegisteredClientFromServiceId(it->second.client_id,client))
failed_msgs[it->first] = client ;
else
std::cerr << " ERROR: client id " << it->second.client_id << " not registered. Consistency error." << std::endl;
}
delete it->second.data_item ;
@ -1302,14 +1302,13 @@ bool p3GRouter::sliceDataItem(RsGRouterAbstractMsgItem *item,std::list<RsGRouter
chunk_item->total_size = size;
chunk_item->chunk_start= offset;
chunk_item->chunk_size = chunk_size ;
chunk_item->chunk_data = (uint8_t*)malloc(chunk_size) ;
chunk_item->chunk_data = (uint8_t*)rs_malloc(chunk_size) ;
#ifdef GROUTER_DEBUG
std::cerr << " preparing to send a chunk [" << offset << " -> " << offset + chunk_size << " / " << size << "]" << std::endl;
#endif
if(chunk_item->chunk_data == NULL)
{
std::cerr << " ERROR: Cannot allocate memory for size " << chunk_size << std::endl;
delete chunk_item;
throw ;
}
@ -1411,7 +1410,7 @@ void p3GRouter::handleIncomingReceiptItem(RsGRouterSignedReceiptItem *receipt_it
#endif
it->second.data_status = RS_GROUTER_DATA_STATUS_DONE;
if(locked_getClientAndServiceId(it->second.tunnel_hash,it->second.data_item->destination_key,client_service,service_id))
if(locked_getLocallyRegisteredClientFromServiceId(it->second.client_id,client_service))
mid = it->first ;
else
{
@ -1604,6 +1603,7 @@ void p3GRouter::handleIncomingDataItem(RsGRouterGenericDataItem *data_item)
info.receipt_item = receipt_item ; // inited before, or NULL.
info.tunnel_status = RS_GROUTER_TUNNEL_STATUS_UNMANAGED ;
info.last_sent_TS = 0 ;
info.client_id = data_item->service_id ;
info.item_hash = item_hash ;
info.last_tunnel_request_TS = 0 ;
info.sending_attempts = 0 ;
@ -1680,26 +1680,10 @@ void p3GRouter::handleIncomingDataItem(RsGRouterGenericDataItem *data_item)
IndicateConfigChanged() ;
}
bool p3GRouter::locked_getClientAndServiceId(const TurtleFileHash& hash, const RsGxsId& destination_key, GRouterClientService *& client, GRouterServiceId& service_id)
bool p3GRouter::locked_getLocallyRegisteredClientFromServiceId(const GRouterServiceId& service_id,GRouterClientService *& client)
{
client = NULL ;
service_id = 0;
RsGxsId gxs_id ;
if(!locked_getGxsIdAndClientId(hash,gxs_id,service_id))
{
std::cerr << " p3GRouter::ERROR: locked_getGxsIdAndClientId(): no key registered for hash " << hash << std::endl;
return false ;
}
if(gxs_id != destination_key)
{
std::cerr << " ERROR: verification (destination) GXS key " << destination_key << " does not match key from hash " << gxs_id << std::endl;
return false;
}
// now find the client given its id.
std::map<GRouterServiceId,GRouterClientService*>::const_iterator its = _registered_services.find(service_id) ;
if(its == _registered_services.end())
@ -1934,7 +1918,11 @@ bool p3GRouter::sendData(const RsGxsId& destination,const GRouterServiceId& clie
RsGRouterGenericDataItem *data_item = new RsGRouterGenericDataItem ;
data_item->data_bytes = (uint8_t*)malloc(data_size) ;
data_item->data_bytes = (uint8_t*)rs_malloc(data_size) ;
if(data_item->data_bytes == NULL)
return false ;
memcpy(data_item->data_bytes,data,data_size) ;
data_item->data_size = data_size ;
@ -1981,6 +1969,7 @@ bool p3GRouter::sendData(const RsGxsId& destination,const GRouterServiceId& clie
info.data_status = RS_GROUTER_DATA_STATUS_PENDING ;
info.tunnel_status = RS_GROUTER_TUNNEL_STATUS_UNMANAGED ;
info.last_sent_TS = 0 ;
info.client_id = client_id ;
info.last_tunnel_request_TS = 0 ;
info.item_hash = computeDataItemHash(data_item) ;
info.sending_attempts = 0 ;
@ -2029,7 +2018,8 @@ Sha1CheckSum p3GRouter::makeTunnelHash(const RsGxsId& destination,const GRouterS
return RsDirUtil::sha1sum(bytes,20) ;
}
bool p3GRouter::locked_getGxsIdAndClientId(const TurtleFileHash& sum,RsGxsId& gxs_id,GRouterServiceId& client_id)
#ifdef TO_REMOVE
bool p3GRouter::locked_getGxsOwnIdAndClientIdFromHash(const TurtleFileHash& sum,RsGxsId& gxs_id,GRouterServiceId& client_id)
{
assert( gxs_id.SIZE_IN_BYTES == 16) ;
assert(Sha1CheckSum::SIZE_IN_BYTES == 20) ;
@ -2047,6 +2037,7 @@ bool p3GRouter::locked_getGxsIdAndClientId(const TurtleFileHash& sum,RsGxsId& gx
return true ;
}
#endif
bool p3GRouter::loadList(std::list<RsItem*>& items)
{
{
@ -2210,7 +2201,8 @@ void p3GRouter::debugDump()
for(std::map<Sha1CheckSum, GRouterPublishedKeyInfo>::const_iterator it(_owned_key_ids.begin());it!=_owned_key_ids.end();++it)
{
grouter_debug() << " Hash : " << it->first << std::endl;
grouter_debug() << " Hash : " << it->first << std::endl;
grouter_debug() << " Key : " << it->second.authentication_key << std::endl;
grouter_debug() << " Service id : " << std::hex << it->second.service_id << std::dec << std::endl;
grouter_debug() << " Description : " << it->second.description_string << std::endl;
}
@ -2226,15 +2218,17 @@ void p3GRouter::debugDump()
for(std::map<GRouterMsgPropagationId, GRouterRoutingInfo>::iterator it(_pending_messages.begin());it!=_pending_messages.end();++it)
{
grouter_debug() << " Msg id : " << std::hex << it->first << std::dec ;
grouter_debug() << " data hash : " << it->second.item_hash ;
grouter_debug() << " Destination : " << it->second.data_item->destination_key ;
grouter_debug() << " Received : " << now - it->second.received_time_TS << " secs ago.";
grouter_debug() << " Last sent : " << now - it->second.last_sent_TS << " secs ago.";
grouter_debug() << " Transaction TS : " << now - it->second.data_transaction_TS << " secs ago.";
grouter_debug() << " Data Status : " << statusString[it->second.data_status] << std::endl;
grouter_debug() << " Tunl Status : " << statusString[it->second.tunnel_status] << std::endl;
grouter_debug() << " Receipt ok : " << (it->second.receipt_item != NULL) << std::endl;
grouter_debug() << " Msg id: " << std::hex << it->first << std::dec ;
grouter_debug() << " data hash: " << it->second.item_hash ;
grouter_debug() << " client id: " << std::hex << it->second.client_id << std::dec;
grouter_debug() << " Flags: " << std::hex << it->second.routing_flags << std::dec;
grouter_debug() << " Destination: " << it->second.data_item->destination_key ;
grouter_debug() << " Received: " << now - it->second.received_time_TS << " secs ago.";
grouter_debug() << " Last sent: " << now - it->second.last_sent_TS << " secs ago.";
grouter_debug() << " Transaction TS: " << now - it->second.data_transaction_TS << " secs ago.";
grouter_debug() << " Data Status: " << statusString[it->second.data_status] << std::endl;
grouter_debug() << " Tunl Status: " << statusString[it->second.tunnel_status] << std::endl;
grouter_debug() << " Receipt ok: " << (it->second.receipt_item != NULL) << std::endl;
}
grouter_debug() << " Tunnels: " << std::endl;

View file

@ -252,8 +252,7 @@ private:
void handleIncomingReceiptItem(RsGRouterSignedReceiptItem *receipt_item) ;
void handleIncomingDataItem(RsGRouterGenericDataItem *data_item) ;
bool locked_getClientAndServiceId(const TurtleFileHash& hash, const RsGxsId& destination_key, GRouterClientService *& client, GRouterServiceId& service_id);
bool locked_getLocallyRegisteredClientFromServiceId(const GRouterServiceId& service_id,GRouterClientService *& client);
// utility functions
//
@ -270,7 +269,7 @@ private:
static Sha1CheckSum makeTunnelHash(const RsGxsId& destination,const GRouterServiceId& client);
bool locked_getGxsIdAndClientId(const TurtleFileHash &sum,RsGxsId& gxs_id,GRouterServiceId& client_id);
//bool locked_getGxsIdAndClientId(const TurtleFileHash &sum,RsGxsId& gxs_id,GRouterServiceId& client_id);
bool locked_sendTransactionData(const RsPeerId& pid,const RsGRouterTransactionItem& item);
void locked_collectAvailableFriends(const GRouterKeyId &gxs_id,std::list<RsPeerId>& friend_peers, const std::set<RsPeerId>& incoming_routes,bool is_origin);

View file

@ -563,7 +563,11 @@ bool GxsSecurity::encrypt(uint8_t *& out, uint32_t &outlen, const uint8_t *in, u
int out_offset = 0;
int max_evp_key_size = EVP_PKEY_size(public_key);
ek = (unsigned char*)malloc(max_evp_key_size);
ek = (unsigned char*)rs_malloc(max_evp_key_size);
if(ek == NULL)
return false ;
const EVP_CIPHER *cipher = EVP_aes_128_cbc();
int cipher_block_size = EVP_CIPHER_block_size(cipher);
int size_net_ekl = sizeof(net_ekl);
@ -574,13 +578,10 @@ bool GxsSecurity::encrypt(uint8_t *& out, uint32_t &outlen, const uint8_t *in, u
if(!EVP_SealInit(&ctx, EVP_aes_128_cbc(), &ek, &eklen, iv, &public_key, 1)) return false;
// now assign memory to out accounting for data, and cipher block size, key length, and key length val
out = (uint8_t*)malloc(inlen + cipher_block_size + size_net_ekl + eklen + EVP_MAX_IV_LENGTH);
out = (uint8_t*)rs_malloc(inlen + cipher_block_size + size_net_ekl + eklen + EVP_MAX_IV_LENGTH);
if(out == NULL)
{
std::cerr << "gxssecurity::encrypt(): cnnot allocate memory of size " << inlen + cipher_block_size + size_net_ekl + eklen + EVP_MAX_IV_LENGTH << " to encrypt data." << std::endl;
return false ;
}
if(out == NULL)
return false ;
net_ekl = htonl(eklen);
memcpy((unsigned char*)out + out_offset, &net_ekl, size_net_ekl);
@ -750,7 +751,11 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
EVP_CIPHER_CTX ctx;
int eklen = 0, net_ekl = 0;
unsigned char *ek = (unsigned char*)malloc(EVP_PKEY_size(privateKey));
unsigned char *ek = (unsigned char*)rs_malloc(EVP_PKEY_size(privateKey));
if(ek == NULL)
return false ;
unsigned char iv[EVP_MAX_IV_LENGTH];
EVP_CIPHER_CTX_init(&ctx);
@ -788,13 +793,10 @@ bool GxsSecurity::decrypt(uint8_t *& out, uint32_t & outlen, const uint8_t *in,
std::cerr << "Severe error in " << __PRETTY_FUNCTION__ << ": cannot encrypt. " << std::endl;
return false ;
}
out = (uint8_t*)malloc(inlen - in_offset);
out = (uint8_t*)rs_malloc(inlen - in_offset);
if(out == NULL)
{
std::cerr << "gxssecurity::decrypt(): cannot allocate memory of size " << inlen - in_offset << " to decrypt data." << std::endl;
return false;
}
if(!EVP_OpenUpdate(&ctx, (unsigned char*) out, &out_currOffset, (unsigned char*)in + in_offset, inlen - in_offset))
{

View file

@ -856,7 +856,7 @@ void p3GxsTunnelService::handleRecvDHPublicKey(RsGxsTunnelDHPublicKeyItem *item)
#endif
uint32_t pubkey_size = BN_num_bytes(item->public_key) ;
unsigned char *data = (unsigned char *)malloc(pubkey_size) ;
RsTemporaryMemory data(pubkey_size) ;
BN_bn2bin(item->public_key, data) ;
RsTlvSecurityKey signature_key ;
@ -901,7 +901,7 @@ void p3GxsTunnelService::handleRecvDHPublicKey(RsGxsTunnelDHPublicKeyItem *item)
signature_key = item->gxs_key ;
}
if(!GxsSecurity::validateSignature((char*)data,pubkey_size,signature_key,item->signature))
if(!GxsSecurity::validateSignature((char*)(unsigned char*)data,pubkey_size,signature_key,item->signature))
{
std::cerr << "(SS) Signature was verified and it doesn't check! This is a security issue!" << std::endl;
return ;
@ -939,7 +939,7 @@ void p3GxsTunnelService::handleRecvDHPublicKey(RsGxsTunnelDHPublicKeyItem *item)
// Looks for the DH params. If not there yet, create them.
//
int size = DH_size(it->second.dh) ;
unsigned char *key_buff = new unsigned char[size] ;
RsTemporaryMemory key_buff(size) ;
if(size != DH_compute_key(key_buff,item->public_key,it->second.dh))
{
@ -959,7 +959,6 @@ void p3GxsTunnelService::handleRecvDHPublicKey(RsGxsTunnelDHPublicKeyItem *item)
assert(GXS_TUNNEL_AES_KEY_SIZE <= Sha1CheckSum::SIZE_IN_BYTES) ;
memcpy(pinfo.aes_key, RsDirUtil::sha1sum(key_buff,size).toByteArray(),GXS_TUNNEL_AES_KEY_SIZE) ;
delete[] key_buff ;
pinfo.last_contact = time(NULL) ;
pinfo.last_keep_alive_sent = time(NULL) ;
@ -1036,7 +1035,15 @@ bool p3GxsTunnelService::locked_sendDHPublicKey(const DH *dh,const RsGxsId& own_
uint32_t error_status ;
uint32_t size = BN_num_bytes(dhitem->public_key) ;
unsigned char *data = (unsigned char *)malloc(size) ;
RsTemporaryMemory data(size) ;
if(data == NULL)
{
delete(dhitem);
return false ;
}
BN_bn2bin(dhitem->public_key, data) ;
if(!mGixs->signData((unsigned char*)data,size,own_gxs_id,signature,error_status))
@ -1048,11 +1055,9 @@ bool p3GxsTunnelService::locked_sendDHPublicKey(const DH *dh,const RsGxsId& own_
default: std::cerr << "(EE) Unknown error when signing" << std::endl;
break ;
}
free(data) ;
delete(dhitem);
return false;
}
free(data) ;
if(!mGixs->getKey(own_gxs_id,signature_key_public))
{
@ -1136,8 +1141,13 @@ bool p3GxsTunnelService::locked_sendClearTunnelData(RsGxsTunnelDHPublicKeyItem *
uint32_t rssize = item->serial_size() ;
gitem->data_size = rssize + 8 ;
gitem->data_bytes = malloc(rssize+8) ;
gitem->data_bytes = rs_malloc(rssize+8) ;
if(gitem->data_bytes == NULL)
{
delete gitem ;
return NULL ;
}
// by convention, we use a IV of 0 for unencrypted data.
memset(gitem->data_bytes,0,8) ;
@ -1221,8 +1231,11 @@ bool p3GxsTunnelService::locked_sendEncryptedTunnelData(RsGxsTunnelItem *item)
RsTurtleGenericDataItem *gitem = new RsTurtleGenericDataItem ;
gitem->data_size = encrypted_size + GXS_TUNNEL_ENCRYPTION_IV_SIZE + GXS_TUNNEL_ENCRYPTION_HMAC_SIZE ;
gitem->data_bytes = malloc(gitem->data_size) ;
gitem->data_bytes = rs_malloc(gitem->data_size) ;
if(gitem->data_bytes == NULL)
return false ;
memcpy(& ((uint8_t*)gitem->data_bytes)[0] ,&IV,8) ;
unsigned int md_len = GXS_TUNNEL_ENCRYPTION_HMAC_SIZE ;
@ -1316,7 +1329,11 @@ bool p3GxsTunnelService::sendData(const RsGxsTunnelId &tunnel_id, uint32_t servi
item->flags = 0; // not used yet.
item->service_id = service_id;
item->data_size = size; // encrypted data size
item->data = (uint8_t*)malloc(size); // encrypted data
item->data = (uint8_t*)rs_malloc(size); // encrypted data
if(item->data == NULL)
delete item ;
item->PeerId(RsPeerId(tunnel_id)) ;
memcpy(item->data,data,size) ;
@ -1465,6 +1482,8 @@ bool p3GxsTunnelService::closeExistingTunnel(const RsGxsTunnelId& tunnel_id, uin
if(it2 != _gxs_tunnel_virtual_peer_ids.end())
hash = it2->second.hash ;
else
hash = it->second.hash ;
// check how many clients are used. If empty, close the tunnel

View file

@ -29,6 +29,7 @@
#include "serialiser/rsbaseserial.h"
#include "serialiser/rstlvbase.h"
#include "util/rsprint.h"
#include "util/rsmemory.h"
#include "gxstunnel/rsgxstunnelitems.h"
@ -343,6 +344,13 @@ RsGxsTunnelDHPublicKeyItem *RsGxsTunnelSerialiser::deserialise_RsGxsTunnelDHPubl
/* get mandatory parts first */
ok &= getRawUInt32(data, rssize, &offset, &s);
if(s > rssize || rssize - s < offset)
{
std::cerr << "RsGxsTunnelDHPublicKeyItem::() Size error while deserializing." << std::endl ;
delete item ;
return NULL ;
}
item->public_key = BN_bin2bn(&((unsigned char *)data)[offset],s,NULL) ;
offset += s ;
@ -380,21 +388,22 @@ RsGxsTunnelDataItem *RsGxsTunnelSerialiser::deserialise_RsGxsTunnelDataItem(void
ok &= getRawUInt32(dat, rssize, &offset, &item->service_id);
ok &= getRawUInt32(dat, rssize, &offset, &item->data_size);
if(offset + item->data_size <= size)
if(item->data_size > rssize || rssize - item->data_size < offset)
{
item->data = (unsigned char*)malloc(item->data_size) ;
if(dat == NULL)
{
delete item ;
return NULL ;
}
memcpy(item->data,&((uint8_t*)dat)[offset],item->data_size) ;
offset += item->data_size ;
std::cerr << "RsGxsTunnelDHPublicKeyItem::() Size error while deserializing." << std::endl ;
delete item ;
return NULL ;
}
else
ok = false ;
item->data = (unsigned char*)rs_malloc(item->data_size) ;
if(item->data == NULL)
{
delete item ;
return NULL ;
}
memcpy(item->data,&((uint8_t*)dat)[offset],item->data_size) ;
offset += item->data_size ;
if (offset != rssize)

View file

@ -73,7 +73,7 @@ class RsGxsTunnelItem: public RsItem
class RsGxsTunnelDataItem: public RsGxsTunnelItem
{
public:
RsGxsTunnelDataItem() :RsGxsTunnelItem(RS_PKT_SUBTYPE_GXS_TUNNEL_DATA) { data=NULL ;data_size=0; }
RsGxsTunnelDataItem() :RsGxsTunnelItem(RS_PKT_SUBTYPE_GXS_TUNNEL_DATA) { data=NULL ;data_size=0;service_id=0;unique_item_counter=0; }
RsGxsTunnelDataItem(uint8_t subtype) :RsGxsTunnelItem(subtype) { data=NULL ;data_size=0; }
virtual ~RsGxsTunnelDataItem() {}
@ -96,7 +96,7 @@ public:
class RsGxsTunnelStatusItem: public RsGxsTunnelItem
{
public:
RsGxsTunnelStatusItem() :RsGxsTunnelItem(RS_PKT_SUBTYPE_GXS_TUNNEL_STATUS) {}
RsGxsTunnelStatusItem() :RsGxsTunnelItem(RS_PKT_SUBTYPE_GXS_TUNNEL_STATUS) , status(0) {}
RsGxsTunnelStatusItem(void *data,uint32_t size) ; // deserialization
virtual ~RsGxsTunnelStatusItem() {}

View file

@ -361,7 +361,6 @@ HEADERS += chat/distantchat.h \
HEADERS += pqi/authssl.h \
pqi/authgpg.h \
pqi/rsmemory.h \
pgp/pgphandler.h \
pgp/pgpkeyutil.h \
pgp/rsaes.h \
@ -475,6 +474,7 @@ HEADERS += turtle/p3turtle.h \
HEADERS += util/folderiterator.h \
util/rsdebug.h \
util/rsmemory.h \
util/rscompress.h \
util/smallobject.h \
util/rsdir.h \
@ -631,6 +631,7 @@ SOURCES += util/folderiterator.cc \
util/rscompress.cc \
util/smallobject.cc \
util/rsdir.cc \
util/rsmemory.cc \
util/rsdiscspace.cc \
util/rsnet.cc \
util/rsnet_ss.cc \

View file

@ -26,6 +26,7 @@ extern "C" {
#include "retroshare/rspeers.h" // For rsicontrol.
#include "util/rsdir.h"
#include "util/rsdiscspace.h"
#include "util/rsmemory.h"
#include "pgp/pgpkeyutil.h"
static const uint32_t PGP_CERTIFICATE_LIMIT_MAX_NAME_SIZE = 64 ;
@ -39,7 +40,11 @@ PassphraseCallback PGPHandler::_passphrase_callback = NULL ;
ops_keyring_t *PGPHandler::allocateOPSKeyring()
{
ops_keyring_t *kr = (ops_keyring_t*)malloc(sizeof(ops_keyring_t)) ;
ops_keyring_t *kr = (ops_keyring_t*)rs_malloc(sizeof(ops_keyring_t)) ;
if(kr == NULL)
return NULL ;
kr->nkeys = 0 ;
kr->nkeys_allocated = 0 ;
kr->keys = 0 ;

View file

@ -82,6 +82,8 @@ bool RsPluginManager::acceptablePluginName(const std::string& name)
//
#ifdef WINDOWS_SYS
return name.size() > 4 && name.substr(name.size() - 4) == ".dll";
#elif defined(__MACH__)
return name.size() > 6 && !strcmp(name.c_str()+name.size()-6,".dylib") ;
#else
return name.size() > 3 && !strcmp(name.c_str()+name.size()-3,".so") ;
#endif

View file

@ -117,10 +117,10 @@ static struct CRYPTO_dynlock_value *dyn_create_function(const char */*file*/, in
{
struct CRYPTO_dynlock_value *value;
value = (struct CRYPTO_dynlock_value*) malloc(sizeof(struct CRYPTO_dynlock_value));
if (!value) {
value = (struct CRYPTO_dynlock_value*) rs_malloc(sizeof(struct CRYPTO_dynlock_value));
if (!value)
return NULL;
}
pthread_mutex_init(&value->mutex, NULL);
return value;
@ -166,10 +166,10 @@ static void dyn_destroy_function(struct CRYPTO_dynlock_value *l, const char */*f
bool tls_init()
{
/* static locks area */
mutex_buf = (pthread_mutex_t*) malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
if (mutex_buf == NULL) {
mutex_buf = (pthread_mutex_t*) rs_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
if (mutex_buf == NULL)
return false;
}
for (int i = 0; i < CRYPTO_num_locks(); i++) {
pthread_mutex_init(&mutex_buf[i], NULL);
}
@ -1259,7 +1259,11 @@ bool AuthSSLimpl::encrypt(void *&out, int &outlen, const void *in, int inlen,
int out_offset = 0;
int max_evp_key_size = EVP_PKEY_size(public_key);
ek = (unsigned char*)malloc(max_evp_key_size);
ek = (unsigned char*)rs_malloc(max_evp_key_size);
if(ek == NULL)
return false ;
const EVP_CIPHER *cipher = EVP_aes_128_cbc();
int cipher_block_size = EVP_CIPHER_block_size(cipher);
int size_net_ekl = sizeof(net_ekl);
@ -1273,8 +1277,13 @@ bool AuthSSLimpl::encrypt(void *&out, int &outlen, const void *in, int inlen,
}
// now assign memory to out accounting for data, and cipher block size, key length, and key length val
out = (unsigned char*)malloc(inlen + cipher_block_size + size_net_ekl + eklen + EVP_MAX_IV_LENGTH);
out = (unsigned char*)rs_malloc(inlen + cipher_block_size + size_net_ekl + eklen + EVP_MAX_IV_LENGTH);
if(out == NULL)
{
free(ek) ;
return false ;
}
net_ekl = htonl(eklen);
memcpy((unsigned char*)out + out_offset, &net_ekl, size_net_ekl);
out_offset += size_net_ekl;
@ -1343,6 +1352,12 @@ bool AuthSSLimpl::decrypt(void *&out, int &outlen, const void *in, int inlen)
unsigned char iv[EVP_MAX_IV_LENGTH];
int ek_mkl = EVP_PKEY_size(mOwnPrivateKey);
ek = (unsigned char*)malloc(ek_mkl);
if(ek == NULL)
{
std::cerr << "(EE) Cannot allocate memory for " << ek_mkl << " bytes in " << __PRETTY_FUNCTION__ << std::endl;
return false ;
}
EVP_CIPHER_CTX_init(&ctx);
int in_offset = 0, out_currOffset = 0;
@ -1380,8 +1395,13 @@ bool AuthSSLimpl::decrypt(void *&out, int &outlen, const void *in, int inlen)
return false;
}
out = (unsigned char*)malloc(inlen - in_offset);
out = (unsigned char*)rs_malloc(inlen - in_offset);
if(out == NULL)
{
free(ek) ;
return false ;
}
if(!EVP_OpenUpdate(&ctx, (unsigned char*) out, &out_currOffset, (unsigned char*)in + in_offset, inlen - in_offset)) {
free(ek);
free(out) ;

View file

@ -27,6 +27,7 @@
#include "pqi/authssl.h"
#include "util/rsnet.h"
#include "util/rsdir.h"
#include "util/rsmemory.h"
// #define DEBUG_PQIBIN
@ -314,7 +315,13 @@ BinMemInterface::BinMemInterface(int defsize, int flags)
:bin_flags(flags), buf(NULL), size(defsize),
recvsize(0), readloc(0), hash(NULL), bcount(0)
{
buf = malloc(defsize);
buf = rs_malloc(defsize);
if(buf == NULL)
{
close() ;
return ;
}
if (bin_flags & BIN_FLAGS_HASH_DATA)
{
hash = new pqihash();
@ -326,7 +333,13 @@ BinMemInterface::BinMemInterface(const void *data, const int defsize, int flags)
:bin_flags(flags), buf(NULL), size(defsize),
recvsize(0), readloc(0), hash(NULL), bcount(0)
{
buf = malloc(defsize);
buf = rs_malloc(defsize);
if(buf == NULL)
{
close() ;
return ;
}
if (bin_flags & BIN_FLAGS_HASH_DATA)
{
hash = new pqihash();

View file

@ -290,7 +290,11 @@ bool getLocalAddresses(std::list<sockaddr_storage> & addrs)
#ifdef WINDOWS_SYS
// Seems strange to me but M$ documentation suggests to allocate this way...
DWORD bf_size = 16000;
IP_ADAPTER_ADDRESSES* adapter_addresses = (IP_ADAPTER_ADDRESSES*) malloc(bf_size);
IP_ADAPTER_ADDRESSES* adapter_addresses = (IP_ADAPTER_ADDRESSES*) rs_malloc(bf_size);
if(adapter_addresses == NULL)
return false ;
DWORD error = GetAdaptersAddresses(AF_UNSPEC,
GAA_FLAG_SKIP_MULTICAST |
GAA_FLAG_SKIP_DNS_SERVER |

View file

@ -46,6 +46,7 @@
#include <fstream>
#include "util/rsdebug.h"
#include "util/rsmemory.h"
#include "util/rsstring.h"
//
@ -194,7 +195,12 @@ int pqistore::writePkt(RsItem *pqi)
#endif
uint32_t pktsize = rsSerialiser->size(pqi);
void *ptr = malloc(pktsize);
RsTemporaryMemory ptr(pktsize) ;
if(ptr == NULL)
return 0 ;
if (!(rsSerialiser->serialise(pqi, ptr, &pktsize)))
{
#ifdef PQISTORE_DEBUG
@ -203,7 +209,6 @@ int pqistore::writePkt(RsItem *pqi)
pqioutput(PQL_ALERT, pqistorezone, out);
#endif
free(ptr);
if (!(bio_flags & BIN_FLAGS_NO_DELETE))
delete pqi;
return 0;
@ -218,7 +223,6 @@ int pqistore::writePkt(RsItem *pqi)
pqi -> print_string(out);
pqioutput(PQL_ALERT, pqistorezone, out);
free(ptr);
if (!(bio_flags & BIN_FLAGS_NO_DELETE))
delete pqi;
return 0;
@ -232,7 +236,6 @@ int pqistore::writePkt(RsItem *pqi)
pqi -> print_string(out);
pqioutput(PQL_ALERT, pqistorezone, out);
free(ptr);
if (!(bio_flags & BIN_FLAGS_NO_DELETE))
delete pqi;
@ -250,7 +253,6 @@ int pqistore::writePkt(RsItem *pqi)
pqioutput(PQL_ALERT, pqistorezone, out);
#endif
free(ptr);
if (!(bio_flags & BIN_FLAGS_NO_DELETE))
delete pqi;
@ -262,7 +264,6 @@ int pqistore::writePkt(RsItem *pqi)
pqioutput(PQL_DEBUG_BASIC, pqistorezone, out);
#endif
free(ptr);
if (!(bio_flags & BIN_FLAGS_NO_DELETE))
delete pqi;
@ -288,7 +289,10 @@ int pqistore::readPkt(RsItem **item_out)
// initial read size: basic packet.
int blen = getRsPktBaseSize();
void *block = malloc(blen);
void *block = rs_malloc(blen);
if(block == NULL)
return false ;
int tmplen;
/* we have the header */
@ -495,7 +499,10 @@ int pqiSSLstore::readPkt(RsItem **item_out)
// initial read size: basic packet.
int blen = getRsPktBaseSize();
void *block = malloc(blen);
void *block = rs_malloc(blen);
if(block == NULL)
return false ;
int tmplen;
/* we have the header */

View file

@ -315,7 +315,11 @@ int pqistreamer::queue_outpqi_locked(RsItem *pqi,uint32_t& pktsize)
/* decide which type of packet it is */
pktsize = mRsSerialiser->size(pqi);
void *ptr = malloc(pktsize);
void *ptr = rs_malloc(pktsize);
if(ptr == NULL)
return 0 ;
#ifdef DEBUG_PQISTREAMER
std::cerr << "pqistreamer::queue_outpqi() serializing packet with packet size : " << pktsize << std::endl;
@ -441,7 +445,6 @@ int pqistreamer::handleoutgoing_locked()
mPkt_wpending_size = 0 ;
}
outSentBytes_locked(sentbytes);
return 0;
}
@ -469,10 +472,10 @@ int pqistreamer::handleoutgoing_locked()
}
#endif
outSentBytes_locked(sentbytes);
return 0;
}
#define GROUP_OUTGOING_PACKETS 1
#define PACKET_GROUPING_SIZE_LIMIT 32768
// send a out_pkt., else send out_data. unless
// there is a pending packet.
if (!mPkt_wpending)
@ -482,7 +485,7 @@ int pqistreamer::handleoutgoing_locked()
mPkt_wpending_size = 0 ;
int k=0;
while(mPkt_wpending_size < maxbytes && (dta = locked_pop_out_data())!=NULL )
while(mPkt_wpending_size < (uint32_t)maxbytes && mPkt_wpending_size < PACKET_GROUPING_SIZE_LIMIT && (dta = locked_pop_out_data())!=NULL )
{
uint32_t s = getRsItemSize(dta);
mPkt_wpending = realloc(mPkt_wpending,s+mPkt_wpending_size) ;
@ -524,12 +527,12 @@ int pqistreamer::handleoutgoing_locked()
pqioutput(PQL_DEBUG_BASIC, pqistreamerzone, out);
#endif
outSentBytes_locked(sentbytes);
// pkt_wpending will kept til next time.
// ensuring exactly the same data is written (openSSL requirement).
return -1;
}
++nsent;
outSentBytes_locked(mPkt_wpending_size); // this is the only time where we know exactly what was sent.
#ifdef DEBUG_TRANSFERS
std::cerr << "pqistreamer::handleoutgoing_locked() Sent Packet len: " << mPkt_wpending_size << " @ " << RsUtil::AccurateTimeString();
@ -549,7 +552,6 @@ int pqistreamer::handleoutgoing_locked()
if(nsent > 0)
std::cerr << "nsent = " << nsent << ", total bytes=" << sentbytes << std::endl;
#endif
outSentBytes_locked(sentbytes);
return 1;
}
@ -568,7 +570,6 @@ int pqistreamer::handleincoming_locked()
if(!(mBio->isactive()))
{
mReading_state = reading_state_initial ;
inReadBytes_locked(readbytes);
free_rpend_locked();
return 0;
}
@ -606,8 +607,6 @@ start_packet_read:
{
pqioutput(PQL_DEBUG_BASIC, pqistreamerzone, "pqistreamer::handleincoming() Didn't read BasePkt!");
inReadBytes_locked(readbytes);
// error.... (either blocked or failure)
if (tmplen == 0)
{
@ -652,7 +651,7 @@ start_packet_read:
#endif
readbytes += blen;
mReading_state = reading_state_packet_started ;
mReading_state = reading_state_packet_started ;
mFailed_read_attempts = 0 ; // reset failed read, as the packet has been totally read.
}
continue_packet:
@ -805,7 +804,7 @@ continue_packet:
mFailed_read_attempts = 0 ;
readbytes += extralen;
}
}
// create packet, based on header.
#ifdef DEBUG_PQISTREAMER
@ -824,7 +823,9 @@ continue_packet:
std::cerr << "[" << (void*)pthread_self() << "] " << "deserializing. Size=" << pktlen << std::endl ;
#endif
RsItem *pkt = mRsSerialiser->deserialise(block, &pktlen);
inReadBytes_locked(pktlen); // only count deserialised packets, because that's what is actually been transfered.
RsItem *pkt = mRsSerialiser->deserialise(block, &pktlen);
if ((pkt != NULL) && (0 < handleincomingitem_locked(pkt,pktlen)))
{
@ -854,7 +855,6 @@ continue_packet:
}
#endif
inReadBytes_locked(readbytes);
return 0;
}
@ -1045,7 +1045,10 @@ void pqistreamer::allocate_rpend_locked()
return;
mPkt_rpend_size = getRsPktMaxSize();
mPkt_rpending = malloc(mPkt_rpend_size);
mPkt_rpending = rs_malloc(mPkt_rpend_size);
if(mPkt_rpending == NULL)
return ;
// avoid uninitialized (and random) memory read.
memset(mPkt_rpending,0,mPkt_rpend_size) ;

View file

@ -87,7 +87,7 @@ class GxsReputation
class RsGxsIdGroup
{
public:
RsGxsIdGroup(): mLastUsageTS(0), mPgpKnown(false) { return; }
RsGxsIdGroup(): mLastUsageTS(0), mPgpKnown(false),mIsAContact(false) { return; }
~RsGxsIdGroup() { return; }

View file

@ -464,10 +464,11 @@ virtual void getOwnAvatarData(unsigned char *& data,int& size) = 0 ;
/****************************************/
virtual bool joinVisibleChatLobby(const ChatLobbyId& lobby_id,const RsGxsId& own_id) = 0 ;
virtual bool isLobbyId(const RsPeerId& virtual_peer_id,ChatLobbyId& lobby_id) = 0;
virtual bool getVirtualPeerId(const ChatLobbyId& lobby_id,RsPeerId& vpid) = 0;
/// get ids of subscribed lobbies
virtual void getChatLobbyList(std::list<ChatLobbyId>& cl_list) = 0;
/// get lobby info of a subscribed chat lobby. Returns true if lobby id is valid.
virtual bool getChatLobbyInfo(const ChatLobbyId& id,ChatLobbyInfo& info) = 0 ;
/// get info about all lobbies, subscribed and unsubscribed
virtual void getListOfNearbyChatLobbies(std::vector<VisibleChatLobbyRecord>& public_lobbies) = 0 ;
virtual void invitePeerToLobby(const ChatLobbyId& lobby_id,const RsPeerId& peer_id) = 0;
virtual bool acceptLobbyInvite(const ChatLobbyId& id,const RsGxsId& identity) = 0 ;

View file

@ -160,7 +160,7 @@ class RsPlugin
// creates a new resource api handler object. ownership is transferred to the caller.
// the caller should supply a statetokenserver, and keep it valid until destruction
// the plugin should return a entry point name. this is to make the entry point name independent from file names
virtual resource_api::ResourceRouter* new_resource_api_handler(const RsPlugInInterfaces& ifaces, resource_api::StateTokenServer* sts, std::string &entrypoint) const { return 0;}
virtual resource_api::ResourceRouter* new_resource_api_handler(const RsPlugInInterfaces& /* ifaces */, resource_api::StateTokenServer* /* sts */, std::string & /*entrypoint*/) const { return 0;}
// Shutdown
virtual void stop() {}

View file

@ -41,6 +41,8 @@ public:
struct ReputationInfo
{
ReputationInfo() : mOwnOpinion(OPINION_NEUTRAL), mOverallReputationScore(REPUTATION_THRESHOLD_DEFAULT), mFriendAverage(REPUTATION_THRESHOLD_DEFAULT),mAssessment(ASSESSMENT_OK){}
RsReputations::Opinion mOwnOpinion ;
float mOverallReputationScore ;
float mFriendAverage ;

View file

@ -444,15 +444,6 @@ void p3Msgs::setCustomStateString(const std::string& state_string)
mChatSrv->setOwnCustomStateString(state_string) ;
}
bool p3Msgs::getVirtualPeerId(const ChatLobbyId& id,RsPeerId& peer_id)
{
return mChatSrv->getVirtualPeerId(id,peer_id) ;
}
bool p3Msgs::isLobbyId(const RsPeerId& peer_id,ChatLobbyId& id)
{
return mChatSrv->isLobbyId(peer_id,id) ;
}
bool p3Msgs::getChatLobbyInfo(const ChatLobbyId& id,ChatLobbyInfo& linfo)
{
return mChatSrv->getChatLobbyInfo(id,linfo) ;

View file

@ -138,8 +138,6 @@ class p3Msgs: public RsMsgs
virtual bool joinVisibleChatLobby(const ChatLobbyId& id, const RsGxsId &own_id) ;
virtual void getListOfNearbyChatLobbies(std::vector<VisibleChatLobbyRecord>& public_lobbies) ;
virtual bool getVirtualPeerId(const ChatLobbyId& id,RsPeerId& vpid) ;
virtual bool isLobbyId(const RsPeerId& virtual_peer_id,ChatLobbyId& lobby_id) ;
virtual void getChatLobbyList(std::list<ChatLobbyId>& cl_list) ;
virtual bool getChatLobbyInfo(const ChatLobbyId& id,ChatLobbyInfo& info) ;
virtual void invitePeerToLobby(const ChatLobbyId&, const RsPeerId&) ;

View file

@ -273,7 +273,13 @@ bool RsLoginHandler::tryAutoLogin(const RsPeerId& ssl_id,std::string& ssl_passwd
fseek(fp, 0, SEEK_END);
datalen = ftell(fp);
fseek(fp, 0, SEEK_SET);
dataptr = (char *) malloc(datalen);
dataptr = (char *) rs_malloc(datalen);
if(data_ptr == NULL)
{
fclose(fp);
return false;
}
fread(dataptr, 1, datalen, fp);
fclose(fp);

View file

@ -40,6 +40,7 @@ bool getRawUInt8(void *data, uint32_t size, uint32_t *offset, uint8_t *out)
/* first check there is space */
if (size < *offset + 1)
{
std::cerr << "(EE) Cannot deserialise uint8_t: not enough size." << std::endl;
return false;
}
void *buf = (void *) &(((uint8_t *) data)[*offset]);
@ -56,6 +57,7 @@ bool setRawUInt8(void *data, uint32_t size, uint32_t *offset, uint8_t in)
/* first check there is space */
if (size < *offset + 1)
{
std::cerr << "(EE) Cannot serialise uint8_t: not enough size." << std::endl;
return false;
}
@ -74,6 +76,7 @@ bool getRawUInt16(void *data, uint32_t size, uint32_t *offset, uint16_t *out)
/* first check there is space */
if (size < *offset + 2)
{
std::cerr << "(EE) Cannot deserialise uint16_t: not enough size." << std::endl;
return false;
}
void *buf = (void *) &(((uint8_t *) data)[*offset]);
@ -92,6 +95,7 @@ bool setRawUInt16(void *data, uint32_t size, uint32_t *offset, uint16_t in)
/* first check there is space */
if (size < *offset + 2)
{
std::cerr << "(EE) Cannot serialise uint16_t: not enough size." << std::endl;
return false;
}
@ -114,6 +118,7 @@ bool getRawUInt32(void *data, uint32_t size, uint32_t *offset, uint32_t *out)
/* first check there is space */
if (size < *offset + 4)
{
std::cerr << "(EE) Cannot deserialise uint32_t: not enough size." << std::endl;
return false;
}
void *buf = (void *) &(((uint8_t *) data)[*offset]);
@ -132,6 +137,7 @@ bool setRawUInt32(void *data, uint32_t size, uint32_t *offset, uint32_t in)
/* first check there is space */
if (size < *offset + 4)
{
std::cerr << "(EE) Cannot serialise uint32_t: not enough size." << std::endl;
return false;
}
@ -154,6 +160,7 @@ bool getRawUInt64(void *data, uint32_t size, uint32_t *offset, uint64_t *out)
/* first check there is space */
if (size < *offset + 8)
{
std::cerr << "(EE) Cannot deserialise uint64_t: not enough size." << std::endl;
return false;
}
void *buf = (void *) &(((uint8_t *) data)[*offset]);
@ -172,6 +179,7 @@ bool setRawUInt64(void *data, uint32_t size, uint32_t *offset, uint64_t in)
/* first check there is space */
if (size < *offset + 8)
{
std::cerr << "(EE) Cannot serialise uint64_t: not enough size." << std::endl;
return false;
}
@ -231,12 +239,13 @@ bool getRawString(void *data, uint32_t size, uint32_t *offset, std::string &outS
}
/* check there is space for string */
if (size < *offset + len)
if(len > size || size-len < *offset) // better than if(size < *offset + len) because it avoids integer overflow
{
std::cerr << "getRawString() not enough size" << std::endl;
return false;
}
uint8_t *buf = &(((uint8_t *) data)[*offset]);
for (uint32_t i = 0; i < len; i++)
{
outStr += buf[i];
@ -250,11 +259,10 @@ bool setRawString(void *data, uint32_t size, uint32_t *offset, const std::string
{
uint32_t len = inStr.length();
/* first check there is space */
if (size < *offset + 4 + len)
if(size < 4 || len > size-4 || size-len-4 < *offset) // better than if(size < *offset + len + 4) because it avoids integer overflow
{
//#ifdef RSSERIAL_DEBUG
std::cerr << "setRawString() Not enough size" << std::endl;
//#endif
return false;
}

View file

@ -899,7 +899,144 @@ RsMsgGRouterMap* RsMsgSerialiser::deserialiseMsgGRouterMap(void* data, uint32_t*
/************************* end of definition of msgGRouterMap serialisation functions ************************/
/************************* definition of msgDistantMessageMap serialisation functions ************************/
std::ostream& RsMsgDistantMessagesHashMap::print(std::ostream& out, uint16_t indent)
{
printRsItemBase(out, "RsMsgDistantMessagesHashMap", indent);
uint16_t int_Indent = indent + 2;
for(std::map<Sha1CheckSum,uint32_t>::const_iterator it(hash_map.begin());it!=hash_map.end();++it)
{
printIndent(out, int_Indent);
out << " " << std::hex << it->first << std::dec << " : " << it->second << std::endl;
}
printRsItemEnd(out, "RsMsgDistantMessagesHashMap", indent);
return out;
}
void RsMsgDistantMessagesHashMap::clear()
{
hash_map.clear() ;
return;
}
uint32_t RsMsgDistantMessagesHashMap::serial_size(bool)
{
uint32_t s = 8; /* header */
s += 4; // number of entries
s += (Sha1CheckSum::SIZE_IN_BYTES+4)*hash_map.size(); // entries
return s;
}
bool RsMsgDistantMessagesHashMap::serialise(void *data, uint32_t& pktsize,bool config)
{
uint32_t tlvsize = serial_size(config) ;
uint32_t offset = 0;
if (pktsize < tlvsize)
return false; /* not enough space */
pktsize = tlvsize;
bool ok = true;
ok &= setRsItemHeader(data, tlvsize, PacketId(), tlvsize);
#ifdef RSSERIAL_DEBUG
std::cerr << "RsMsgSerialiser::serialiseMsgDistantMessagesHashMap() Header: " << ok << std::endl;
std::cerr << "RsMsgSerialiser::serialiseMsgDistantMessagesHashMap() Size: " << tlvsize << std::endl;
#endif
/* skip the header */
offset += 8;
ok &= setRawUInt32(data, tlvsize, &offset, hash_map.size());
for(std::map<Sha1CheckSum,uint32_t>::const_iterator it=hash_map.begin();ok && it!=hash_map.end();++it)
{
ok &= it->first.serialise(data, tlvsize, offset) ;
ok &= setRawUInt32(data, tlvsize, &offset, it->second);
}
if (offset != tlvsize)
{
ok = false;
std::cerr << "RsMsgSerialiser::serialiseMsgDistantMessagesHashMap() Size Error! " << std::endl;
}
return ok;
}
RsMsgDistantMessagesHashMap* RsMsgSerialiser::deserialiseMsgDistantMessageHashMap(void* data, uint32_t* pktsize)
{
/* get the type and size */
uint32_t rstype = getRsItemId(data);
uint32_t rssize = getRsItemSize(data);
uint32_t offset = 0;
if ((RS_PKT_VERSION_SERVICE != getRsItemVersion(rstype)) ||
(RS_SERVICE_TYPE_MSG != getRsItemService(rstype)) ||
(RS_PKT_SUBTYPE_MSG_DISTANT_MSG_MAP != getRsItemSubType(rstype)))
{
return NULL; /* wrong type */
}
if (*pktsize < rssize) /* check size */
return NULL; /* not enough data */
/* set the packet length */
*pktsize = rssize;
bool ok = true;
/* ready to load */
RsMsgDistantMessagesHashMap *item = new RsMsgDistantMessagesHashMap();
item->clear();
/* skip the header */
offset += 8;
uint32_t s=0 ;
/* get mandatory parts first */
ok &= getRawUInt32(data, rssize, &offset, &s);
for(uint32_t i=0;i<s && ok;++i)
{
Sha1CheckSum s ;
uint32_t tm ;
ok &= s.deserialise(data, rssize, offset) ;
ok &= getRawUInt32(data, rssize, &offset, &tm);
item->hash_map.insert(std::make_pair(s,tm)) ;
}
if (offset != rssize)
{
/* error */
std::cerr << "(EE) size error in packet deserialisation: p3MsgItem, subtype " << getRsItemSubType(rstype) << ". offset=" << offset << " != rssize=" << rssize << std::endl;
delete item;
return NULL;
}
if (!ok)
{
std::cerr << "(EE) size error in packet deserialisation: p3MsgItem, subtype " << getRsItemSubType(rstype) << std::endl;
delete item;
return NULL;
}
return item;
}
/************************************** Message ParentId **********************/
std::ostream& RsMsgParentId::print(std::ostream& out, uint16_t indent)
@ -1042,27 +1179,14 @@ RsItem* RsMsgSerialiser::deserialise(void *data, uint32_t *pktsize)
switch(getRsItemSubType(rstype))
{
case RS_PKT_SUBTYPE_DEFAULT:
return deserialiseMsgItem(data, pktsize);
break;
case RS_PKT_SUBTYPE_MSG_SRC_TAG:
return deserialiseMsgSrcIdItem(data, pktsize);
break;
case RS_PKT_SUBTYPE_MSG_PARENT_TAG:
return deserialiseMsgParentIdItem(data, pktsize);
break;
case RS_PKT_SUBTYPE_MSG_TAG_TYPE:
return deserialiseTagItem(data, pktsize);
break;
case RS_PKT_SUBTYPE_MSG_INVITE:
return deserialisePublicMsgInviteConfigItem(data, pktsize);
break;
case RS_PKT_SUBTYPE_MSG_TAGS:
return deserialiseMsgTagItem(data, pktsize);
break;
case RS_PKT_SUBTYPE_MSG_GROUTER_MAP:
return deserialiseMsgGRouterMap(data, pktsize);
break;
case RS_PKT_SUBTYPE_DEFAULT: return deserialiseMsgItem(data, pktsize);
case RS_PKT_SUBTYPE_MSG_SRC_TAG: return deserialiseMsgSrcIdItem(data, pktsize);
case RS_PKT_SUBTYPE_MSG_PARENT_TAG: return deserialiseMsgParentIdItem(data, pktsize);
case RS_PKT_SUBTYPE_MSG_TAG_TYPE: return deserialiseTagItem(data, pktsize);
case RS_PKT_SUBTYPE_MSG_INVITE: return deserialisePublicMsgInviteConfigItem(data, pktsize);
case RS_PKT_SUBTYPE_MSG_TAGS: return deserialiseMsgTagItem(data, pktsize);
case RS_PKT_SUBTYPE_MSG_GROUTER_MAP: return deserialiseMsgGRouterMap(data, pktsize);
case RS_PKT_SUBTYPE_MSG_DISTANT_MSG_MAP: return deserialiseMsgDistantMessageHashMap(data, pktsize);
default:
return NULL;
break;

View file

@ -45,12 +45,13 @@
/**************************************************************************/
// for defining tags themselves and msg tags
const uint8_t RS_PKT_SUBTYPE_MSG_TAG_TYPE = 0x03;
const uint8_t RS_PKT_SUBTYPE_MSG_TAGS = 0x04;
const uint8_t RS_PKT_SUBTYPE_MSG_SRC_TAG = 0x05;
const uint8_t RS_PKT_SUBTYPE_MSG_PARENT_TAG = 0x06;
const uint8_t RS_PKT_SUBTYPE_MSG_INVITE = 0x07;
const uint8_t RS_PKT_SUBTYPE_MSG_GROUTER_MAP = 0x08;
const uint8_t RS_PKT_SUBTYPE_MSG_TAG_TYPE = 0x03;
const uint8_t RS_PKT_SUBTYPE_MSG_TAGS = 0x04;
const uint8_t RS_PKT_SUBTYPE_MSG_SRC_TAG = 0x05;
const uint8_t RS_PKT_SUBTYPE_MSG_PARENT_TAG = 0x06;
const uint8_t RS_PKT_SUBTYPE_MSG_INVITE = 0x07;
const uint8_t RS_PKT_SUBTYPE_MSG_GROUTER_MAP = 0x08;
const uint8_t RS_PKT_SUBTYPE_MSG_DISTANT_MSG_MAP = 0x09;
/**************************************************************************/
@ -226,7 +227,23 @@ class RsMsgGRouterMap : public RsMessageItem
//
std::map<GRouterMsgPropagationId,uint32_t> ongoing_msgs ;
};
class RsMsgDistantMessagesHashMap : public RsMessageItem
{
public:
RsMsgDistantMessagesHashMap() : RsMessageItem(RS_PKT_SUBTYPE_MSG_DISTANT_MSG_MAP) {}
std::ostream &print(std::ostream &out, uint16_t indent = 0);
virtual bool serialise(void *data,uint32_t& size,bool config) ;
virtual uint32_t serial_size(bool config) ;
virtual ~RsMsgDistantMessagesHashMap() {}
virtual void clear();
// ----------- Specific fields ------------- //
//
std::map<Sha1CheckSum,uint32_t> hash_map ;
};
class RsMsgParentId : public RsMessageItem
{
public:
@ -275,7 +292,8 @@ class RsMsgSerialiser: public RsSerialType
virtual RsMsgSrcId *deserialiseMsgSrcIdItem(void *data, uint32_t *size);
virtual RsMsgParentId *deserialiseMsgParentIdItem(void *data, uint32_t *size);
virtual RsPublicMsgInviteConfigItem *deserialisePublicMsgInviteConfigItem(void *data, uint32_t *size);
virtual RsMsgGRouterMap *deserialiseMsgGRouterMap(void *data, uint32_t *size);
virtual RsMsgGRouterMap *deserialiseMsgGRouterMap(void *data, uint32_t *size);
virtual RsMsgDistantMessagesHashMap *deserialiseMsgDistantMessageHashMap(void *data, uint32_t *size);
bool m_bConfiguration; // is set to true for saving configuration (enables serialising msgId)
};

View file

@ -34,6 +34,7 @@
#include <stdlib.h>
#include <stdint.h>
#include "util/rsmemory.h"
#include "retroshare/rstypes.h"
/*******************************************************************
@ -181,7 +182,7 @@ class RsRawItem: public RsItem
RsRawItem(uint32_t t, uint32_t size)
:RsItem(t), len(size)
{
data = malloc(len);
data = rs_malloc(len);
}
virtual ~RsRawItem()

View file

@ -24,6 +24,7 @@
*
*/
#include "util/rsmemory.h"
#include "serialiser/rstlvbinary.h"
#include "serialiser/rstlvbase.h"
@ -78,7 +79,11 @@ bool RsTlvBinaryData::setBinData(const void *data, uint32_t size)
return true;
}
bin_data = malloc(bin_len);
bin_data = rs_malloc(bin_len);
if(bin_data == NULL)
return false ;
memcpy(bin_data, data, bin_len);
return true;
}

View file

@ -916,6 +916,12 @@ bool SSGxsChannelGroup::load(const std::string &input)
mAutoDownload = false;
mDownloadDirectory.clear();
if(input.empty())
{
std::cerr << "(EE) SSGxsChannelGroup::load() asked to load a null string. Weird." << std::endl;
return false ;
}
RsTemporaryMemory tmpmem(input.length());
if (1 == sscanf(input.c_str(), "D:%d", &download_val))

View file

@ -98,7 +98,8 @@ void RsGxsImage::take(uint8_t *data, uint32_t size)
// NB Must make sure that we always use malloc/free for this data.
uint8_t *RsGxsImage::allocate(uint32_t size)
{
uint8_t *val = (uint8_t *) malloc(size);
uint8_t *val = (uint8_t *) rs_malloc(size);
#ifdef DEBUG_GXSCOMMON
std::cerr << "RsGxsImage()::allocate(" << (void *) val << ")";
std::cerr << std::endl;

View file

@ -51,7 +51,9 @@
#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>
@ -67,6 +69,8 @@ using namespace Rs::Msgs;
const int msgservicezone = 54319;
static const uint32_t RS_MSG_DISTANT_MESSAGE_HASH_KEEP_TIME = 2*30*86400 ; // keep msg hashes for 2 months to avoid re-sent msgs
/* Another little hack ..... unique message Ids
* will be handled in this class.....
* These are unique within this run of the server,
@ -78,20 +82,22 @@ const int msgservicezone = 54319;
* (3) from storage...
*/
p3MsgService::p3MsgService(p3ServiceControl *sc, p3IdService *id_serv)
:p3Service(), p3Config(), mIdService(id_serv), mServiceCtrl(sc), mMsgMtx("p3MsgService"), mMsgUniqueId(time(NULL))
:p3Service(), p3Config(), mIdService(id_serv), mServiceCtrl(sc), mMsgMtx("p3MsgService"), mMsgUniqueId(0)
{
_serialiser = new RsMsgSerialiser();
_serialiser = new RsMsgSerialiser(); // this serialiser is used for services. It's not the same than the one returned by setupSerialiser(). We need both!!
addSerialType(_serialiser);
mMsgUniqueId = 1 ; // 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 ;
/* Initialize standard tag types */
if(sc)
initStandardTagTypes();
/* Initialize standard tag types */
if(sc)
initStandardTagTypes();
}
@ -114,7 +120,7 @@ RsServiceInfo p3MsgService::getServiceInfo()
uint32_t p3MsgService::getNewUniqueMsgId()
{
RsStackMutex stack(mMsgMtx); /********** STACK LOCKED MTX ******/
RS_STACK_MUTEX(mMsgMtx); /********** STACK LOCKED MTX ******/
return mMsgUniqueId++;
}
@ -136,6 +142,7 @@ int p3MsgService::tick()
{
manageDistantPeers() ;
checkOutgoingMessages();
cleanListOfReceivedMessageHashes();
last_management_time = now ;
}
@ -143,6 +150,24 @@ int p3MsgService::tick()
return 0;
}
void p3MsgService::cleanListOfReceivedMessageHashes()
{
RS_STACK_MUTEX(mMsgMtx); /********** STACK LOCKED MTX ******/
time_t now = time(NULL) ;
for(std::map<Sha1CheckSum,uint32_t>::iterator it(mRecentlyReceivedDistantMessageHashes.begin());it!=mRecentlyReceivedDistantMessageHashes.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;
std::map<Sha1CheckSum,uint32_t>::iterator tmp(it) ;
++tmp ;
mRecentlyReceivedDistantMessageHashes.erase(it) ;
it=tmp ;
}
else
++it ;
}
int p3MsgService::status()
{
@ -152,7 +177,7 @@ int p3MsgService::status()
return 1;
}
void p3MsgService::processMsg(RsMsgItem *mi, bool incoming)
void p3MsgService::processIncomingMsg(RsMsgItem *mi)
{
mi -> recvTime = time(NULL);
mi -> msgId = getNewUniqueMsgId();
@ -160,26 +185,19 @@ void p3MsgService::processMsg(RsMsgItem *mi, bool incoming)
{
RsStackMutex stack(mMsgMtx); /*** STACK LOCKED MTX ***/
if (incoming)
/* from a peer */
mi->msgFlags &= (RS_MSG_FLAGS_DISTANT | RS_MSG_FLAGS_SYSTEM); // remove flags except those
mi->msgFlags |= RS_MSG_FLAGS_NEW;
p3Notify *notify = RsServer::notify();
if (notify)
{
/* from a peer */
notify->AddPopupMessage(RS_POPUP_MSG, mi->PeerId().toStdString(), mi->subject, mi->message);
mi->msgFlags &= (RS_MSG_FLAGS_DISTANT | RS_MSG_FLAGS_SYSTEM); // remove flags except those
mi->msgFlags |= RS_MSG_FLAGS_NEW;
p3Notify *notify = RsServer::notify();
if (notify)
{
notify->AddPopupMessage(RS_POPUP_MSG, mi->PeerId().toStdString(), mi->subject, mi->message);
std::string out;
rs_sprintf(out, "%lu", mi->msgId);
notify->AddFeedItem(RS_FEED_ITEM_MESSAGE, out, "", "");
}
}
else
{
mi->msgFlags |= RS_MSG_OUTGOING;
std::string out;
rs_sprintf(out, "%lu", mi->msgId);
notify->AddFeedItem(RS_FEED_ITEM_MESSAGE, out, "", "");
}
imsg[mi->msgId] = mi;
@ -187,13 +205,12 @@ void p3MsgService::processMsg(RsMsgItem *mi, bool incoming)
msi->msgId = mi->msgId;
msi->srcId = mi->PeerId();
mSrcIds.insert(std::pair<uint32_t, RsMsgSrcId*>(msi->msgId, msi));
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
/**** STACK UNLOCKED ***/
}
if (incoming)
{
// If the peer is allowed to push files, then auto-download the recommended files.
if(rsPeers->servicePermissionFlags(mi->PeerId()) & RS_NODE_PERM_ALLOW_PUSH)
{
@ -203,7 +220,6 @@ void p3MsgService::processMsg(RsMsgItem *mi, bool incoming)
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) ;
}
}
RsServer::notify()->notifyListChange(NOTIFY_LIST_MESSAGELIST,NOTIFY_TYPE_ADD);
}
@ -271,7 +287,7 @@ void p3MsgService::handleIncomingItem(RsMsgItem *mi)
if(checkAndRebuildPartialMessage(mi)) // only returns true when a msg is complete.
{
processMsg(mi, true);
processIncomingMsg(mi);
changed = true ;
}
if(changed)
@ -333,96 +349,106 @@ void p3MsgService::checkSizeAndSendMessage(RsMsgItem *msg)
int p3MsgService::checkOutgoingMessages()
{
/* iterate through the outgoing queue
/* iterate through the outgoing queue
*
* if online, send
*/
bool changed = false ;
std::list<RsMsgItem*> output_queue ;
time_t now = time(NULL);
bool changed = false ;
std::list<RsMsgItem*> output_queue ;
{
const RsPeerId& ownId = mServiceCtrl->getOwnId();
{
RS_STACK_MUTEX(mMsgMtx); /********** STACK LOCKED MTX ******/
const RsPeerId& ownId = mServiceCtrl->getOwnId();
std::list<uint32_t>::iterator it;
std::list<uint32_t> toErase;
RsStackMutex stack(mMsgMtx); /********** STACK LOCKED MTX ******/
std::list<uint32_t>::iterator it;
std::list<uint32_t> toErase;
std::map<uint32_t, RsMsgItem *>::iterator mit;
for(mit = msgOutgoing.begin(); mit != msgOutgoing.end(); ++mit)
{
if (mit->second->msgFlags & RS_MSG_FLAGS_TRASH)
continue;
std::map<uint32_t, RsMsgItem *>::iterator mit;
for(mit = msgOutgoing.begin(); mit != msgOutgoing.end(); ++mit)
{
if (mit->second->msgFlags & RS_MSG_FLAGS_TRASH)
continue;
/* find the certificate */
RsPeerId pid = mit->second->PeerId();
/* find the certificate */
RsPeerId pid = mit->second->PeerId();
bool should_send = false ;
if( pid == ownId
|| ( (mit->second->msgFlags & RS_MSG_FLAGS_DISTANT) && (!(mit->second->msgFlags & RS_MSG_FLAGS_ROUTED)))
|| mServiceCtrl->isPeerConnected(getServiceInfo().mServiceType, pid) ) /* FEEDBACK Msg to Ourselves */
{
/* send msg */
pqioutput(PQL_DEBUG_BASIC, msgservicezone,
"p3MsgService::checkOutGoingMessages() Sending out message");
/* remove the pending flag */
if( pid == ownId)
should_send = true ;
output_queue.push_back(mit->second) ;
if( mServiceCtrl->isPeerConnected(getServiceInfo().mServiceType, pid) ) /* FEEDBACK Msg to Ourselves */
should_send = true ;
// When the message is a distant msg, dont remove it yet from the list. Only mark it as being sent, so that we don't send it again.
//
if(!(mit->second->msgFlags & RS_MSG_FLAGS_DISTANT))
{
(mit->second)->msgFlags &= ~RS_MSG_FLAGS_PENDING;
toErase.push_back(mit->first);
changed = true ;
}
else
{
if((mit->second->msgFlags & RS_MSG_FLAGS_DISTANT) && !(mit->second->msgFlags & RS_MSG_FLAGS_ROUTED))
should_send = true ;
if(should_send)
{
/* send msg */
pqioutput(PQL_DEBUG_BASIC, msgservicezone,
"p3MsgService::checkOutGoingMessages() Sending out message");
/* remove the pending flag */
output_queue.push_back(mit->second) ;
// When the message is a distant msg, dont remove it yet from the list. Only mark it as being sent, so that we don't send it again.
//
if(!(mit->second->msgFlags & RS_MSG_FLAGS_DISTANT))
{
(mit->second)->msgFlags &= ~RS_MSG_FLAGS_PENDING;
toErase.push_back(mit->first);
changed = true ;
}
else
{
#ifdef DEBUG_DISTANT_MSG
std::cerr << "Message id " << mit->first << " is distant: kept in outgoing, and marked as ROUTED" << std::endl;
std::cerr << "Message id " << mit->first << " is distant: kept in outgoing, and marked as ROUTED" << std::endl;
#endif
mit->second->msgFlags |= RS_MSG_FLAGS_ROUTED ;
}
}
else
{
pqioutput(PQL_DEBUG_BASIC, msgservicezone,
"p3MsgService::checkOutGoingMessages() Delaying until available...");
}
}
mit->second->msgFlags |= RS_MSG_FLAGS_ROUTED ;
}
}
else
{
pqioutput(PQL_DEBUG_BASIC, msgservicezone,
"p3MsgService::checkOutGoingMessages() Delaying until available...");
}
}
/* clean up */
for(it = toErase.begin(); it != toErase.end(); ++it)
{
mit = msgOutgoing.find(*it);
if (mit != msgOutgoing.end())
{
msgOutgoing.erase(mit);
}
/* clean up */
for(it = toErase.begin(); it != toErase.end(); ++it)
{
mit = msgOutgoing.find(*it);
if (mit != msgOutgoing.end())
{
msgOutgoing.erase(mit);
}
std::map<uint32_t, RsMsgSrcId*>::iterator srcIt = mSrcIds.find(*it);
if (srcIt != mSrcIds.end()) {
delete (srcIt->second);
mSrcIds.erase(srcIt);
}
}
std::map<uint32_t, RsMsgSrcId*>::iterator srcIt = mSrcIds.find(*it);
if (srcIt != mSrcIds.end()) {
delete (srcIt->second);
mSrcIds.erase(srcIt);
}
}
if (toErase.size() > 0)
{
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
}
if (toErase.size() > 0)
{
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
}
}
for(std::list<RsMsgItem*>::const_iterator it(output_queue.begin());it!=output_queue.end();++it)
if((*it)->msgFlags & RS_MSG_FLAGS_DISTANT) // don't split distant messages. The global router takes care of it.
sendDistantMsgItem(*it) ;
else
checkSizeAndSendMessage(*it) ;
if((*it)->msgFlags & RS_MSG_FLAGS_DISTANT) // don't split distant messages. The global router takes care of it.
sendDistantMsgItem(*it) ;
else
checkSizeAndSendMessage(*it) ;
if(changed)
RsServer::notify()->notifyListChange(NOTIFY_LIST_MESSAGELIST,NOTIFY_TYPE_MOD);
if(changed)
RsServer::notify()->notifyListChange(NOTIFY_LIST_MESSAGELIST,NOTIFY_TYPE_MOD);
return 0;
return 0;
}
bool p3MsgService::saveList(bool& cleanup, std::list<RsItem*>& itemList)
@ -463,6 +489,10 @@ bool p3MsgService::saveList(bool& cleanup, std::list<RsItem*>& itemList)
grmap->ongoing_msgs = _ongoing_messages ;
itemList.push_back(grmap) ;
RsMsgDistantMessagesHashMap *ghm = new RsMsgDistantMessagesHashMap ;
ghm->hash_map = mRecentlyReceivedDistantMessageHashes ;
itemList.push_back(ghm) ;
RsConfigKeyValueSet *vitem = new RsConfigKeyValueSet ;
RsTlvKeyValue kv;
@ -485,7 +515,7 @@ void p3MsgService::saveDone()
mMsgMtx.unlock();
}
RsSerialiser* p3MsgService::setupSerialiser()
RsSerialiser* p3MsgService::setupSerialiser() // this serialiser is used for config. So it adds somemore info in the serialised items
{
RsSerialiser *rss = new RsSerialiser ;
@ -544,7 +574,7 @@ bool p3MsgService::loadList(std::list<RsItem*>& load)
RsMsgSrcId* msi;
RsMsgParentId* msp;
RsMsgGRouterMap* grm;
// RsPublicMsgInviteConfigItem* msv;
RsMsgDistantMessagesHashMap *ghm;
std::list<RsMsgItem*> items;
std::list<RsItem*>::iterator it;
@ -552,6 +582,8 @@ bool p3MsgService::loadList(std::list<RsItem*>& load)
std::map<uint32_t, RsPeerId> srcIdMsgMap;
std::map<uint32_t, RsPeerId>::iterator srcIt;
uint32_t max_msg_id = 0 ;
// load items and calculate next unique msgId
for(it = load.begin(); it != load.end(); ++it)
{
@ -559,9 +591,9 @@ bool p3MsgService::loadList(std::list<RsItem*>& load)
if (NULL != (mitem = dynamic_cast<RsMsgItem *>(*it)))
{
/* STORE MsgID */
if (mitem->msgId >= mMsgUniqueId) {
mMsgUniqueId = mitem->msgId + 1;
}
if (mitem->msgId > max_msg_id)
max_msg_id = mitem->msgId ;
items.push_back(mitem);
}
else if (NULL != (grm = dynamic_cast<RsMsgGRouterMap *>(*it)))
@ -570,6 +602,17 @@ bool p3MsgService::loadList(std::list<RsItem*>& load)
for(std::map<GRouterMsgPropagationId,uint32_t>::const_iterator it(grm->ongoing_msgs.begin());it!=grm->ongoing_msgs.end();++it)
_ongoing_messages.insert(*it) ;
}
else if(NULL != (ghm = dynamic_cast<RsMsgDistantMessagesHashMap*>(*it)))
{
mRecentlyReceivedDistantMessageHashes = 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(mRecentlyReceivedDistantMessageHashes.begin());it!=mRecentlyReceivedDistantMessageHashes.end();++it)
std::cerr << " " << it->first << " received " << time(NULL)-it->second << " secs ago." << std::endl;
#endif
}
else if(NULL != (mtt = dynamic_cast<RsMsgTagType *>(*it)))
{
// delete standard tags as they are now save in config
@ -636,6 +679,7 @@ bool p3MsgService::loadList(std::list<RsItem*>& load)
continue ;
}
}
mMsgUniqueId = max_msg_id + 1; // make it unique with respect to what was loaded. Not totally safe, but works 99.9999% of the cases.
load.clear() ;
// sort items into lists
@ -1030,61 +1074,85 @@ bool p3MsgService::setMsgParentId(uint32_t msgId, uint32_t msgParentId)
/****************************************/
/****************************************/
/* Message Items */
uint32_t p3MsgService::sendMessage(RsMsgItem *item)
uint32_t p3MsgService::sendMessage(RsMsgItem *item) // no from field because it's implicitly our own PeerId
{
if(!item)
return 0 ;
return 0 ;
pqioutput(PQL_DEBUG_BASIC, msgservicezone,
"p3MsgService::sendMessage()");
pqioutput(PQL_DEBUG_BASIC, msgservicezone, "p3MsgService::sendMessage()");
item -> msgId = getNewUniqueMsgId(); /* grabs Mtx as well */
item->msgId = getNewUniqueMsgId(); /* grabs Mtx as well */
item->msgFlags |= (RS_MSG_FLAGS_OUTGOING | RS_MSG_FLAGS_PENDING); /* add pending flag */
{
RS_STACK_MUTEX(mMsgMtx) ;
/* STORE MsgID */
msgOutgoing[item->msgId] = item;
if (item->PeerId() != mServiceCtrl->getOwnId())
{
/* not to the loopback device */
RsMsgSrcId* msi = new RsMsgSrcId();
msi->msgId = item->msgId;
msi->srcId = mServiceCtrl->getOwnId();
mSrcIds.insert(std::pair<uint32_t, RsMsgSrcId*>(msi->msgId, msi));
}
}
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
RsServer::notify()->notifyListChange(NOTIFY_LIST_MESSAGELIST, NOTIFY_TYPE_ADD);
return item->msgId;
}
uint32_t p3MsgService::sendDistantMessage(RsMsgItem *item,const RsGxsId& from)
{
if(!item)
return 0 ;
item->msgId = getNewUniqueMsgId(); /* grabs Mtx as well */
item->msgFlags |= (RS_MSG_FLAGS_DISTANT | RS_MSG_FLAGS_OUTGOING | RS_MSG_FLAGS_PENDING); /* add pending flag */
{
RsStackMutex stack(mMsgMtx); /********** STACK LOCKED MTX ******/
RS_STACK_MUTEX(mMsgMtx) ;
/* add pending flag */
item->msgFlags |= (RS_MSG_FLAGS_OUTGOING | RS_MSG_FLAGS_PENDING);
/* STORE MsgID */
msgOutgoing[item->msgId] = item;
mDistantOutgoingMsgSigners[item->msgId] = from ;
if (item->PeerId() != mServiceCtrl->getOwnId()) {
if (item->PeerId() != mServiceCtrl->getOwnId())
{
/* not to the loopback device */
RsMsgSrcId* msi = new RsMsgSrcId();
msi->msgId = item->msgId;
msi->srcId = item->PeerId();
msi->srcId = RsPeerId(from) ;
mSrcIds.insert(std::pair<uint32_t, RsMsgSrcId*>(msi->msgId, msi));
}
}
}
IndicateConfigChanged(); /**** INDICATE MSG CONFIG CHANGED! *****/
RsServer::notify()->notifyListChange(NOTIFY_LIST_MESSAGELIST, NOTIFY_TYPE_ADD);
return item->msgId;
}
uint32_t p3MsgService::sendDistantMessage(RsMsgItem *item,const RsGxsId& from)
{
uint32_t msg_id = sendMessage(item) ;
return item->msgId;
RS_STACK_MUTEX(mMsgMtx) ;
mDistantOutgoingMsgSigners[msg_id] = from ;
return msg_id ;
}
bool p3MsgService::MessageSend(MessageInfo &info)
{
for(std::set<RsPeerId>::const_iterator pit = info.rspeerid_msgto.begin(); pit != info.rspeerid_msgto.end(); ++pit) sendMessage(initMIRsMsg(info, *pit));
for(std::set<RsPeerId>::const_iterator pit = info.rspeerid_msgcc.begin(); pit != info.rspeerid_msgcc.end(); ++pit) sendMessage(initMIRsMsg(info, *pit));
for(std::set<RsPeerId>::const_iterator pit = info.rspeerid_msgbcc.begin(); pit != info.rspeerid_msgbcc.end(); ++pit) sendMessage(initMIRsMsg(info, *pit));
for(std::set<RsPeerId>::const_iterator pit = info.rspeerid_msgto.begin(); pit != info.rspeerid_msgto.end(); ++pit) sendMessage(initMIRsMsg(info, *pit));
for(std::set<RsPeerId>::const_iterator pit = info.rspeerid_msgcc.begin(); pit != info.rspeerid_msgcc.end(); ++pit) sendMessage(initMIRsMsg(info, *pit));
for(std::set<RsPeerId>::const_iterator pit = info.rspeerid_msgbcc.begin(); pit != info.rspeerid_msgbcc.end(); ++pit) sendMessage(initMIRsMsg(info, *pit));
for(std::set<RsGxsId>::const_iterator pit = info.rsgxsid_msgto.begin(); pit != info.rsgxsid_msgto.end(); ++pit) sendDistantMessage(initMIRsMsg(info, *pit),info.rsgxsid_srcId);
for(std::set<RsGxsId>::const_iterator pit = info.rsgxsid_msgcc.begin(); pit != info.rsgxsid_msgcc.end(); ++pit) sendDistantMessage(initMIRsMsg(info, *pit),info.rsgxsid_srcId);
for(std::set<RsGxsId>::const_iterator pit = info.rsgxsid_msgbcc.begin(); pit != info.rsgxsid_msgbcc.end(); ++pit) sendDistantMessage(initMIRsMsg(info, *pit),info.rsgxsid_srcId);
for(std::set<RsGxsId>::const_iterator pit = info.rsgxsid_msgto.begin(); pit != info.rsgxsid_msgto.end(); ++pit) sendDistantMessage(initMIRsMsg(info, *pit),info.rsgxsid_srcId);
for(std::set<RsGxsId>::const_iterator pit = info.rsgxsid_msgcc.begin(); pit != info.rsgxsid_msgcc.end(); ++pit) sendDistantMessage(initMIRsMsg(info, *pit),info.rsgxsid_srcId);
for(std::set<RsGxsId>::const_iterator pit = info.rsgxsid_msgbcc.begin(); pit != info.rsgxsid_msgbcc.end(); ++pit) sendDistantMessage(initMIRsMsg(info, *pit),info.rsgxsid_srcId);
// store message in outgoing list. In order to appear as sent the message needs to have the OUTGOING flg, but no pending flag on.
/* send to ourselves as well */
RsMsgItem *msg = initMIRsMsg(info, mServiceCtrl->getOwnId());
if (msg)
@ -1095,10 +1163,17 @@ bool p3MsgService::MessageSend(MessageInfo &info)
msg->msgFlags |= RS_MSG_FLAGS_SIGNATURE_CHECKS; // this is always true, since we are sending the message
/* use processMsg to get the new msgId */
processMsg(msg, false);
msg->recvTime = time(NULL);
msg->msgId = getNewUniqueMsgId();
msg->msgFlags |= RS_MSG_OUTGOING;
// return new message id
rs_sprintf(info.msgId, "%lu", msg->msgId);
imsg[msg->msgId] = msg;
RsServer::notify()->notifyListChange(NOTIFY_LIST_MESSAGELIST,NOTIFY_TYPE_ADD);
//
// // return new message id
// rs_sprintf(info.msgId, "%lu", msg->msgId);
}
return true;
@ -1138,7 +1213,7 @@ bool p3MsgService::SystemMessage(const std::string &title, const std::string &me
msg->rspeerid_msgto.ids.insert(ownId);
processMsg(msg, true);
processIncomingMsg(msg);
return true;
}
@ -1762,7 +1837,7 @@ void p3MsgService::manageDistantPeers()
{
#ifdef DEBUG_DISTANT_MSG
for(std::list<RsGxsId>::const_iterator it(own_id_list.begin());it!=own_id_list.end();++it)
std::cerr << (b?"Enabling":"Disabling") << " distant messaging, with peer id = " << *it << std::endl;
std::cerr << (mShouldEnableDistantMessaging?"Enabling":"Disabling") << " distant messaging, with peer id = " << *it << std::endl;
#endif
for(std::list<RsGxsId>::const_iterator it(own_id_list.begin());it!=own_id_list.end();++it)
@ -1782,44 +1857,67 @@ void p3MsgService::notifyDataStatus(const GRouterMsgPropagationId& id,uint32_t d
{
if(data_status == GROUTER_CLIENT_SERVICE_DATA_STATUS_FAILED)
{
std::cerr << __PRETTY_FUNCTION__ << ": Not fully implemented. The global router fails to send apacket, but we don't deal with it. Please remind the devs to do it" << std::endl;
return ;
RS_STACK_MUTEX(mMsgMtx); /********** STACK LOCKED MTX ******/
std::cerr << "(WW) p3MsgService::notifyDataStatus: Global router tells us that item ID " << id << " could not be delivered on time." ;
std::map<GRouterMsgPropagationId,uint32_t>::iterator it = _ongoing_messages.find(id) ;
if(it == _ongoing_messages.end())
{
std::cerr << " (EE) cannot find pending message to acknowledge. Weird. grouter id = " << id << std::endl;
return ;
}
uint32_t msg_id = it->second ;
std::cerr << " message id = " << msg_id << std::endl;
std::map<uint32_t,RsMsgItem*>::iterator mit = msgOutgoing.find(msg_id) ;
if(mit == msgOutgoing.end())
{
std::cerr << " (EE) message has been notified as not delivered, but it not on outgoing list. Something's wrong!!" << std::endl;
return ;
}
std::cerr << " reseting the ROUTED flag so that the message is requested again" << std::endl;
mit->second->msgFlags &= ~RS_MSG_FLAGS_ROUTED ; // clear the routed flag so that the message is requested again
return ;
}
if(data_status != GROUTER_CLIENT_SERVICE_DATA_STATUS_RECEIVED)
if(data_status == GROUTER_CLIENT_SERVICE_DATA_STATUS_RECEIVED)
{
std::cerr << "p3MsgService: unhandled data status info from global router for msg ID " << id << ": this is a bug." << std::endl;
return ;
}
RsStackMutex stack(mMsgMtx); /********** STACK LOCKED MTX ******/
RS_STACK_MUTEX(mMsgMtx); /********** STACK LOCKED MTX ******/
#ifdef DEBUG_DISTANT_MSG
std::cerr << "p3MsgService::acknowledgeDataReceived(): acknowledging data received for msg propagation id " << id << std::endl;
std::cerr << "p3MsgService::acknowledgeDataReceived(): acknowledging data received for msg propagation id " << id << std::endl;
#endif
std::map<GRouterMsgPropagationId,uint32_t>::iterator it = _ongoing_messages.find(id) ;
std::map<GRouterMsgPropagationId,uint32_t>::iterator it = _ongoing_messages.find(id) ;
if(it == _ongoing_messages.end())
{
std::cerr << " (EE) cannot find pending message to acknowledge. Weird. grouter id = " << id << std::endl;
return ;
}
if(it == _ongoing_messages.end())
{
std::cerr << " (EE) cannot find pending message to acknowledge. Weird. grouter id = " << id << std::endl;
return ;
}
uint32_t msg_id = it->second ;
uint32_t msg_id = it->second ;
// we should now remove the item from the msgOutgoing list.
std::map<uint32_t,RsMsgItem*>::iterator it2 = msgOutgoing.find(msg_id) ;
// we should now remove the item from the msgOutgoing list.
if(it2 == msgOutgoing.end())
{
std::cerr << "(EE) message has been ACKed, but is not in outgoing list. Something's wrong!!" << std::endl;
return ;
}
std::map<uint32_t,RsMsgItem*>::iterator it2 = msgOutgoing.find(msg_id) ;
delete it2->second ;
msgOutgoing.erase(it2) ;
if(it2 == msgOutgoing.end())
{
std::cerr << "(EE) message has been ACKed, but is not in outgoing list. Something's wrong!!" << std::endl;
return ;
}
RsServer::notify()->notifyListChange(NOTIFY_LIST_MESSAGELIST,NOTIFY_TYPE_ADD);
IndicateConfigChanged() ;
delete it2->second ;
msgOutgoing.erase(it2) ;
RsServer::notify()->notifyListChange(NOTIFY_LIST_MESSAGELIST,NOTIFY_TYPE_ADD);
IndicateConfigChanged() ;
return ;
}
std::cerr << "p3MsgService: unhandled data status info from global router for msg ID " << id << ": this is a bug." << std::endl;
}
bool p3MsgService::acceptDataFromPeer(const RsGxsId& to_gxs_id)
{
@ -1851,8 +1949,20 @@ void p3MsgService::receiveGRouterData(const RsGxsId& destination_key, const RsGx
{
std::cerr << "p3MsgService::receiveGRouterData(): received message item of size " << data_size << ", for key " << destination_key << std::endl;
// first make sure that we havn't already received the data. Since we allow to re-send messages, it's necessary to check.
Sha1CheckSum hash = RsDirUtil::sha1sum(data,data_size) ;
if(mRecentlyReceivedDistantMessageHashes.find(hash) != mRecentlyReceivedDistantMessageHashes.end())
{
std::cerr << "(WW) receiving distant message of hash " << hash << " more than once. This is not a bug, unless it happens very often." << std::endl;
free(data) ;
return ;
}
mRecentlyReceivedDistantMessageHashes[hash] = time(NULL) ;
IndicateConfigChanged() ;
RsItem *item = _serialiser->deserialise(data,&data_size) ;
free(data) ;
RsMsgItem *msg_item = dynamic_cast<RsMsgItem*>(item) ;
@ -1861,9 +1971,9 @@ void p3MsgService::receiveGRouterData(const RsGxsId& destination_key, const RsGx
{
std::cerr << " Encrypted item correctly deserialised. Passing on to incoming list." << std::endl;
msg_item->msgFlags |= RS_MSG_FLAGS_DISTANT ;
/* we expect complete msgs - remove partial flag just in case someone has funny ideas */
msg_item->msgFlags &= ~RS_MSG_FLAGS_PARTIAL;
msg_item->msgFlags |= RS_MSG_FLAGS_DISTANT ;
/* we expect complete msgs - remove partial flag just in case someone has funny ideas */
msg_item->msgFlags &= ~RS_MSG_FLAGS_PARTIAL;
msg_item->PeerId(RsPeerId(signing_key)) ; // hack to pass on GXS id.
handleIncomingItem(msg_item) ;
@ -1877,7 +1987,8 @@ void p3MsgService::sendDistantMsgItem(RsMsgItem *msgitem)
RsGxsId destination_key_id(msgitem->PeerId()) ;
RsGxsId signing_key_id ;
msgitem->msgFlags |= RS_MSG_FLAGS_DISTANT ;
msgitem->msgFlags |= RS_MSG_FLAGS_DISTANT ;// just in case, but normally we should always have this flag set, when ending up here.
{
RS_STACK_MUTEX(mMsgMtx) ;
@ -1899,15 +2010,14 @@ void p3MsgService::sendDistantMsgItem(RsMsgItem *msgitem)
std::cerr << " signing : " << signing_key_id << std::endl;
#endif
// The item is serialized and turned into a generic turtle item.
// The item is serialized and turned into a generic turtle item. Use use the explicit serialiser to make sure that the msgId is not included
uint32_t msg_serialized_rssize = _serialiser->size(msgitem) ;
unsigned char *msg_serialized_data = new unsigned char[msg_serialized_rssize] ;
uint32_t msg_serialized_rssize = msgitem->serial_size(false) ;
RsTemporaryMemory msg_serialized_data(msg_serialized_rssize) ;
if(!_serialiser->serialise(msgitem,msg_serialized_data,&msg_serialized_rssize))
if(!msgitem->serialise(msg_serialized_data,msg_serialized_rssize,false))
{
std::cerr << "(EE) p3MsgService::sendTurtleData(): Serialization error." << std::endl;
delete[] msg_serialized_data ;
return ;
}
#ifdef DEBUG_DISTANT_MSG
@ -1917,8 +2027,6 @@ void p3MsgService::sendDistantMsgItem(RsMsgItem *msgitem)
GRouterMsgPropagationId grouter_message_id ;
mGRouter->sendData(destination_key_id,GROUTER_CLIENT_ID_MESSAGES,msg_serialized_data,msg_serialized_rssize,signing_key_id,grouter_message_id) ;
delete[] msg_serialized_data ;
// now store the grouter id along with the message id, so that we can keep track of received messages
{

View file

@ -56,159 +56,161 @@ class p3IdService;
// Temp tweak to test grouter
class p3MsgService: public p3Service, public p3Config, public pqiServiceMonitor, public GRouterClientService
{
public:
p3MsgService(p3ServiceControl *sc, p3IdService *id_service);
virtual RsServiceInfo getServiceInfo();
public:
p3MsgService(p3ServiceControl *sc, p3IdService *id_service);
virtual RsServiceInfo getServiceInfo();
/* External Interface */
bool getMessageSummaries(std::list<Rs::Msgs::MsgInfoSummary> &msgList);
bool getMessage(const std::string &mid, Rs::Msgs::MessageInfo &msg);
void getMessageCount(unsigned int *pnInbox, unsigned int *pnInboxNew, unsigned int *pnOutbox, unsigned int *pnDraftbox, unsigned int *pnSentbox, unsigned int *pnTrashbox);
/* External Interface */
bool getMessageSummaries(std::list<Rs::Msgs::MsgInfoSummary> &msgList);
bool getMessage(const std::string &mid, Rs::Msgs::MessageInfo &msg);
void getMessageCount(unsigned int *pnInbox, unsigned int *pnInboxNew, unsigned int *pnOutbox, unsigned int *pnDraftbox, unsigned int *pnSentbox, unsigned int *pnTrashbox);
bool decryptMessage(const std::string& mid) ;
bool removeMsgId(const std::string &mid);
bool markMsgIdRead(const std::string &mid, bool bUnreadByUser);
bool setMsgFlag(const std::string &mid, uint32_t flag, uint32_t mask);
bool getMsgParentId(const std::string &msgId, std::string &msgParentId);
// msgParentId == 0 --> remove
bool setMsgParentId(uint32_t msgId, uint32_t msgParentId);
bool decryptMessage(const std::string& mid) ;
bool removeMsgId(const std::string &mid);
bool markMsgIdRead(const std::string &mid, bool bUnreadByUser);
bool setMsgFlag(const std::string &mid, uint32_t flag, uint32_t mask);
bool getMsgParentId(const std::string &msgId, std::string &msgParentId);
// msgParentId == 0 --> remove
bool setMsgParentId(uint32_t msgId, uint32_t msgParentId);
bool MessageSend(Rs::Msgs::MessageInfo &info);
bool SystemMessage(const std::string &title, const std::string &message, uint32_t systemFlag);
bool MessageToDraft(Rs::Msgs::MessageInfo &info, const std::string &msgParentId);
bool MessageToTrash(const std::string &mid, bool bTrash);
bool MessageSend(Rs::Msgs::MessageInfo &info);
bool SystemMessage(const std::string &title, const std::string &message, uint32_t systemFlag);
bool MessageToDraft(Rs::Msgs::MessageInfo &info, const std::string &msgParentId);
bool MessageToTrash(const std::string &mid, bool bTrash);
bool getMessageTagTypes(Rs::Msgs::MsgTagType& tags);
bool setMessageTagType(uint32_t tagId, std::string& text, uint32_t rgb_color);
bool removeMessageTagType(uint32_t tagId);
bool getMessageTagTypes(Rs::Msgs::MsgTagType& tags);
bool setMessageTagType(uint32_t tagId, std::string& text, uint32_t rgb_color);
bool removeMessageTagType(uint32_t tagId);
bool getMessageTag(const std::string &msgId, Rs::Msgs::MsgTagInfo& info);
/* set == false && tagId == 0 --> remove all */
bool setMessageTag(const std::string &msgId, uint32_t tagId, bool set);
bool getMessageTag(const std::string &msgId, Rs::Msgs::MsgTagInfo& info);
/* set == false && tagId == 0 --> remove all */
bool setMessageTag(const std::string &msgId, uint32_t tagId, bool set);
bool resetMessageStandardTagTypes(Rs::Msgs::MsgTagType& tags);
bool resetMessageStandardTagTypes(Rs::Msgs::MsgTagType& tags);
void loadWelcomeMsg(); /* startup message */
void loadWelcomeMsg(); /* startup message */
//std::list<RsMsgItem *> &getMsgList();
//std::list<RsMsgItem *> &getMsgOutList();
int tick();
int status();
//std::list<RsMsgItem *> &getMsgList();
//std::list<RsMsgItem *> &getMsgOutList();
/*** Overloaded from p3Config ****/
virtual RsSerialiser *setupSerialiser();
virtual bool saveList(bool& cleanup, std::list<RsItem*>&);
virtual bool loadList(std::list<RsItem*>& load);
virtual void saveDone();
/*** Overloaded from p3Config ****/
int tick();
int status();
/*** Overloaded from pqiMonitor ***/
virtual void statusChange(const std::list<pqiServicePeer> &plist);
int checkOutgoingMessages();
/*** Overloaded from pqiMonitor ***/
/*** Overloaded from p3Config ****/
virtual RsSerialiser *setupSerialiser();
virtual bool saveList(bool& cleanup, std::list<RsItem*>&);
virtual bool loadList(std::list<RsItem*>& load);
virtual void saveDone();
/*** Overloaded from p3Config ****/
/*** overloaded from p3turtle ***/
/*** Overloaded from pqiMonitor ***/
virtual void statusChange(const std::list<pqiServicePeer> &plist);
int checkOutgoingMessages();
/*** Overloaded from pqiMonitor ***/
virtual void connectToGlobalRouter(p3GRouter *) ;
/*** overloaded from p3turtle ***/
struct DistantMessengingInvite
{
time_t time_of_validity ;
};
struct DistantMessengingContact
{
time_t last_hit_time ;
RsPeerId virtual_peer_id ;
uint32_t status ;
bool pending_messages ;
};
void enableDistantMessaging(bool b) ;
bool distantMessagingEnabled() ;
void setDistantMessagingPermissionFlags(uint32_t flags) ;
uint32_t getDistantMessagingPermissionFlags() ;
virtual void connectToGlobalRouter(p3GRouter *) ;
private:
void sendDistantMsgItem(RsMsgItem *msgitem) ;
struct DistantMessengingInvite
{
time_t time_of_validity ;
};
struct DistantMessengingContact
{
time_t last_hit_time ;
RsPeerId virtual_peer_id ;
uint32_t status ;
bool pending_messages ;
};
void enableDistantMessaging(bool b) ;
bool distantMessagingEnabled() ;
// This contains the ongoing tunnel handling contacts.
// The map is indexed by the hash
//
std::map<GRouterMsgPropagationId,uint32_t> _ongoing_messages ;
void setDistantMessagingPermissionFlags(uint32_t flags) ;
uint32_t getDistantMessagingPermissionFlags() ;
// Overloaded from GRouterClientService
private:
void sendDistantMsgItem(RsMsgItem *msgitem) ;
virtual bool acceptDataFromPeer(const RsGxsId& gxs_id) ;
virtual void receiveGRouterData(const RsGxsId& destination_key,const RsGxsId& signing_key, GRouterServiceId &client_id, uint8_t *data, uint32_t data_size) ;
virtual void notifyDataStatus(const GRouterMsgPropagationId& msg_id,uint32_t data_status) ;
// This contains the ongoing tunnel handling contacts.
// The map is indexed by the hash
//
std::map<GRouterMsgPropagationId,uint32_t> _ongoing_messages ;
// Utility functions
// Overloaded from GRouterClientService
bool createDistantMessage(const RsGxsId& destination_gxs_id,const RsGxsId& source_gxs_id,RsMsgItem *msg) ;
bool locked_findHashForVirtualPeerId(const RsPeerId& pid,Sha1CheckSum& hash) ;
void sendGRouterData(const RsGxsId &key_id,RsMsgItem *) ;
virtual bool acceptDataFromPeer(const RsGxsId& gxs_id) ;
virtual void receiveGRouterData(const RsGxsId& destination_key,const RsGxsId& signing_key, GRouterServiceId &client_id, uint8_t *data, uint32_t data_size) ;
virtual void notifyDataStatus(const GRouterMsgPropagationId& msg_id,uint32_t data_status) ;
void manageDistantPeers() ;
// Utility functions
void handleIncomingItem(RsMsgItem *) ;
bool createDistantMessage(const RsGxsId& destination_gxs_id,const RsGxsId& source_gxs_id,RsMsgItem *msg) ;
bool locked_findHashForVirtualPeerId(const RsPeerId& pid,Sha1CheckSum& hash) ;
void sendGRouterData(const RsGxsId &key_id,RsMsgItem *) ;
uint32_t getNewUniqueMsgId();
uint32_t sendMessage(RsMsgItem *item);
uint32_t sendDistantMessage(RsMsgItem *item,const RsGxsId& signing_gxs_id);
void checkSizeAndSendMessage(RsMsgItem *msg);
void manageDistantPeers() ;
int incomingMsgs();
void processMsg(RsMsgItem *mi, bool incoming);
bool checkAndRebuildPartialMessage(RsMsgItem*) ;
void handleIncomingItem(RsMsgItem *) ;
void initRsMI(RsMsgItem *msg, Rs::Msgs::MessageInfo &mi);
void initRsMIS(RsMsgItem *msg, Rs::Msgs::MsgInfoSummary &mis);
uint32_t getNewUniqueMsgId();
uint32_t sendMessage(RsMsgItem *item);
uint32_t sendDistantMessage(RsMsgItem *item,const RsGxsId& signing_gxs_id);
void checkSizeAndSendMessage(RsMsgItem *msg);
void cleanListOfReceivedMessageHashes();
RsMsgItem *initMIRsMsg(const Rs::Msgs::MessageInfo &info, const RsPeerId& to);
RsMsgItem *initMIRsMsg(const Rs::Msgs::MessageInfo &info, const RsGxsId& to);
void initMIRsMsg(RsMsgItem *item,const Rs::Msgs::MessageInfo &info) ;
int incomingMsgs();
void processIncomingMsg(RsMsgItem *mi) ;
bool checkAndRebuildPartialMessage(RsMsgItem*) ;
void initStandardTagTypes();
void initRsMI(RsMsgItem *msg, Rs::Msgs::MessageInfo &mi);
void initRsMIS(RsMsgItem *msg, Rs::Msgs::MsgInfoSummary &mis);
p3IdService *mIdService ;
p3ServiceControl *mServiceCtrl;
p3GRouter *mGRouter ;
RsMsgItem *initMIRsMsg(const Rs::Msgs::MessageInfo &info, const RsPeerId& to);
RsMsgItem *initMIRsMsg(const Rs::Msgs::MessageInfo &info, const RsGxsId& to);
void initMIRsMsg(RsMsgItem *item,const Rs::Msgs::MessageInfo &info) ;
/* Mutex Required for stuff below */
void initStandardTagTypes();
RsMutex mMsgMtx;
RsMsgSerialiser *_serialiser ;
p3IdService *mIdService ;
p3ServiceControl *mServiceCtrl;
p3GRouter *mGRouter ;
/* stored list of messages */
std::map<uint32_t, RsMsgItem *> imsg;
/* ones that haven't made it out yet! */
std::map<uint32_t, RsMsgItem *> msgOutgoing;
/* Mutex Required for stuff below */
std::map<RsPeerId, RsMsgItem *> _pendingPartialMessages ;
RsMutex mMsgMtx;
RsMsgSerialiser *_serialiser ;
/* maps for tags types and msg tags */
/* stored list of messages */
std::map<uint32_t, RsMsgItem *> imsg;
/* ones that haven't made it out yet! */
std::map<uint32_t, RsMsgItem *> msgOutgoing;
std::map<uint32_t, RsMsgTagType*> mTags;
std::map<uint32_t, RsMsgTags*> mMsgTags;
std::map<RsPeerId, RsMsgItem *> _pendingPartialMessages ;
uint32_t mMsgUniqueId;
/* maps for tags types and msg tags */
// used delete msgSrcIds after config save
std::map<uint32_t, RsMsgSrcId*> mSrcIds;
std::map<uint32_t, RsMsgTagType*> mTags;
std::map<uint32_t, RsMsgTags*> mMsgTags;
// temporary storage. Will not be needed when messages have a proper "from" field. Not saved!
std::map<uint32_t, RsGxsId> mDistantOutgoingMsgSigners;
uint32_t mMsgUniqueId;
std::map<Sha1CheckSum,uint32_t> mRecentlyReceivedDistantMessageHashes;
// save the parent of the messages in draft for replied and forwarded
std::map<uint32_t, RsMsgParentId*> mParentId;
// used delete msgSrcIds after config save
std::map<uint32_t, RsMsgSrcId*> mSrcIds;
std::string config_dir;
// temporary storage. Will not be needed when messages have a proper "from" field. Not saved!
std::map<uint32_t, RsGxsId> mDistantOutgoingMsgSigners;
bool mDistantMessagingEnabled ;
uint32_t mDistantMessagePermissions ;
bool mShouldEnableDistantMessaging ;
// save the parent of the messages in draft for replied and forwarded
std::map<uint32_t, RsMsgParentId*> mParentId;
std::string config_dir;
bool mDistantMessagingEnabled ;
uint32_t mDistantMessagePermissions ;
bool mShouldEnableDistantMessaging ;
};
#endif // MESSAGE_SERVICE_HEADER

View file

@ -26,7 +26,11 @@ bool RsPhotoThumbnail::copyFrom(const RsPhotoThumbnail &nail)
size = nail.size;
type = nail.type;
data = (uint8_t *) malloc(size);
data = (uint8_t *) rs_malloc(size);
if(data == NULL)
return false ;
memcpy(data, nail.data, size);
return true;

View file

@ -36,6 +36,7 @@
#include <stdlib.h>
#include <string.h>
#include <util/rsmemory.h>
#include <iostream>
@ -79,8 +80,10 @@ TcpPacket::TcpPacket(uint8 *ptr, int size)
if (size > 0)
{
datasize = size;
data = (uint8 *) malloc(datasize);
memcpy(data, (void *) ptr, size);
data = (uint8 *) rs_malloc(datasize);
if(data != NULL)
memcpy(data, (void *) ptr, size);
}
return;
}
@ -185,7 +188,17 @@ int TcpPacket::readPacket(void *buf, int size)
free(data);
}
datasize = size - TCP_PSEUDO_HDR_SIZE;
data = (uint8 *) malloc(datasize);
if(datasize == 0) // this happens!
{
data = NULL ;
return 0 ;
}
data = (uint8 *) rs_malloc(datasize);
if(data == NULL)
return 0 ;
/* now the data */
memcpy(data, (void *) &(((uint8 *) buf)[20]), datasize);

View file

@ -26,6 +26,7 @@
#include "udprelay.h"
#include <iostream>
#include <time.h>
#include <util/rsmemory.h>
/*
* #define DEBUG_UDP_RELAY 1
@ -70,7 +71,7 @@ UdpRelayReceiver::UdpRelayReceiver(UdpPublisher *pub)
setRelayClassMax(UDP_RELAY_CLASS_GENERAL, UDP_RELAY_DEFAULT_GENERAL, UDP_RELAY_DEFAULT_BANDWIDTH);
/* only allocate this space once */
mTmpSendPkt = malloc(MAX_RELAY_UDP_PACKET_SIZE);
mTmpSendPkt = rs_malloc(MAX_RELAY_UDP_PACKET_SIZE);
mTmpSendSize = MAX_RELAY_UDP_PACKET_SIZE;
clearDataTransferred();

View file

@ -29,6 +29,7 @@
#include "util/rsrandom.h"
#include "util/rsprint.h"
#include "util/rsmemory.h"
#include "util/rsstring.h"
static const int STUN_TTL = 64;
@ -535,7 +536,11 @@ bool UdpStun_generate_stun_pkt(void *stun_pkt, int *len)
void *UdpStun_generate_stun_reply(struct sockaddr_in *stun_addr, int *len)
{
/* just the header */
void *stun_pkt = malloc(28);
void *stun_pkt = rs_malloc(28);
if(!stun_pkt)
return NULL ;
((uint16_t *) stun_pkt)[0] = (uint16_t) htons(0x0101);
((uint16_t *) stun_pkt)[1] = (uint16_t) htons(28); /* only header + 8 byte addr */
/* transaction id - should be random */

View file

@ -284,19 +284,24 @@ RsTurtleRegExpSearchRequestItem::RsTurtleRegExpSearchRequestItem(void *data,uint
uint32_t n =0 ;
ok &= getRawUInt32(data,pktsize,&offset,&n) ;
expr._tokens.resize(n) ;
if(ok)
expr._tokens.resize(n) ;
for(uint32_t i=0;i<n;++i) ok &= getRawUInt8(data,pktsize,&offset,&expr._tokens[i]) ;
for(uint32_t i=0;i<n && ok;++i) ok &= getRawUInt8(data,pktsize,&offset,&expr._tokens[i]) ;
ok &= getRawUInt32(data,pktsize,&offset,&n) ;
expr._ints.resize(n) ;
for(uint32_t i=0;i<n;++i) ok &= getRawUInt32(data,pktsize,&offset,&expr._ints[i]) ;
if(ok)
expr._ints.resize(n) ;
ok &= getRawUInt32(data,pktsize,&offset,&n) ;
for(uint32_t i=0;i<n && ok;++i) ok &= getRawUInt32(data,pktsize,&offset,&expr._ints[i]) ;
ok &= getRawUInt32(data,pktsize,&offset,&n) ;
if(ok)
expr._strings.resize(n) ;
for(uint32_t i=0;i<n;++i) ok &= GetTlvString(data, pktsize, &offset, TLV_TYPE_STR_VALUE, expr._strings[i]);
for(uint32_t i=0;i<n && ok;++i) ok &= GetTlvString(data, pktsize, &offset, TLV_TYPE_STR_VALUE, expr._strings[i]);
#ifdef WINDOWS_SYS // No Exceptions in Windows compile. (drbobs).
UNREFERENCED_LOCAL_VARIABLE(rssize);
@ -531,6 +536,9 @@ RsTurtleGenericDataItem::RsTurtleGenericDataItem(void *data,uint32_t pktsize)
uint32_t offset = 8; // skip the header
uint32_t rssize = getRsItemSize(data);
if(rssize > pktsize)
throw std::runtime_error("RsTurtleTunnelOkItem::() wrong rssize (exceeds pktsize).") ;
/* add mandatory parts first */
bool ok = true ;
@ -540,7 +548,11 @@ RsTurtleGenericDataItem::RsTurtleGenericDataItem(void *data,uint32_t pktsize)
#ifdef P3TURTLE_DEBUG
std::cerr << " request_id=" << (void*)request_id << ", tunnel_id=" << (void*)tunnel_id << std::endl ;
#endif
data_bytes = malloc(data_size) ;
if(data_size > rssize || rssize - data_size < offset)
throw std::runtime_error("RsTurtleTunnelOkItem::() wrong data_size (exceeds rssize).") ;
data_bytes = rs_malloc(data_size) ;
if(data_bytes != NULL)
{
@ -548,10 +560,7 @@ RsTurtleGenericDataItem::RsTurtleGenericDataItem(void *data,uint32_t pktsize)
offset += data_size ;
}
else
{
std::cerr << "(EE) RsTurtleGenericDataItem: Error. Cannot allocate data for a size of " << data_size << " bytes." <<std::endl;
offset = 0 ; // generate an error
}
#ifdef WINDOWS_SYS // No Exceptions in Windows compile. (drbobs).
UNREFERENCED_LOCAL_VARIABLE(rssize);

View file

@ -30,6 +30,7 @@
#include <assert.h>
#include "rscompress.h"
#include "zlib.h"
#include "util/rsmemory.h"
// 16K buffer size.
//
@ -42,7 +43,10 @@ bool RsCompress::compress_memory_chunk(const uint8_t *input_mem,const uint32_t i
uint32_t output_offset = 0 ;
uint32_t input_offset = 0 ;
output_size = 1024 ;
output_mem = (uint8_t*)malloc(output_size) ;
output_mem = (uint8_t*)rs_malloc(output_size) ;
if(!output_mem)
return false ;
int ret, flush;
unsigned have;
@ -113,8 +117,11 @@ bool RsCompress::uncompress_memory_chunk(const uint8_t *input_mem,const uint32_t
output_size = input_size ;
uint32_t output_offset = 0 ;
uint32_t input_offset = 0 ;
output_mem = (uint8_t*)malloc(output_size) ;
output_mem = (uint8_t*)rs_malloc(output_size) ;
if(!output_mem)
return false ;
int ret;
unsigned have;
z_stream strm;

View file

@ -33,6 +33,7 @@
#include "util/rsdir.h"
#include "util/rsstring.h"
#include "util/rsrandom.h"
#include "util/rsmemory.h"
#include "retroshare/rstypes.h"
#include "rsthreads.h"
#include <iostream>
@ -267,7 +268,14 @@ bool RsDirUtil::copyFile(const std::string& source,const std::string& dest)
size_t T=0;
static const int BUFF_SIZE = 10485760 ; // 10 MB buffer to speed things up.
void *buffer = malloc(BUFF_SIZE) ;
RsTemporaryMemory buffer(BUFF_SIZE) ;
if(!buffer)
{
fclose(in) ;
fclose(out) ;
return false ;
}
bool bRet = true;
@ -286,8 +294,6 @@ bool RsDirUtil::copyFile(const std::string& source,const std::string& dest)
fclose(in) ;
fclose(out) ;
free(buffer) ;
return true ;
#endif

View file

@ -0,0 +1,32 @@
#include "util/rsmemory.h"
void *rs_malloc(size_t size)
{
static const size_t SAFE_MEMALLOC_THRESHOLD = 1024*1024*1024 ; // 1Gb should be enough for everything!
if(size == 0)
{
std::cerr << "(EE) Memory allocation error. A chunk of size 0 was requested. Callstack:" << std::endl;
print_stacktrace() ;
return NULL ;
}
if(size > SAFE_MEMALLOC_THRESHOLD)
{
std::cerr << "(EE) Memory allocation error. A chunk of size 0 was requested. Callstack:" << std::endl;
print_stacktrace() ;
return NULL ;
}
void *mem = malloc(size) ;
if(mem == NULL)
{
std::cerr << "(EE) Memory allocation error for a chunk of " << size << " bytes. Callstack:" << std::endl;
print_stacktrace() ;
return NULL ;
}
return mem ;
}

View file

@ -1,6 +1,10 @@
#pragma once
#include <stdlib.h>
#include <iostream>
#include <util/stacktrace.h>
void *rs_malloc(size_t size) ;
// This is a scope guard to release the memory block when going of of the current scope.
// Can be very useful to auto-delete some memory on quit without the need to call free each time.
@ -24,7 +28,7 @@ class RsTemporaryMemory
public:
RsTemporaryMemory(size_t s)
{
_mem = (unsigned char *)malloc(s) ;
_mem = (unsigned char *)rs_malloc(s) ;
if(_mem)
_size = s ;
@ -53,5 +57,3 @@ private:
RsTemporaryMemory& operator=(const RsTemporaryMemory&) { return *this ;}
RsTemporaryMemory(const RsTemporaryMemory&) {}
};

View file

@ -145,7 +145,12 @@ bool RsRecogn::loadSigningKeys(std::map<RsGxsId, RsGxsRecognSignerItem *> &signM
/* store in */
uint32_t datalen = recognSerialiser.size(item);
uint8_t *data = (uint8_t *) malloc(datalen);
RsTemporaryMemory data(datalen) ;
if(!data)
return false ;
uint32_t pktlen = datalen;
int signOk = 0;
@ -181,8 +186,6 @@ bool RsRecogn::loadSigningKeys(std::map<RsGxsId, RsGxsRecognSignerItem *> &signM
#endif // DEBUG_RECOGN
delete item;
}
free(data);
}
/* clean up */
@ -233,7 +236,12 @@ bool RsRecogn::validateTagSignature(RsGxsRecognSignerItem *signer, RsGxsRecognTa
RsGxsRecognSerialiser serialiser;
uint32_t datalen = serialiser.size(item);
uint8_t *data = (uint8_t *) malloc(datalen);
RsTemporaryMemory data(datalen) ;
if(!data)
return false ;
int signOk = 0;
uint32_t pktlen = datalen;
@ -262,8 +270,6 @@ bool RsRecogn::validateTagSignature(RsGxsRecognSignerItem *signer, RsGxsRecognTa
EVP_MD_CTX_destroy(mdctx);
EVP_PKEY_free(signKey);
free(data);
return (signOk == 1);
}

View file

@ -1,6 +1,7 @@
#include <iostream>
#include "smallobject.h"
#include "util/rsthreads.h"
#include "util/rsmemory.h"
using namespace RsMemoryManagement ;
@ -206,7 +207,7 @@ SmallObjectAllocator::~SmallObjectAllocator()
void *SmallObjectAllocator::allocate(size_t bytes)
{
if(bytes > _maxObjectSize)
return malloc(bytes) ;
return rs_malloc(bytes) ;
else if(_lastAlloc != NULL && _lastAlloc->blockSize() == bytes)
return _lastAlloc->allocate() ;
else