Commit 51814f48 authored by Pavel Vainerman's avatar Pavel Vainerman

Исправления после проверки coverity (v12162/p10326) // первая часть

parent 3c50182e
...@@ -138,8 +138,13 @@ int main(int argc, char** argv) ...@@ -138,8 +138,13 @@ int main(int argc, char** argv)
int optindex = 0; int optindex = 0;
char opt = 0; char opt = 0;
while( (opt = getopt_long(argc, argv, "hc:beosfur:l:i:x:g:w:y:p:vq", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "hc:beosfur:l:i:x:g:w:y:p:vq", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) //разбираем параметры switch (opt) //разбираем параметры
{ {
case 'h': //--help case 'h': //--help
...@@ -369,6 +374,8 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository ...@@ -369,6 +374,8 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository
if( verb ) if( verb )
cout << "\n||=======******** " << section << " ********=========||\n" << endl; cout << "\n||=======******** " << section << " ********=========||\n" << endl;
std::ios_base::fmtflags old_flags = cout.flags();
try try
{ {
ListObjectName ls; ListObjectName ls;
...@@ -474,6 +481,7 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository ...@@ -474,6 +481,7 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository
if( !quiet ) if( !quiet )
cout << "неизвестная команда -" << cmd << endl; cout << "неизвестная команда -" << cmd << endl;
cout.setf(old_flags);
return false; return false;
} }
} }
...@@ -497,9 +505,11 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository ...@@ -497,9 +505,11 @@ static bool commandToAll(const string& section, std::shared_ptr<ObjectRepository
} }
catch( ORepFailed ) catch( ORepFailed )
{ {
cout.setf(old_flags);
return false; return false;
} }
cout.setf(old_flags);
return true; return true;
} }
...@@ -521,6 +531,7 @@ static void createSections( const std::shared_ptr<UniSetTypes::Configuration>& r ...@@ -521,6 +531,7 @@ static void createSections( const std::shared_ptr<UniSetTypes::Configuration>& r
// ============================================================================================== // ==============================================================================================
int omap() int omap()
{ {
std::ios_base::fmtflags old_flags = cout.flags();
try try
{ {
cout.setf(ios::left, ios::adjustfield); cout.setf(ios::left, ios::adjustfield);
...@@ -533,6 +544,7 @@ int omap() ...@@ -533,6 +544,7 @@ int omap()
if( !quiet ) if( !quiet )
cerr << " configuration init failed: " << ex << endl; cerr << " configuration init failed: " << ex << endl;
cout.setf(old_flags);
return 1; return 1;
} }
catch( const std::exception& ex ) catch( const std::exception& ex )
...@@ -540,9 +552,11 @@ int omap() ...@@ -540,9 +552,11 @@ int omap()
if( !quiet ) if( !quiet )
cerr << "std::exception: " << ex.what() << endl; cerr << "std::exception: " << ex.what() << endl;
cout.setf(old_flags);
return 1; return 1;
} }
cout.setf(old_flags);
return 0; return 0;
} }
......
...@@ -51,8 +51,12 @@ int main( int argc, char** argv ) ...@@ -51,8 +51,12 @@ int main( int argc, char** argv )
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:d:s:yc:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "hva:d:s:yc:", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -124,8 +124,12 @@ int main( int argc, char** argv ) ...@@ -124,8 +124,12 @@ int main( int argc, char** argv )
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:w:z:m:r:x:c:b:d:s:t:qn:u:yl:t:o:e:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "hva:w:z:m:r:x:c:b:d:s:t:qn:u:yl:t:o:e:", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -48,8 +48,11 @@ int main( int argc, char** argv ) ...@@ -48,8 +48,11 @@ int main( int argc, char** argv )
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:d:s:c:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "hva:d:s:c:", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -47,8 +47,12 @@ int main( int argc, char** argv ) ...@@ -47,8 +47,12 @@ int main( int argc, char** argv )
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:p:i:bc:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "hva:p:i:bc:", longopts, &optindex);
if( opt != -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -36,8 +36,12 @@ int main( int argc, char* argv[], char* envp[] ) ...@@ -36,8 +36,12 @@ int main( int argc, char* argv[], char* envp[] )
try try
{ {
while( (opt = getopt_long(argc, argv, "hvi:p:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "hvi:p:", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -79,8 +79,12 @@ int main( int argc, char** argv ) ...@@ -79,8 +79,12 @@ int main( int argc, char** argv )
try try
{ {
while( (opt = getopt_long(argc, argv, "chvlf:a:p:i:d:s:n:eorbx:w:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "chvlf:a:p:i:d:s:n:eorbx:w:", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -48,8 +48,12 @@ int main( int argc, char** argv ) ...@@ -48,8 +48,12 @@ int main( int argc, char** argv )
try try
{ {
while( (opt = getopt_long(argc, argv, "hvi:p:d:m:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "hvi:p:d:m:", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -83,8 +83,12 @@ int main(int argc, char* argv[]) ...@@ -83,8 +83,12 @@ int main(int argc, char* argv[])
int optindex = 0; int optindex = 0;
int opt = 0; int opt = 0;
while( (opt = getopt_long(argc, argv, "hr:s:d:a:x:o:f:n:i:c:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "hr:s:d:a:x:o:f:n:i:c:", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -68,8 +68,12 @@ int main(int argc, char* argv[]) ...@@ -68,8 +68,12 @@ int main(int argc, char* argv[])
memset(chan, -1, sizeof(chan)); memset(chan, -1, sizeof(chan));
while( (opt = getopt_long(argc, argv, "habvr:w:i:o:s:d:c:p:m:q:x:z:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "habvr:w:i:o:s:d:c:p:m:q:x:z:", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -76,8 +76,12 @@ int main( int argc, char** argv ) ...@@ -76,8 +76,12 @@ int main( int argc, char** argv )
try try
{ {
while( (opt = getopt_long(argc, argv, "hvyq:r:d:s:t:x:m:n:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "hvyq:r:d:s:t:x:m:n:", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -102,8 +102,12 @@ int main( int argc, char** argv ) ...@@ -102,8 +102,12 @@ int main( int argc, char** argv )
try try
{ {
while( (opt = getopt_long(argc, argv, "hvw:r:x:d:s:t:l:n:yb:e:x:z:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "hvw:r:x:d:s:t:l:n:yb:e:x:z:", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -44,8 +44,12 @@ int main( int argc, char** argv ) ...@@ -44,8 +44,12 @@ int main( int argc, char** argv )
try try
{ {
while( (opt = getopt_long(argc, argv, "hva:d:s:t:q:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "hva:d:s:t:q:", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -167,7 +167,7 @@ class UNetReceiver: ...@@ -167,7 +167,7 @@ class UNetReceiver:
std::shared_ptr<ost::UDPReceive> udp; std::shared_ptr<ost::UDPReceive> udp;
ost::IPV4Address addr; ost::IPV4Address addr;
ost::tpport_t port; ost::tpport_t port = { 0 };
std::string myname; std::string myname;
UniSetTypes::uniset_rwmutex pollMutex; UniSetTypes::uniset_rwmutex pollMutex;
...@@ -177,15 +177,15 @@ class UNetReceiver: ...@@ -177,15 +177,15 @@ class UNetReceiver:
timeout_t prepareTime; timeout_t prepareTime;
timeout_t lostTimeout; timeout_t lostTimeout;
PassiveTimer ptLostTimeout; PassiveTimer ptLostTimeout;
unsigned long lostPackets; /*!< счётчик потерянных пакетов */ unsigned long lostPackets = { 0 }; /*!< счётчик потерянных пакетов */
UniSetTypes::ObjectId sidRespond; UniSetTypes::ObjectId sidRespond = { UniSetTypes::DefaultObjectId };
IOController::IOStateList::iterator itRespond; IOController::IOStateList::iterator itRespond;
bool respondInvert; bool respondInvert = { false };
UniSetTypes::ObjectId sidLostPackets; UniSetTypes::ObjectId sidLostPackets;
IOController::IOStateList::iterator itLostPackets; IOController::IOStateList::iterator itLostPackets;
std::atomic_bool activated; std::atomic_bool activated = { false };
std::shared_ptr< ThreadCreator<UNetReceiver> > r_thr; // receive thread std::shared_ptr< ThreadCreator<UNetReceiver> > r_thr; // receive thread
std::shared_ptr< ThreadCreator<UNetReceiver> > u_thr; // update thread std::shared_ptr< ThreadCreator<UNetReceiver> > u_thr; // update thread
...@@ -199,15 +199,15 @@ class UNetReceiver: ...@@ -199,15 +199,15 @@ class UNetReceiver:
/*! максимальная разница межд номерами пакетов, при которой считается, что счётчик пакетов /*! максимальная разница межд номерами пакетов, при которой считается, что счётчик пакетов
* прошёл через максимум или сбился... * прошёл через максимум или сбился...
*/ */
unsigned long maxDifferens; unsigned long maxDifferens = { 20 };
PacketQueue qtmp; /*!< очередь на время обработки(очистки) основной очереди */ PacketQueue qtmp; /*!< очередь на время обработки(очистки) основной очереди */
bool waitClean; /*!< флаг означающий, что ждём очистики очереди до конца */ bool waitClean = { false }; /*!< флаг означающий, что ждём очистики очереди до конца */
unsigned long rnum; /*!< текущий номер принятого сообщения, для проверки "переполнения" или "сбоя" счётчика */ unsigned long rnum = { 0 }; /*!< текущий номер принятого сообщения, для проверки "переполнения" или "сбоя" счётчика */
int maxProcessingCount; /*!< максимальное число обрабатываемых за один раз сообщений */ int maxProcessingCount; /*!< максимальное число обрабатываемых за один раз сообщений */
bool lockUpdate; /*!< флаг блокировки сохранения принятых данных в SM */ bool lockUpdate = { false }; /*!< флаг блокировки сохранения принятых данных в SM */
UniSetTypes::uniset_rwmutex lockMutex; UniSetTypes::uniset_rwmutex lockMutex;
EventSlot slEvent; EventSlot slEvent;
...@@ -239,8 +239,8 @@ class UNetReceiver: ...@@ -239,8 +239,8 @@ class UNetReceiver:
CacheMap d_icache_map; /*!< кэш итераторов для булевых */ CacheMap d_icache_map; /*!< кэш итераторов для булевых */
CacheMap a_icache_map; /*!< кэш итераторов для аналоговых */ CacheMap a_icache_map; /*!< кэш итераторов для аналоговых */
bool d_cache_init_ok; bool d_cache_init_ok = { false };
bool a_cache_init_ok; bool a_cache_init_ok = { false };
void initDCache( UniSetUDP::UDPMessage& pack, bool force = false ); void initDCache( UniSetUDP::UDPMessage& pack, bool force = false );
void initACache( UniSetUDP::UDPMessage& pack, bool force = false ); void initACache( UniSetUDP::UDPMessage& pack, bool force = false );
......
...@@ -123,9 +123,9 @@ class UNetSender ...@@ -123,9 +123,9 @@ class UNetSender
protected: protected:
std::string s_field; std::string s_field = { "" };
std::string s_fvalue; std::string s_fvalue = { "" };
std::string prefix; std::string prefix = { "" };
const std::shared_ptr<SMInterface> shm; const std::shared_ptr<SMInterface> shm;
std::shared_ptr<DebugStream> unetlog; std::shared_ptr<DebugStream> unetlog;
...@@ -140,13 +140,13 @@ class UNetSender ...@@ -140,13 +140,13 @@ class UNetSender
std::shared_ptr<ost::UDPBroadcast> udp; std::shared_ptr<ost::UDPBroadcast> udp;
ost::IPV4Address addr; ost::IPV4Address addr;
ost::tpport_t port; ost::tpport_t port = { 0 };
std::string s_host; std::string s_host = { "" };
std::string myname; std::string myname = { "" };
int sendpause; int sendpause = { 150 };
int packsendpause; int packsendpause = { 5 };
std::atomic_bool activated; std::atomic_bool activated = { false };
UniSetTypes::uniset_rwmutex pack_mutex; UniSetTypes::uniset_rwmutex pack_mutex;
...@@ -156,13 +156,13 @@ class UNetSender ...@@ -156,13 +156,13 @@ class UNetSender
std::unordered_map<sendfactor_t, int> packs_anum; std::unordered_map<sendfactor_t, int> packs_anum;
std::unordered_map<sendfactor_t, int> packs_dnum; std::unordered_map<sendfactor_t, int> packs_dnum;
DMap dlist; DMap dlist;
int maxItem; int maxItem = { 0 };
unsigned long packetnum; /*!< номер очередного посылаемого пакета */ unsigned long packetnum = { 1 }; /*!< номер очередного посылаемого пакета */
unsigned short lastcrc; unsigned short lastcrc = { 0 };
UniSetUDP::UDPPacket s_msg; UniSetUDP::UDPPacket s_msg;
size_t maxAData; size_t maxAData = { UniSetUDP::MaxACount };
size_t maxDData; size_t maxDData = { UniSetUDP::MaxDCount };
std::shared_ptr< ThreadCreator<UNetSender> > s_thr; // send thread std::shared_ptr< ThreadCreator<UNetSender> > s_thr; // send thread
......
...@@ -73,8 +73,12 @@ int main(int argc, char* argv[]) ...@@ -73,8 +73,12 @@ int main(int argc, char* argv[])
int ncycles = -1; int ncycles = -1;
unsigned int nprof = 0; unsigned int nprof = 0;
while( (opt = getopt_long(argc, argv, "hs:c:r:p:n:t:x:blvdz:y:", longopts, &optindex)) != -1 ) while(1)
{ {
opt = getopt_long(argc, argv, "hs:c:r:p:n:t:x:blvdz:y:", longopts, &optindex);
if( opt == -1 )
break;
switch (opt) switch (opt)
{ {
case 'h': case 'h':
......
...@@ -58,9 +58,9 @@ class UniExchange: ...@@ -58,9 +58,9 @@ class UniExchange:
virtual void askSensors( UniversalIO::UIOCommand cmd ); virtual void askSensors( UniversalIO::UIOCommand cmd );
virtual void sigterm( int signo ) override; virtual void sigterm( int signo ) override;
xmlNode* cnode; xmlNode* cnode = { 0 };
std::string s_field; std::string s_field = { "" };
std::string s_fvalue; std::string s_fvalue = { "" };
std::shared_ptr<SMInterface> shm; std::shared_ptr<SMInterface> shm;
struct SInfo struct SInfo
...@@ -118,13 +118,13 @@ class UniExchange: ...@@ -118,13 +118,13 @@ class UniExchange:
void updateLocalData(); void updateLocalData();
void initIterators(); void initIterators();
int polltime; int polltime = { 200 };
PassiveTimer ptUpdate; PassiveTimer ptUpdate;
bool init_ok; bool init_ok = { false };
SList mymap; SList mymap;
size_t maxIndex; size_t maxIndex = { 0 };
int smReadyTimeout; int smReadyTimeout = { 15000 }; // msec
private: private:
}; };
......
...@@ -64,6 +64,7 @@ struct IOBase ...@@ -64,6 +64,7 @@ struct IOBase
si.id = UniSetTypes::DefaultObjectId; si.id = UniSetTypes::DefaultObjectId;
si.node = UniSetTypes::DefaultObjectId; si.node = UniSetTypes::DefaultObjectId;
cal.minRaw = cal.maxRaw = cal.minCal = cal.maxCal = cal.precision = 0; cal.minRaw = cal.maxRaw = cal.minCal = cal.maxCal = cal.precision = 0;
ti.invert = false;
} }
bool check_channel_break( long val ); /*!< проверка обрыва провода */ bool check_channel_break( long val ); /*!< проверка обрыва провода */
......
...@@ -112,18 +112,18 @@ class ComPort ...@@ -112,18 +112,18 @@ class ComPort
static const int BufSize = 8192; static const int BufSize = 8192;
unsigned char buf[BufSize]; unsigned char buf[BufSize];
int curSym; int curSym = { 0 };
int bufLength; int bufLength = { 0 };
int fd; int fd = { -1 };
int uTimeout; int uTimeout = { 0 };
bool waiting; bool waiting = { false };
Speed speed; Speed speed = ComSpeed38400;
std::string dev; std::string dev = { "" };
virtual unsigned char m_receiveByte( bool wait ); virtual unsigned char m_receiveByte( bool wait );
private: private:
struct termios oldTermios; struct termios oldTermios = { 0 };
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#endif // _COMPORT_H_ #endif // _COMPORT_H_
......
...@@ -46,7 +46,7 @@ class ComPort485F: ...@@ -46,7 +46,7 @@ class ComPort485F:
int gpio_num; int gpio_num;
bool tmit_ctrl_on; bool tmit_ctrl_on;
PassiveTimer ptRecv; PassiveTimer ptRecv;
int tout_msec; int tout_msec = { 2000 };
}; };
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
#endif // _COMPORT_E_H_ #endif // _COMPORT_E_H_
......
...@@ -267,54 +267,54 @@ namespace UniSetTypes ...@@ -267,54 +267,54 @@ namespace UniSetTypes
std::string getPort( const std::string& port = "" ); std::string getPort( const std::string& port = "" );
std::string rootDir; std::string rootDir = { "" };
std::shared_ptr<UniXML> unixml; std::shared_ptr<UniXML> unixml;
int _argc; int _argc = { 0 };
const char* const* _argv; const char* const* _argv;
CORBA::ORB_var orb; CORBA::ORB_var orb;
CORBA::PolicyList policyList; CORBA::PolicyList policyList;
std::string NSName; /*!< имя сервиса именования на ланной машине (обычно "NameService") */ std::string NSName = { "" }; /*!< имя сервиса именования на ланной машине (обычно "NameService") */
unsigned int countOfNet; /*!< количество резервных каналов */ unsigned int countOfNet = { 1 }; /*!< количество резервных каналов */
unsigned int repeatCount; /*!< количество попыток получить доступ к удаленному объекту unsigned int repeatCount = { 3 }; /*!< количество попыток получить доступ к удаленному объекту
прежде чем будет выработано исключение TimeOut. */ прежде чем будет выработано исключение TimeOut. */
unsigned int repeatTimeout; /*!< пауза между попытками [мс] */ unsigned int repeatTimeout = { 50 }; /*!< пауза между попытками [мс] */
UniSetTypes::ListOfNode lnodes; UniSetTypes::ListOfNode lnodes;
// repository // repository
std::string secRoot; std::string secRoot = { "" };
std::string secSensors; std::string secSensors = { "" };
std::string secObjects; std::string secObjects = { "" };
std::string secControlles; std::string secControlles = { "" };
std::string secServices; std::string secServices = { "" };
// xml // xml
xmlNode* xmlSensorsSec; xmlNode* xmlSensorsSec = { 0 };
xmlNode* xmlObjectsSec; xmlNode* xmlObjectsSec = { 0 };
xmlNode* xmlControllersSec; xmlNode* xmlControllersSec = { 0 };
xmlNode* xmlServicesSec; xmlNode* xmlServicesSec = { 0 };
xmlNode* xmlNodesSec; xmlNode* xmlNodesSec = { 0 };
ObjectId localDBServer; ObjectId localDBServer = { UniSetTypes::DefaultObjectId };
ObjectId localNode; ObjectId localNode = { UniSetTypes::DefaultObjectId };
std::string localNodeName; std::string localNodeName = { "" };
std::string fileConfName; std::string fileConfName = { "" };
std::string imagesDir; std::string imagesDir = { "" };
std::string confDir; std::string confDir = { "" };
std::string dataDir; std::string dataDir = { "" };
std::string binDir; std::string binDir = { "" };
std::string logDir; std::string logDir = { "" };
std::string docDir; std::string docDir = { "" };
std::string lockDir; std::string lockDir = { "" };
bool localIOR; bool localIOR = { false };
bool transientIOR; bool transientIOR = { false };
int heartbeat_msec; int heartbeat_msec = { 3000 };
}; };
/*! Глобальный указатель на конфигурацию (singleton) */ /*! Глобальный указатель на конфигурацию (singleton) */
......
...@@ -294,6 +294,7 @@ class IOController: ...@@ -294,6 +294,7 @@ class IOController:
{ {
d_si.id = UniSetTypes::DefaultObjectId; d_si.id = UniSetTypes::DefaultObjectId;
d_si.node = UniSetTypes::DefaultObjectId; d_si.node = UniSetTypes::DefaultObjectId;
default_val = 0;
value = default_val; value = default_val;
real_value = default_val; real_value = default_val;
dbignore = false; dbignore = false;
......
...@@ -266,7 +266,7 @@ class IONotifyController: ...@@ -266,7 +266,7 @@ class IONotifyController:
UniSetTypes::uniset_rwmutex mut; UniSetTypes::uniset_rwmutex mut;
IOController_i::SensorInfo si; /*!< аналоговый датчик */ IOController_i::SensorInfo si; /*!< аналоговый датчик */
std::shared_ptr<USensorInfo> ait; std::shared_ptr<USensorInfo> ait;
UniversalIO::IOType type; UniversalIO::IOType type = { UniversalIO::AI };
ThresholdExtList list; /*!< список порогов по данному аналоговому датчику */ ThresholdExtList list; /*!< список порогов по данному аналоговому датчику */
}; };
......
...@@ -69,16 +69,16 @@ class LogReader ...@@ -69,16 +69,16 @@ class LogReader
void logOnEvent( const std::string& s ); void logOnEvent( const std::string& s );
void sendCommand(LogServerTypes::lsMessage& msg, bool verbose = false ); void sendCommand(LogServerTypes::lsMessage& msg, bool verbose = false );
timeout_t inTimeout; timeout_t inTimeout = { 10000 };
timeout_t outTimeout; timeout_t outTimeout = { 6000 };
timeout_t reconDelay; timeout_t reconDelay = { 5000 };
private: private:
std::shared_ptr<UTCPStream> tcp; std::shared_ptr<UTCPStream> tcp;
std::string iaddr; std::string iaddr = { "" };
ost::tpport_t port; ost::tpport_t port = { 0 };
bool cmdonly; bool cmdonly { false };
unsigned int readcount; // количество циклов чтения unsigned int readcount = { 0 }; // количество циклов чтения
DebugStream rlog; DebugStream rlog;
DebugStream log; // рабочий лог в который выводиться полученная информация.. DebugStream log; // рабочий лог в который выводиться полученная информация..
......
...@@ -56,16 +56,17 @@ class LogSession: ...@@ -56,16 +56,17 @@ class LogSession:
void logOnEvent( const std::string& s ); void logOnEvent( const std::string& s );
void readStream(); void readStream();
timeout_t sessTimeout; // msec
timeout_t cmdTimeout; timeout_t sessTimeout = { 10000 };
timeout_t outTimeout; timeout_t cmdTimeout = { 2000 };
timeout_t delayTime; timeout_t outTimeout = { 2000 };
timeout_t delayTime = { 2000 };
private: private:
typedef std::deque<std::string> LogBuffer; typedef std::deque<std::string> LogBuffer;
LogBuffer lbuf; LogBuffer lbuf;
std::string peername; std::string peername = { "" };
std::string caddr; std::string caddr = { "" };
std::shared_ptr<DebugStream> log; std::shared_ptr<DebugStream> log;
std::shared_ptr<LogAgregator> alog; std::shared_ptr<LogAgregator> alog;
sigc::connection conn; sigc::connection conn;
...@@ -74,7 +75,7 @@ class LogSession: ...@@ -74,7 +75,7 @@ class LogSession:
// PassiveTimer ptSessionTimeout; // PassiveTimer ptSessionTimeout;
FinalSlot slFin; FinalSlot slFin;
std::atomic_bool cancelled; std::atomic_bool cancelled = { false };
DebugStream slog; DebugStream slog;
std::ostringstream sbuf; std::ostringstream sbuf;
......
...@@ -60,7 +60,7 @@ namespace UniSetTypes ...@@ -60,7 +60,7 @@ namespace UniSetTypes
ObjectId node = { UniSetTypes::DefaultObjectId }; // откуда ObjectId node = { UniSetTypes::DefaultObjectId }; // откуда
ObjectId supplier = { UniSetTypes::DefaultObjectId }; // от кого ObjectId supplier = { UniSetTypes::DefaultObjectId }; // от кого
ObjectId consumer = { UniSetTypes::DefaultObjectId }; // кому ObjectId consumer = { UniSetTypes::DefaultObjectId }; // кому
struct timeval tm; struct timeval tm = { 0, 0 };
Message( Message&& ) = default; Message( Message&& ) = default;
......
...@@ -169,11 +169,11 @@ class PassiveSigTimer: ...@@ -169,11 +169,11 @@ class PassiveSigTimer:
protected: protected:
private: private:
struct itimerval mtimer; struct itimerval mtimer = { {0, 0}, {0, 0} };
pid_t pid; pid_t pid = { 0 };
// bool terminated; // bool terminated;
volatile sig_atomic_t terminated; volatile sig_atomic_t terminated = { 0 };
void init(); void init();
......
...@@ -16,7 +16,8 @@ class UTCPStream: ...@@ -16,7 +16,8 @@ class UTCPStream:
void create( const std::string& hname, int port, bool throwflag = false, timeout_t timer = 0 ); void create( const std::string& hname, int port, bool throwflag = false, timeout_t timer = 0 );
// set keepalive params // set keepalive params
void setKeepAliveParams( timeout_t timeout_sec = 5, int conn_keepcnt = 1, int keepintvl = 2 ); // return true if OK
bool setKeepAliveParams( timeout_t timeout_sec = 5, int conn_keepcnt = 1, int keepintvl = 2 );
protected: protected:
......
...@@ -128,7 +128,7 @@ class VMonitor ...@@ -128,7 +128,7 @@ class VMonitor
* \param namewidth - ширина резервируемая под "имя" * \param namewidth - ширина резервируемая под "имя"
* \param colnum - количество столбцов вывода * \param colnum - количество столбцов вывода
*/ */
std::string pretty_str( int namewidth=NameWidth, int colnum=ColCount ); std::string pretty_str( int namewidth = NameWidth, int colnum = ColCount );
// функции добавления.. // функции добавления..
VMON_DEF_FUNC2(int); VMON_DEF_FUNC2(int);
...@@ -145,7 +145,7 @@ class VMonitor ...@@ -145,7 +145,7 @@ class VMonitor
static const std::string pretty_str( const std::string& name, const std::string* v, int width = NameWidth ); static const std::string pretty_str( const std::string& name, const std::string* v, int width = NameWidth );
static const std::string pretty_str( const std::string& name, const std::string& v, int width = NameWidth ); static const std::string pretty_str( const std::string& name, const std::string& v, int width = NameWidth );
std::list<std::pair<std::string,std::string>> getList(); std::list<std::pair<std::string, std::string>> getList();
protected: protected:
......
...@@ -61,9 +61,9 @@ class ModbusTCPMaster: ...@@ -61,9 +61,9 @@ class ModbusTCPMaster:
ModbusRTU::ModbusData nTransaction; ModbusRTU::ModbusData nTransaction;
std::queue<unsigned char> qrecv; std::queue<unsigned char> qrecv;
PassiveTimer ptTimeout; PassiveTimer ptTimeout;
std::string iaddr; std::string iaddr = { "" };
int port; int port = { 0 };
bool force_disconnect; bool force_disconnect = { false };
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif // ModbusTCPMaster_H_ #endif // ModbusTCPMaster_H_
......
...@@ -91,7 +91,7 @@ class ModbusTCPServer: ...@@ -91,7 +91,7 @@ class ModbusTCPServer:
virtual ModbusRTU::mbErrCode tcp_processing( ost::TCPStream& tcp, ModbusTCP::MBAPHeader& mhead ); virtual ModbusRTU::mbErrCode tcp_processing( ost::TCPStream& tcp, ModbusTCP::MBAPHeader& mhead );
void sessionFinished( ModbusTCPSession* s ); void sessionFinished( ModbusTCPSession* s );
ost::tpport_t port; ost::tpport_t port = { 0 };
ost::TCPStream tcp; ost::TCPStream tcp;
ost::InetAddress iaddr; ost::InetAddress iaddr;
std::queue<unsigned char> qrecv; std::queue<unsigned char> qrecv;
...@@ -101,12 +101,12 @@ class ModbusTCPServer: ...@@ -101,12 +101,12 @@ class ModbusTCPServer:
UniSetTypes::uniset_mutex sMutex; UniSetTypes::uniset_mutex sMutex;
SessionList slist; SessionList slist;
bool ignoreAddr; bool ignoreAddr = { false };
unsigned int maxSessions; unsigned int maxSessions = { 5 };
unsigned int sessCount; unsigned int sessCount = { 0 };
timeout_t sessTimeout; timeout_t sessTimeout = { 10000 }; // msec
private: private:
......
...@@ -102,21 +102,21 @@ class ModbusTCPSession: ...@@ -102,21 +102,21 @@ class ModbusTCPSession:
ModbusTCP::MBAPHeader curQueryHeader; ModbusTCP::MBAPHeader curQueryHeader;
std::unordered_set<ModbusRTU::ModbusAddr> vaddr; std::unordered_set<ModbusRTU::ModbusAddr> vaddr;
PassiveTimer ptTimeout; PassiveTimer ptTimeout;
timeout_t timeout; timeout_t timeout = { 0 };
ModbusRTU::ModbusMessage buf; ModbusRTU::ModbusMessage buf;
bool ignoreAddr; bool ignoreAddr = { false };
std::string peername; std::string peername = { "" };
std::string caddr; std::string caddr = { "" };
FinalSlot slFin; FinalSlot slFin;
std::atomic_bool cancelled; std::atomic_bool cancelled = { false };
// статистика // статистика
UniSetTypes::uniset_rwmutex mAsk; UniSetTypes::uniset_rwmutex mAsk;
unsigned int askCount; unsigned int askCount = { 0 };
}; };
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
#endif // ModbusTCPSession_H_ #endif // ModbusTCPSession_H_
......
...@@ -345,7 +345,7 @@ void ComPort::cleanupChannel() ...@@ -345,7 +345,7 @@ void ComPort::cleanupChannel()
bool old_waiting = waiting; bool old_waiting = waiting;
waiting = false; waiting = false;
int mask = fcntl(fd, F_GETFL); int mask = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, O_NONBLOCK); (void)fcntl(fd, F_SETFL, O_NONBLOCK);
try try
{ {
...@@ -357,7 +357,7 @@ void ComPort::cleanupChannel() ...@@ -357,7 +357,7 @@ void ComPort::cleanupChannel()
} }
catch(...) {} catch(...) {}
fcntl(fd, F_SETFL, mask); (void)fcntl(fd, F_SETFL, mask);
waiting = old_waiting; waiting = old_waiting;
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
......
...@@ -994,7 +994,7 @@ mbErrCode ModbusClient::recv_pdu( ModbusByte qfunc, ModbusMessage& rbuf, timeout ...@@ -994,7 +994,7 @@ mbErrCode ModbusClient::recv_pdu( ModbusByte qfunc, ModbusMessage& rbuf, timeout
{ {
int onum = 0; int onum = 0;
while( rlen < sizeof(rbuf) && onum < mPreRDI.objNum ) while( (rlen+2) < sizeof(rbuf) && onum < mPreRDI.objNum )
{ {
// сперва получаем два байта, для определения длины последующих данных // сперва получаем два байта, для определения длины последующих данных
int szDataLen = 2; // object id + len int szDataLen = 2; // object id + len
...@@ -1351,7 +1351,7 @@ mbErrCode ModbusClient::send( ModbusMessage& msg ) ...@@ -1351,7 +1351,7 @@ mbErrCode ModbusClient::send( ModbusMessage& msg )
} }
// Пауза, чтобы не ловить свою посылку // Пауза, чтобы не ловить свою посылку
if( aftersend_msec >= 0 ) if( aftersend_msec > 0 )
msleep(aftersend_msec); msleep(aftersend_msec);
//#warning Разобраться с паузой после посылки... //#warning Разобраться с паузой после посылки...
......
...@@ -94,7 +94,7 @@ mbErrCode ModbusRTUSlave::receive(const std::unordered_set<ModbusAddr>& vmbaddr, ...@@ -94,7 +94,7 @@ mbErrCode ModbusRTUSlave::receive(const std::unordered_set<ModbusAddr>& vmbaddr,
printProcessingTime(); printProcessingTime();
} }
if( aftersend_msec >= 0 ) if( aftersend_msec > 0 )
msleep(aftersend_msec); msleep(aftersend_msec);
// usleep(10000); // usleep(10000);
return res; return res;
...@@ -106,9 +106,6 @@ mbErrCode ModbusRTUSlave::receive(const std::unordered_set<ModbusAddr>& vmbaddr, ...@@ -106,9 +106,6 @@ mbErrCode ModbusRTUSlave::receive(const std::unordered_set<ModbusAddr>& vmbaddr,
} }
while( res == erBadReplyNodeAddress ); while( res == erBadReplyNodeAddress );
if( res != erNoError )
return res;
return processing(buf); return processing(buf);
} }
// -------------------------------------------------------------------------------- // --------------------------------------------------------------------------------
......
...@@ -1534,7 +1534,7 @@ ModbusRTU::mbErrCode ModbusServer::replyFileTransfer( const std::string& fname, ...@@ -1534,7 +1534,7 @@ ModbusRTU::mbErrCode ModbusServer::replyFileTransfer( const std::string& fname,
int fd = open(fname.c_str(), O_RDONLY | O_NONBLOCK ); int fd = open(fname.c_str(), O_RDONLY | O_NONBLOCK );
if( fd <= 0 ) if( fd < 0 )
{ {
if( dlog && dlog->is_warn() ) if( dlog && dlog->is_warn() )
(*dlog)[Debug::WARN] << "(replyFileTransfer): open '" << fname << "' with error: " << strerror(errno) << endl; (*dlog)[Debug::WARN] << "(replyFileTransfer): open '" << fname << "' with error: " << strerror(errno) << endl;
...@@ -1608,10 +1608,10 @@ ModbusRTU::mbErrCode ModbusServer::replySetDateTime( ModbusRTU::SetDateTimeMessa ...@@ -1608,10 +1608,10 @@ ModbusRTU::mbErrCode ModbusServer::replySetDateTime( ModbusRTU::SetDateTimeMessa
t.tm_mon = query.mon - 1; t.tm_mon = query.mon - 1;
// t.tm_year = (query.century>19) ? query.year + query.century*10 - 1900 : query.year; // t.tm_year = (query.century>19) ? query.year + query.century*10 - 1900 : query.year;
t.tm_year = (query.century > 19) ? query.year + 2000 - 1900 : query.year; t.tm_year = (query.century > 19) ? query.year + 2000 - 1900 : query.year;
set.tv_sec = mktime(&t); set.tv_sec = mktime(&t); // может вернуть -1 (!)
set.tv_usec = 0; set.tv_usec = 0;
if( settimeofday(&set, &tz) == 0 ) if( set.tv_sec >=0 && settimeofday(&set, &tz) == 0 )
{ {
// подтверждаем сохранение // подтверждаем сохранение
// в ответе возвращаем установленное время... // в ответе возвращаем установленное время...
...@@ -1677,7 +1677,7 @@ mbErrCode ModbusServer::send( ModbusMessage& msg ) ...@@ -1677,7 +1677,7 @@ mbErrCode ModbusServer::send( ModbusMessage& msg )
return erHardwareError; return erHardwareError;
} }
if( aftersend_msec >= 0 ) if( aftersend_msec > 0 )
msleep(aftersend_msec); msleep(aftersend_msec);
return post_send_request(msg); return post_send_request(msg);
......
...@@ -190,7 +190,7 @@ mbErrCode ModbusTCPServer::receive(const std::unordered_set<ModbusAddr>& vmbaddr ...@@ -190,7 +190,7 @@ mbErrCode ModbusTCPServer::receive(const std::unordered_set<ModbusAddr>& vmbaddr
send(buf); send(buf);
printProcessingTime(); printProcessingTime();
} }
else if( aftersend_msec >= 0 ) else if( aftersend_msec > 0 )
msleep(aftersend_msec); msleep(aftersend_msec);
tcp.disconnect(); tcp.disconnect();
...@@ -275,6 +275,15 @@ mbErrCode ModbusTCPServer::tcp_processing( ost::TCPStream& tcp, ModbusTCP::MBAPH ...@@ -275,6 +275,15 @@ mbErrCode ModbusTCPServer::tcp_processing( ost::TCPStream& tcp, ModbusTCP::MBAPH
if( mhead.pID != 0 ) if( mhead.pID != 0 )
return erUnExpectedPacketType; // erTimeOut; return erUnExpectedPacketType; // erTimeOut;
if( mhead.len > ModbusRTU::MAXLENPACKET )
{
if( dlog->is_info() )
dlog->info() << "(ModbusTCPServer::tcp_processing): len(" << (int)mhead.len
<< ") < MAXLENPACKET(" << ModbusRTU::MAXLENPACKET << ")" << endl;
return erInvalidFormat;
}
len = ModbusTCPCore::readNextData(&tcp, qrecv, mhead.len); len = ModbusTCPCore::readNextData(&tcp, qrecv, mhead.len);
if( len < mhead.len ) if( len < mhead.len )
......
...@@ -52,10 +52,10 @@ void ModbusTCPSession::setKeepAliveParams( timeout_t timeout_sec, int keepcnt, i ...@@ -52,10 +52,10 @@ void ModbusTCPSession::setKeepAliveParams( timeout_t timeout_sec, int keepcnt, i
{ {
SOCKET fd = TCPSession::so; SOCKET fd = TCPSession::so;
int enable = 1; int enable = 1;
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void*)&enable, sizeof(enable)); (void)setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void*)&enable, sizeof(enable));
setsockopt(fd, SOL_TCP, TCP_KEEPCNT, (void*) &keepcnt, sizeof(keepcnt)); (void)setsockopt(fd, SOL_TCP, TCP_KEEPCNT, (void*) &keepcnt, sizeof(keepcnt));
setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, (void*) &keepintvl, sizeof (keepintvl)); (void)setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, (void*) &keepintvl, sizeof (keepintvl));
setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, (void*) &timeout_sec, sizeof (timeout_sec)); (void)setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, (void*) &timeout_sec, sizeof (timeout_sec));
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void ModbusTCPSession::run() void ModbusTCPSession::run()
...@@ -161,7 +161,7 @@ ModbusRTU::mbErrCode ModbusTCPSession::receive( const std::unordered_set<ModbusA ...@@ -161,7 +161,7 @@ ModbusRTU::mbErrCode ModbusTCPSession::receive( const std::unordered_set<ModbusA
send(buf); send(buf);
printProcessingTime(); printProcessingTime();
} }
else if( aftersend_msec >= 0 ) else if( aftersend_msec > 0 )
msleep(aftersend_msec); msleep(aftersend_msec);
return res; return res;
...@@ -175,9 +175,6 @@ ModbusRTU::mbErrCode ModbusTCPSession::receive( const std::unordered_set<ModbusA ...@@ -175,9 +175,6 @@ ModbusRTU::mbErrCode ModbusTCPSession::receive( const std::unordered_set<ModbusA
return erTimeOut; return erTimeOut;
} }
if( res != erNoError )
return res;
if( cancelled ) if( cancelled )
return erSessionClosed; return erSessionClosed;
...@@ -236,6 +233,15 @@ mbErrCode ModbusTCPSession::tcp_processing( ost::TCPStream& tcp, ModbusTCP::MBAP ...@@ -236,6 +233,15 @@ mbErrCode ModbusTCPSession::tcp_processing( ost::TCPStream& tcp, ModbusTCP::MBAP
if( mhead.pID != 0 ) if( mhead.pID != 0 )
return erUnExpectedPacketType; // erTimeOut; return erUnExpectedPacketType; // erTimeOut;
if( mhead.len > ModbusRTU::MAXLENPACKET )
{
if( dlog->is_info() )
dlog->info() << "(ModbusTCPServer::tcp_processing): len(" << (int)mhead.len
<< ") < MAXLENPACKET(" << ModbusRTU::MAXLENPACKET << ")" << endl;
return erInvalidFormat;
}
len = ModbusTCPCore::readNextData(&tcp, qrecv, mhead.len); len = ModbusTCPCore::readNextData(&tcp, qrecv, mhead.len);
if( len < mhead.len ) if( len < mhead.len )
......
...@@ -500,7 +500,7 @@ void ReadCoilRetMessage::init( ModbusMessage& m ) ...@@ -500,7 +500,7 @@ void ReadCoilRetMessage::init( ModbusMessage& m )
bcnt = m.data[0]; bcnt = m.data[0];
if( bcnt > MAXLENPACKET ) if( bcnt > MAXPDULEN )
throw mbException(erPacketTooLong); throw mbException(erPacketTooLong);
memcpy(&data, &(m.data[1]), bcnt); memcpy(&data, &(m.data[1]), bcnt);
...@@ -702,7 +702,7 @@ void ReadInputStatusRetMessage::init( ModbusMessage& m ) ...@@ -702,7 +702,7 @@ void ReadInputStatusRetMessage::init( ModbusMessage& m )
bcnt = m.data[0]; bcnt = m.data[0];
if( bcnt > MAXLENPACKET ) if( bcnt > MAXPDULEN )
throw mbException(erPacketTooLong); throw mbException(erPacketTooLong);
memcpy(&data, &(m.data[1]), bcnt); memcpy(&data, &(m.data[1]), bcnt);
......
...@@ -23,14 +23,24 @@ UTCPStream::UTCPStream(): ...@@ -23,14 +23,24 @@ UTCPStream::UTCPStream():
{ {
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void UTCPStream::setKeepAliveParams(timeout_t timeout_sec, int keepcnt, int keepintvl ) bool UTCPStream::setKeepAliveParams(timeout_t timeout_sec, int keepcnt, int keepintvl )
{ {
SOCKET fd = TCPStream::so; SOCKET fd = TCPStream::so;
int enable = 1; int enable = 1;
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void*)&enable, sizeof(enable)); bool ok = true;
setsockopt(fd, SOL_TCP, TCP_KEEPCNT, (void*) &keepcnt, sizeof(keepcnt)); if( setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (void*)&enable, sizeof(enable)) == -1 )
setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, (void*) &keepintvl, sizeof (keepintvl)); ok = false;
setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, (void*) &timeout_sec, sizeof (timeout_sec));
if( setsockopt(fd, SOL_TCP, TCP_KEEPCNT, (void*) &keepcnt, sizeof(keepcnt)) == -1 )
ok = false;
if( setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, (void*) &keepintvl, sizeof (keepintvl)) == -1 )
ok = false;
if( setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, (void*) &timeout_sec, sizeof (timeout_sec)) == -1 )
ok = false;
return ok;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
void UTCPStream::create( const std::string& hname, int port, bool throwflag, timeout_t t ) void UTCPStream::create( const std::string& hname, int port, bool throwflag, timeout_t t )
......
...@@ -766,7 +766,7 @@ ObjectType UInterface::getType( const ObjectId name ) const ...@@ -766,7 +766,7 @@ ObjectType UInterface::getType( const ObjectId name ) const
} }
// ------------------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------------------
void UInterface::registered( const ObjectId id, const ObjectPtr oRef, bool force ) const throw(ORepFailed) void UInterface::registered( const ObjectId id, const ObjectPtr oRef, bool force ) const throw(UniSetTypes::ORepFailed)
{ {
// если влючён режим использования локальных файлов // если влючён режим использования локальных файлов
// то пишем IOR в файл // то пишем IOR в файл
......
...@@ -185,6 +185,8 @@ std::ostream& LogAgregator::printTree( std::ostream& os, const std::string& g_ta ...@@ -185,6 +185,8 @@ std::ostream& LogAgregator::printTree( std::ostream& os, const std::string& g_ta
string s_tab(s.str()); string s_tab(s.str());
std::ios_base::fmtflags old_flags = os.flags();
os << std::left << g_tab << getLogName() << sep << endl; // << setw(6) << " " << "[ " << Debug::str(DebugStream::level()) << " ]" << endl; os << std::left << g_tab << getLogName() << sep << endl; // << setw(6) << " " << "[ " << Debug::str(DebugStream::level()) << " ]" << endl;
std::list<std::shared_ptr<DebugStream>> lst; std::list<std::shared_ptr<DebugStream>> lst;
...@@ -206,6 +208,7 @@ std::ostream& LogAgregator::printTree( std::ostream& os, const std::string& g_ta ...@@ -206,6 +208,7 @@ std::ostream& LogAgregator::printTree( std::ostream& os, const std::string& g_ta
os << s_tab << setw(tab_width) << std::right << l->getLogName() << std::left << " [ " << Debug::str(l->level()) << " ]" << endl; os << s_tab << setw(tab_width) << std::right << l->getLogName() << std::left << " [ " << Debug::str(l->level()) << " ]" << endl;
} }
os.setf(old_flags);
return os; return os;
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
......
...@@ -55,7 +55,7 @@ void IORFile::setIOR( const ObjectId id, const string& sior ) ...@@ -55,7 +55,7 @@ void IORFile::setIOR( const ObjectId id, const string& sior )
if( !ior_file ) if( !ior_file )
{ {
ucrit << "(IORFile): не смог открыть файл " + fname << endl; ucrit << "(IORFile): не смог открыть файл " + fname << endl;
throw TimeOut("(IORFile): не смог создать ior-файл " + fname); throw ORepFailed("(IORFile): не смог создать ior-файл " + fname);
} }
ior_file << sior << endl; ior_file << sior << endl;
......
...@@ -67,7 +67,7 @@ ObjectId ObjectIndex_XML::getIdByName( const string& name ) ...@@ -67,7 +67,7 @@ ObjectId ObjectIndex_XML::getIdByName( const string& name )
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
string ObjectIndex_XML::getMapName( const ObjectId id ) string ObjectIndex_XML::getMapName( const ObjectId id )
{ {
if( (unsigned)id < omap.size() && (unsigned)id >= 0 ) if( (unsigned)id < omap.size() && (unsigned)id > 0 )
return omap[id].repName; return omap[id].repName;
return ""; return "";
...@@ -75,7 +75,7 @@ string ObjectIndex_XML::getMapName( const ObjectId id ) ...@@ -75,7 +75,7 @@ string ObjectIndex_XML::getMapName( const ObjectId id )
// ----------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------
string ObjectIndex_XML::getTextName( const ObjectId id ) string ObjectIndex_XML::getTextName( const ObjectId id )
{ {
if( (unsigned)id < omap.size() && (unsigned)id >= 0 ) if( (unsigned)id < omap.size() && (unsigned)id > 0 )
return omap[id].textName; return omap[id].textName;
return ""; return "";
...@@ -287,7 +287,7 @@ unsigned int ObjectIndex_XML::read_nodes( const std::shared_ptr<UniXML>& xml, co ...@@ -287,7 +287,7 @@ unsigned int ObjectIndex_XML::read_nodes( const std::shared_ptr<UniXML>& xml, co
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
const ObjectInfo* ObjectIndex_XML::getObjectInfo( const ObjectId id ) const ObjectInfo* ObjectIndex_XML::getObjectInfo( const ObjectId id )
{ {
if( (unsigned)id < omap.size() && (unsigned)id >= 0 ) if( (unsigned)id < omap.size() && (unsigned)id > 0 )
return &omap[id]; return &omap[id];
return NULL; return NULL;
......
...@@ -366,6 +366,12 @@ bool ObjectRepository::list(const string& section, ListObjectName* ls, unsigned ...@@ -366,6 +366,12 @@ bool ObjectRepository::list(const string& section, ListObjectName* ls, unsigned
CosNaming::BindingIterator_var bi; CosNaming::BindingIterator_var bi;
ctx->list(how_many, bl, bi); ctx->list(how_many, bl, bi);
// хитрая проверка на null приобращении к bl
// coverity говорит потенциально это возможно
// т.к. там возвращается указатель, который по умолчанию null
if( !bl.operator->() )
return false;
bool res = true; bool res = true;
if(how_many >= bl->length()) if(how_many >= bl->length())
......
...@@ -232,6 +232,11 @@ bool ObjectRepositoryFactory::removeSection(const string& fullName, bool recursi ...@@ -232,6 +232,11 @@ bool ObjectRepositoryFactory::removeSection(const string& fullName, bool recursi
ctx->list(how_many, bl, bi); ctx->list(how_many, bl, bi);
// хитрая проверка на null приобращении к bl
// coverity говорит потенциально это возможно
// т.к. там возвращается указатель, который по умолчанию null
if( !bl.operator->() )
return false;
if( how_many > bl->length() ) if( how_many > bl->length() )
how_many = bl->length(); how_many = bl->length();
...@@ -301,7 +306,9 @@ bool ObjectRepositoryFactory::removeSection(const string& fullName, bool recursi ...@@ -301,7 +306,9 @@ bool ObjectRepositoryFactory::removeSection(const string& fullName, bool recursi
} }
if( !CORBA::is_nil(bi) )
bi->destroy(); // ?? bi->destroy(); // ??
return rem; return rem;
} }
......
...@@ -718,7 +718,7 @@ namespace UniSetTypes ...@@ -718,7 +718,7 @@ namespace UniSetTypes
} }
UniXML::iterator it(node); UniXML::iterator it(node);
it.goChildren(); (void)it.goChildren();
// определяем порт // определяем порт
string defPort(getPort(unixml->getProp(node, "port"))); string defPort(getPort(unixml->getProp(node, "port")));
...@@ -927,6 +927,7 @@ namespace UniSetTypes ...@@ -927,6 +927,7 @@ namespace UniSetTypes
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
string Configuration::getRepSectionName( const string& sec, xmlNode* secnode ) string Configuration::getRepSectionName( const string& sec, xmlNode* secnode )
{ {
secnode = 0;
xmlNode* node = unixml->findNode(unixml->getFirstNode(), sec); xmlNode* node = unixml->findNode(unixml->getFirstNode(), sec);
if( node == NULL ) if( node == NULL )
......
...@@ -39,14 +39,16 @@ RunLock::~RunLock() ...@@ -39,14 +39,16 @@ RunLock::~RunLock()
} }
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
bool RunLock::isLocked(const string& name) bool RunLock::isLocked( const string& name )
{ {
FILE* out = fopen( string(name + ".lock" ).c_str(), "r" ); FILE* out = fopen( string(name + ".lock" ).c_str(), "r" );
if( out ) if( out )
{ {
char ptr[10]; char ptr[10];
fscanf( out, "%9s", ptr ); int n = fscanf( out, "%9s", ptr );
if( n < 1 )
return false;
DIR* d = opendir( "/proc" ); DIR* d = opendir( "/proc" );
dirent* dir; dirent* dir;
......
...@@ -223,7 +223,7 @@ bool UniXML::save(const string& filename, int level) ...@@ -223,7 +223,7 @@ bool UniXML::save(const string& filename, int level)
// Если файл уже существует, переименовываем его в *.xml.bak // Если файл уже существует, переименовываем его в *.xml.bak
string bakfilename(fn + ".bak"); string bakfilename(fn + ".bak");
rename(fn.c_str(), bakfilename.c_str()); (void)rename(fn.c_str(), bakfilename.c_str());
// int res = ::xmlSaveFormatFileEnc(fn.c_str(), doc, ExternalEncoding.c_str(), level); // int res = ::xmlSaveFormatFileEnc(fn.c_str(), doc, ExternalEncoding.c_str(), level);
// Write in UTF-8 without XML encoding in the header */ // Write in UTF-8 without XML encoding in the header */
int res = ::xmlSaveFormatFile(fn.c_str(), doc, level); int res = ::xmlSaveFormatFile(fn.c_str(), doc, level);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment