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