NSIS-ka
A free C++ implementation of NSIS protocols

Changeset 6765


Ignore:
Timestamp:
Mar 5, 2014, 3:55:10 PM (4 years ago)
Author:
bless@…
Message:
Location:
protlib/trunk
Files:
28 edited
4 copied

Legend:

Unmodified
Added
Removed
  • protlib/trunk

  • protlib/trunk/README

    r6176 r6765  
     1ls
    12-----------------------------------------------------------
    23$Id$
     
    1516* socket and transport related functions
    1617
     18Compile under Ubuntu 13.04 with:
     191. change to this directory where README is located
     202. autoreconf --install
     213. ./configure --enable-nfq
     224. make
     23
  • protlib/trunk/configure.ac

    r6282 r6765  
    55#
    66AC_INIT([protlib-ka], [0.0.0.5551], [roland.bless@kit.edu])
    7 AM_INIT_AUTOMAKE([1.11 silent-rules -Wall -Werror foreign])
     7AM_INIT_AUTOMAKE([1.11 silent-rules -Wall -Werror -Wno-extra-portability  foreign])
    88
    99# silent build by default
     
    1515AC_PROG_CXX
    1616AC_PROG_RANLIB
     17AM_PROG_CC_C_O
    1718
    1819# Checks for libraries.
     
    5455AM_CONDITIONAL(PROTLIB_DISABLE_LOGGING, test "$protlib_logging" = no)
    5556
     57AC_ARG_ENABLE([rao],
     58        [AS_HELP_STRING([--enable-rao], [compile with rout alert option support (default: disabled)])],
     59        [protlib_with_rao=$enableval],
     60        [protlib_with_rao=no])
     61
     62AM_CONDITIONAL(PROTLIB_WITH_RAO, test "$protlib_with_rao" = yes)
     63
    5664## libnetfilter_queue or obsolete libipq
    5765AC_ARG_ENABLE([nfq],
     
    6270#LIB NETFILTER_QUEUE
    6371AM_CONDITIONAL(PROTLIB_WITH_NFQ, test "$protlib_with_nfq" = yes)
     72
     73if test $protlib_with_rao = yes; then
     74AC_MSG_NOTICE([protlib will be built with router alert option support (query encapsulation), requires netfilterqueue or libipq])
    6475if test $protlib_with_nfq = yes; then
    65         AC_CHECK_HEADERS([libnetfilter_queue/libnetfilter_queue.h], [],
    66                 [AC_MSG_ERROR([cannot find libnetfilter_queue/libnetfilter_queue.h in include path, probably you need to install libnetfilter-queue-dev first])],[[#include<libnetfilter_queue/libnetfilter_queue.h>]])
     76        AC_CHECK_HEADERS([libnetfilter_queue/libnetfilter_queue.h], [], [AC_MSG_ERROR([cannot find libnetfilter_queue/libnetfilter_queue.h in include path, probably you need to install libnetfilter-queue-dev first])],
     77          [[#include <stdint.h>
     78            #include <libnetfilter_queue/libnetfilter_queue.h>]])
    6779        AC_CHECK_LIB([netfilter_queue],[nfq_get_payload],,[AC_MSG_ERROR([cannot find libnetfilter_queue, probably you need to install libnetfilter-queue-dev first])])
    6880        AC_CHECK_FILE([/usr/include/libnetfilter_queue], [NETFILTER_QUEUE_INCLUDE=" -I /usr/include/libnetfilter_queue"], [])
     
    7284fi
    7385
     86else
     87AC_MSG_NOTICE([NOTE: protlib will be built without router alert option support (query encapsulation)])
     88fi #end if $protlib_with_rao
    7489
    7590AC_SUBST([NETFILTER_QUEUE_INCLUDE])
     
    128143
    129144
    130 
    131 #AC_CHECK_HEADER([libipq.h], [],)
    132 
    133145AC_LANG_CPLUSPLUS
    134146
  • protlib/trunk/include/address.h

    r6282 r6765  
    66/// $HeadURL$
    77// ===========================================================
    8 //                     
     8//
    99// Copyright (C) 2005-2007, all rights reserved by
    1010// - Institute of Telematics, Universitaet Karlsruhe (TH)
     
    1212// More information and contact:
    1313// https://projekte.tm.uka.de/trac/NSIS
    14 //                     
     14//
    1515// This program is free software; you can redistribute it and/or modify
    1616// it under the terms of the GNU General Public License as published by
     
    2727//
    2828// ===========================================================
    29 /** @ingroup ieaddress 
     29/** @ingroup ieaddress
    3030 *
    3131 * GIST address objects
     
    3434#ifndef PROTLIB__ADDRESS_H
    3535#define PROTLIB__ADDRESS_H
     36
     37# pragma GCC diagnostic pop
     38# pragma GCC diagnostic ignored "-Weffc++"
    3639
    3740#include "protlib_types.h"
     
    6568
    6669        enum subtype_t {
    67                 /** 255 is not a valid subtype and is used to register for all 
     70                /** 255 is not a valid subtype and is used to register for all
    6871                 * subtypes.
    69                  * @note This is no valid subtype because it is not in 0..64. 
     72                 * @note This is no valid subtype because it is not in 0..64.
    7073                 */
    7174                all_subtypes          = 255,
     
    133136        virtual ~hostaddress();
    134137        /// set IPv4 from string
    135         bool set_ipv4(const char *str); 
     138        bool set_ipv4(const char *str);
    136139        /// set IPv4 from in_addr
    137140        void set_ip(const struct in_addr &in);
    138141        /// set IPv6 from string
    139         bool set_ipv6(const char *str); 
     142        bool set_ipv6(const char *str);
    140143        /// set IPv6 from in6_addr
    141144        void set_ip(const struct in6_addr &in);
    142145        /// set IPv4 or IPv6 from string
    143         bool set_ip(const char *str);   
    144         bool set_ip(const string& str); 
     146        bool set_ip(const char *str);
     147        bool set_ip(const string& str);
    145148        /// set IP from hostaddress
    146149        void set_ip(const hostaddress& h);
     
    223226
    224227inline
    225 hostaddress::hostaddress(const struct in6_addr& ipv6addr) 
    226   : address(IPv6HostAddress), 
    227     ipv4flag(false), 
     228hostaddress::hostaddress(const struct in6_addr& ipv6addr)
     229  : address(IPv6HostAddress),
     230    ipv4flag(false),
    228231    ipv6addr(ipv6addr),
    229232    outstring(NULL)
     
    232235
    233236inline
    234 hostaddress::hostaddress(const struct in_addr& ipv4addr) 
    235   : address(IPv4HostAddress), 
    236     ipv4flag(true), 
     237hostaddress::hostaddress(const struct in_addr& ipv4addr)
     238  : address(IPv4HostAddress),
     239    ipv4flag(true),
    237240    ipv4addr(ipv4addr),
    238241    outstring(NULL)
     
    251254        virtual appladdress* copy() const;
    252255        virtual bool operator==(const address& ie) const;
    253        
     256
    254257        /// hash function
    255258        virtual size_t get_hash() const;
    256        
     259
    257260    protected:
    258261        /// set subtype and IPv4 flag
    259262        virtual void set_subtype(bool ipv4);
    260        
     263
    261264    public:
    262265        /// constructor
     
    287290        virtual ~appladdress() {};
    288291
    289        
     292
    290293        /// are they equivalent
    291294        ///virtual bool equiv(const appladdress& h) const { return hostaddress::equiv(h); }
     
    299302        /// get port
    300303        port_t get_port() const;
    301        
     304
    302305        /// get sockaddr_in6
    303306        void get_sockaddr(struct sockaddr_in6& sockaddr) const;
     
    322325            return prefix;
    323326        }
    324        
     327
    325328        /// set prefix
    326329        inline
     
    328331            prefix=prfx;
    329332        }
    330        
     333
    331334        /// set IP TTL
    332335        inline
     
    334337            ip_ttl = ttl;
    335338        }
    336        
    337        
     339
     340
    338341        /// unset IP TTL
    339342        inline
     
    341344            ip_ttl = 0;
    342345        }
    343        
    344        
     346
     347
    345348        /// get IP TTL, if == 0, no IP TTL should be set
    346349        inline
     
    349352        }
    350353
    351        
     354
    352355        /// set RAO value
    353356        inline
     
    356359            rao = value;
    357360        }
    358        
     361
    359362        /// unset RAO value
    360363        inline
     
    363366            rao = 0;
    364367        }
    365        
     368
    366369        /// get RAO value
    367370        inline
     
    369372            return rao;
    370373        }
    371        
    372        
     374
     375
    373376        /// test if RAO present
    374377        inline
     
    376379        return rao_presence;
    377380        }
    378        
     381
    379382        /// set outgoing Interface index
    380383        inline
     
    382385        if_index = value;
    383386        }
    384        
     387
    385388        /// get outgoing Interface index
    386389        inline
     
    388391            return if_index;
    389392        }
    390        
     393
    391394        /// unset outgoing Interface index
    392395        inline
     
    394397            if_index = 0;
    395398        }
    396        
     399
    397400
    398401
     
    403406        port_t port;
    404407        uint8 prefix;
    405        
     408
    406409        uint16 rao;
    407410        uint16 ip_ttl;
    408         bool rao_presence; 
     411        bool rao_presence;
    409412        uint16 if_index;
    410        
     413
    411414    }; // end appladdress
    412    
    413    
     415
     416
    414417inline
    415418appladdress::appladdress(const sockaddr_in6& sockaddr, protocol_t prot)
     
    433436                             port(0),
    434437                             prefix(32),
    435                              rao(0), 
    436                              ip_ttl(0), 
    437                              rao_presence(false), 
     438                             rao(0),
     439                             ip_ttl(0),
     440                             rao_presence(false),
    438441                             if_index(0)
    439                              
     442
    440443{
    441444  //Log(DEBUG_LOG,LOG_NORMAL,"address","address constructor called for bool ipv4=" << ipv4);
     
    448451                                                   port(app.port),
    449452                                                   prefix(app.prefix),
    450                                                    rao(app.rao), 
    451                                                    ip_ttl(app.ip_ttl), 
    452                                                    rao_presence(app.rao_presence), 
     453                                                   rao(app.rao),
     454                                                   ip_ttl(app.ip_ttl),
     455                                                   rao_presence(app.rao_presence),
    453456                                                   if_index(app.if_index)
    454    
     457
    455458{
    456459    //Log(DEBUG_LOG,LOG_NORMAL,"appladdress", "Copy address constructor called for appladdress& app:" << app);
     
    469472      port(p),
    470473      prefix(0),
    471       rao(0), 
    472       ip_ttl(0), 
    473       rao_presence(false), 
     474      rao(0),
     475      ip_ttl(0),
     476      rao_presence(false),
    474477      if_index(0)
    475478{
     
    488491    port(p),
    489492    prefix(0),
    490     rao(0), 
    491     ip_ttl(0), 
    492     rao_presence(false), 
     493    rao(0),
     494    ip_ttl(0),
     495    rao_presence(false),
    493496    if_index(0)
    494497
     
    509512    port(p),
    510513    prefix(0),
    511     rao(0), 
    512     ip_ttl(0), 
    513     rao_presence(false), 
     514    rao(0),
     515    ip_ttl(0),
     516    rao_presence(false),
    514517    if_index(0)
    515518{
     
    527530    port(p),
    528531    prefix(0),
    529     rao(0), 
    530     ip_ttl(0), 
    531     rao_presence(false), 
     532    rao(0),
     533    ip_ttl(0),
     534    rao_presence(false),
    532535    if_index(0)
    533536{
     
    548551inline
    549552appladdress::appladdress(const char* str, const char* pname, const char* portname, bool *res)
    550     : hostaddress(str,res), 
     553    : hostaddress(str,res),
    551554      prefix(0),
    552       rao(0), 
    553       ip_ttl(0), 
    554       rao_presence(false), 
     555      rao(0),
     556      ip_ttl(0),
     557      rao_presence(false),
    555558      if_index(0)
    556559{
     
    568571/** Assigns the given application address by using hostaddress::operator=(). */
    569572inline
    570 appladdress& 
    571 appladdress::operator=(const appladdress& app) 
     573appladdress&
     574appladdress::operator=(const appladdress& app)
    572575{
    573576        hostaddress::operator=(app);
     
    627630        proto = p;
    628631        return o;
    629 } // end set_protocol 
     632} // end set_protocol
    630633
    631634/** Set protocol ID and return old value.
     
    637640        proto = tsdb::getprotobyname(pname,res);
    638641        return o;
    639 } // end set_protocol 
     642} // end set_protocol
    640643
    641644/** Set protocol ID and return old value.
     
    647650        proto = tsdb::getprotobyname(pname,res);
    648651        return o;
    649 } // end set_protocol 
     652} // end set_protocol
    650653
    651654inline
     
    748751    virtual udsaddress* copy() const;
    749752    virtual bool operator==(const address& ie) const;
    750    
     753
    751754    /// constructor
    752755    udsaddress() : address(UDSAddress), socknum(invalid_socknum) {};
     
    754757    udsaddress(const udsaddress& h) : address(UDSAddress), uds_socket(h.uds_socket), socknum(h.socknum) {};
    755758    /// assignment
    756     udsaddress& operator=(const udsaddress& uds) { 
     759    udsaddress& operator=(const udsaddress& uds) {
    757760        uds_socket= uds.uds_socket;
    758761        socknum= uds.socknum;
     
    767770    /// destructor
    768771    virtual ~udsaddress() {};
    769    
     772
    770773    bool is_invalid() const { return socknum == invalid_socknum; };
    771774
     
    877880
    878881inline
    879 size_t 
    880 hostaddress::get_hash() const 
     882size_t
     883hostaddress::get_hash() const
    881884{
    882885        return (ipv6addr.s6_addr32[0] ^ ipv6addr.s6_addr32[1] ^ ipv6addr.s6_addr32[2] ^ ipv6addr.s6_addr32[3]);
     
    903906/** Assign h to this object. */
    904907inline
    905 hostaddress& 
     908hostaddress&
    906909hostaddress::operator=(const hostaddress& h) {
    907910        address::operator=(h);
     
    915918/** Copy constructor for hostaddress objects */
    916919inline
    917 hostaddress::hostaddress(const hostaddress& h) : 
    918   address(h), 
     920hostaddress::hostaddress(const hostaddress& h) :
     921  address(h),
    919922  outstring(NULL)
    920923{
     
    927930/** Check if this is an IPv4 address. */
    928931inline
    929 bool 
     932bool
    930933hostaddress::is_ipv4() const {
    931934        return ipv4flag;
     
    934937/** Check if this is an IPv6 address. */
    935938inline
    936 bool 
     939bool
    937940hostaddress::is_ipv6() const {
    938941        return (!ipv4flag);
     
    941944/** Check if this is an IPv4 mapped IPv6 address. */
    942945inline
    943 bool 
    944 hostaddress::is_mapped_ip() const 
     946bool
     947hostaddress::is_mapped_ip() const
    945948{
    946949  return (ipv4flag) ? false : IN6_IS_ADDR_V4MAPPED(&ipv6addr);
    947950} // end is_mapped_ip
    948951
    949 inline 
    950 bool 
     952inline
     953bool
    951954hostaddress::set_ip(const string& str) { return set_ip(str.c_str()); }
    952955
     
    954957/** Delete outstring if it exists. */
    955958hostaddress::~hostaddress() {
    956         if (outstring) 
    957         { 
     959        if (outstring)
     960        {
    958961          delete[] outstring;
    959962          outstring= 0;
     
    966969 */
    967970inline
    968 bool 
    969 hostaddress::set_ip(const char *str) 
    970 {
    971   return (!str) ? false : 
     971bool
     972hostaddress::set_ip(const char *str)
     973{
     974  return (!str) ? false :
    972975                 ( strchr(str,':') ? set_ipv6(str) : set_ipv4(str));    // which IP version?
    973976
     
    977980/** Lookup the host name associated with the current IP address. */
    978981inline
    979 string hostaddress::get_host_name(bool *res) const 
     982string hostaddress::get_host_name(bool *res) const
    980983{
    981984  return  ipv4flag ? tsdb::get_hostname(ipv4addr,res) : tsdb::get_hostname(ipv6addr,res);
     
    989992
    990993/** Set subtype and IPv4 flag. This does NOT clear the outstring buffer.
    991  * Use clear_ip(). 
    992  */
    993 inline
    994 void 
    995 appladdress::set_subtype(bool ipv4) 
    996 {
    997         ipv4flag = ipv4; 
     994 * Use clear_ip().
     995 */
     996inline
     997void
     998appladdress::set_subtype(bool ipv4)
     999{
     1000        ipv4flag = ipv4;
    9981001        subtype = (ipv4) ?  IPv4ApplAddress : IPv6ApplAddress;
    9991002} // end set_subtype
     
    10081011
    10091012inline
    1010 int 
    1011 netaddress::match_against(const netaddress& na) const 
     1013int
     1014netaddress::match_against(const netaddress& na) const
    10121015{
    10131016        // compare prefix lengths
     
    11121115}; // end macaddress equal_to
    11131116
    1114 } // end namespace std
     1117} // end namespace std
     1118
     1119# pragma GCC diagnostic pop
    11151120#endif // PROTLIB__ADDRESS_H
  • protlib/trunk/include/configpar.h

    r4210 r6765  
    104104
    105105
    106 /** confipar Base class (abstract)
     106/**
     107 * confipar Base class (abstract)
     108 *
    107109 * this class only provides meta information about the configuration parameter:
    108110 * its id, realm, name and description
     
    113115
    114116  // constructors
    115   configparBase() : realm_id(0), par_id(0), unit(NULL) {};
     117  configparBase() : realm_id(0), par_id(0),  changeable_while_running(false),  name(),  description(), unit(NULL) {};
    116118  configparBase(realm_id_t realm, configpar_id_t configparid, const char* name, const char* description, bool chg_at_runtime, const char* unitinfo= NULL);
    117119
     
    150152  bool isChangeableWhileRunning() const { return changeable_while_running; }
    151153
     154//   configparBase(const configparBase& other) = delete;
     155//   configparBase& operator=(const configparBase& other) = delete;
     156 
    152157protected:
    153158  ostream& appendUnitInfoComment(ostream& outstream) const;
  • protlib/trunk/include/configpar_repository.h

    r4107 r6765  
    66/// $HeadURL$
    77// ===========================================================
    8 //                     
     8//
    99// Copyright (C) 2008, all rights reserved by
    1010// - Institute of Telematics, Universitaet Karlsruhe (TH)
     
    1212// More information and contact:
    1313// https://projekte.tm.uka.de/trac/NSIS
    14 //                     
     14//
    1515// This program is free software; you can redistribute it and/or modify
    1616// it under the terms of the GNU General Public License as published by
     
    101101
    102102template <class T>
    103 T 
     103T
    104104configpar_repository::getPar(realm_id_t realm, configpar_id_t configparid) const
    105105{
     
    116116
    117117template <class T>
    118 const T& 
     118const T&
    119119configpar_repository::getParRef(realm_id_t realm, configpar_id_t configparid) const
    120120{
     
    130130
    131131template <class T>
    132 T& 
     132T&
    133133configpar_repository::getParRef(realm_id_t realm, configpar_id_t configparid)
    134134{
  • protlib/trunk/include/fqueue.h

    r6277 r6765  
    6565        /// FastQueue error
    6666        class FQError{};
     67       
    6768        /// constructor
    6869        FastQueue(const char *qname = 0, bool exp = false);
     
    9394        /// Return the name of the queue.
    9495        const char* get_name() const { return queue_name.c_str(); }
     96       
     97        FastQueue(const FastQueue&) = delete;
     98        FastQueue& operator=(const FastQueue&) = delete;
    9599private:
    96100        /// C fastqueue
  • protlib/trunk/include/logfile.h

    r4948 r6765  
    2929#ifndef _logfile_h_
    3030#define _logfile_h_
     31
     32# pragma GCC diagnostic push
     33# pragma GCC diagnostic ignored "-Weffc++"
    3134
    3235#include <fstream> // file stream
     
    221224
    222225  void logend();
     226 
     227 
     228 
    223229}; // end class logfile
    224230
     
    397403
    398404
    399 
     405# pragma GCC diagnostic pop
    400406#endif
  • protlib/trunk/include/messages.h

    r6654 r6765  
    107107                qaddr_api_6,
    108108                qaddr_api_7,
     109    qaddr_ice,
     110    qaddr_ice_2,
    109111                qaddr_api_wrapper_input,
    110112                qaddr_tp_over_uds,
  • protlib/trunk/include/network_message.h

    r6685 r6765  
    66/// $HeadURL$
    77// ===========================================================
    8 //                     
     8//
    99// Copyright (C) 2005-2007, all rights reserved by
    1010// - Institute of Telematics, Universitaet Karlsruhe (TH)
     
    1212// More information and contact:
    1313// https://projekte.tm.uka.de/trac/NSIS
    14 //                     
     14//
    1515// This program is free software; you can redistribute it and/or modify
    1616// it under the terms of the GNU General Public License as published by
     
    2828// ===========================================================
    2929
    30 /** @ingroup networkmsg
     30/**
     31 * @ingroup networkmsg
    3132 *
    32  * This is a generic class for network messages. 
     33 * This is a generic class for network messages.
    3334 * A network message consists of a number of bytes.
    3435 * There are no access member functions. So the user has full control over
    3536 * the buffer.
    3637 */
    37  
     38
    3839#ifndef _PROTLIB__NETWORK_MESSAGE_H_
    3940#define _PROTLIB__NETWORK_MESSAGE_H_
     
    4647#include "tlp_list.h"
    4748
    48 namespace protlib {
    49 
    50 /** @addtogroup networkmsg Network Messages
     49namespace protlib
     50{
     51
     52/**
     53 * @addtogroup networkmsg Network Messages
    5154 * @ingroup network
    5255 * @{
    5356 */
    5457
    55 class NetMsgError : public ProtLibException {
     58class NetMsgError : public ProtLibException
     59{
    5660public:
    57         enum error_t {
    58                 ERROR_TOO_LONG,
    59                 ERROR_NO_MEM,
    60                 ERROR_INVALID_POS,
    61                 ERROR_NULL_POINTER,
    62                 ERROR_INVALID_START_OFFSET,
    63                 ERROR_TOO_SHORT,
    64                 ERROR_INVALID_BUFSIZE
    65         };
    66         NetMsgError(error_t e);
    67         const char * getstr() const;
    68         virtual const char *what() const throw() { return getstr(); }
    69         const error_t err;
     61  enum error_t
     62  {
     63    ERROR_TOO_LONG,
     64    ERROR_NO_MEM,
     65    ERROR_INVALID_POS,
     66    ERROR_NULL_POINTER,
     67    ERROR_INVALID_START_OFFSET,
     68    ERROR_TOO_SHORT,
     69    ERROR_INVALID_BUFSIZE
     70  };
     71  NetMsgError (error_t e);
     72  const char* getstr() const;
     73  virtual const char* what() const throw() { return getstr(); }
     74  const error_t err;
     75
    7076private:
    71         static const char* const errstr[];
     77  static const char* const errstr[];
    7278}; // end NetMsgError
    7379
     80
    7481/// network message
    75 /** This class is used to exchange data between signalling and transport
    76 * protocol.
    77 */
    78 class NetMsg {
     82/**
     83 * TODO fix comment
     84 * This class is used to exchange data between signalling and transport
     85 * protocol.
     86 */
     87class NetMsg
     88{
    7989public:
    80         static const uint32 max_size;
    81         /// constructor
    82         NetMsg(uint32 s);
    83         /// constructor
    84         NetMsg(uchar *b, uint32 s, bool copy = true);
    85         /// copy constructor
    86         NetMsg(const NetMsg& n);
    87         /// destructor
    88         ~NetMsg();
    89 
    90         NetMsg* copy() const { return new NetMsg(*this); }
    91 
    92         /// buffer
    93         /// get buffer size
    94         uint32 get_size() const;
    95         /// get bytes left until buffer ends
    96         uint32 get_bytes_left() const;
    97         /// get pointer offset
    98         uint32 get_pos() const;
    99         /// move pointer to offset
    100         NetMsg& set_pos(uint32 p);
    101         /// move pointer relative
    102         NetMsg& set_pos_r(int32 rp);
    103         /// set pointer to beginning
    104         NetMsg& to_start();
    105         /// Copy n bytes from buffer b into NetMsg buffer, starting there at position 0
    106         uint32 copy_from(const uchar *b, uint32 n);
    107         /// Copy n bytes from buffer b into NetMsg buffer, starting there at position start
    108         uint32 copy_from(const uchar *b, uint32 start, uint32 n);
    109         /// Copy n bytes into NetMsg buffer, starting from current position
    110         /// buffer position will be shifted by n bytes forward
    111         uint32 copy_from_cpos(const uchar *b, uint32 n);
    112 
    113         /// Copy n bytes from NetMsg buffer to given buffer, starting from current position
    114         /// buffer position will be shifted by n bytes forward
    115         uint32 copy_to_cpos(uchar *b, uint32 n);
    116         /// copy from NetMsg buffer
    117         uint32 copy_to(uchar *b, uint32 n) const;
    118         /// copy from NetMsg buffer
    119         uint32 copy_to(uchar *b, uint32 start, uint32 n) const;
    120         /// get pointer to beginning of the buffer
    121         uchar* get_buffer() const;
    122         /// get read-only pointer to current position of the buffer
    123         const uchar* get_pointer() const { return pos; };
    124         /// decode uint8
    125         uint8 decode8(bool move = true);
    126         /// decode uint16
    127         uint16 decode16(bool move = true);
    128         /// decode uint16 read only
    129         uint16 decode16ro() const;
    130         /// decode uint32
    131         uint32 decode32(bool move = true);
    132         /// decode uint64
    133         uint64 decode64(bool move = true);
    134         /// decode uint128
    135         uint128 decode128(bool move = true);
    136         /// encode uint8
    137         void encode8(uint8 i, bool move = true);
    138         /// encode uint16
    139         void encode16(uint16 i, bool move = true);
    140         /// encode uint32
    141         void encode32(uint32 i, bool move = true);
    142         /// encode uint64
    143         void encode64(uint64 i, bool move = true);
    144         /// encode uint128
    145         void encode128(uint128 i, bool move = true);
    146         /// decode uchars
    147         void decode(uchar *c, uint32 len, bool move = true);
    148         /// encode uchars
    149         void encode(const uchar *c, uint32 len, bool move = true);
    150         /// decode string
    151         uint32 decode(string& s, uint32 len, bool move = true);
    152         /// encode string
    153         uint32 encode(const string& s, bool move = true);
    154         /// decode IPv4
    155         void decode(struct in_addr& in, bool move = true);
    156         /// encode IPv4
    157         void encode(const struct in_addr& in, bool move = true);
    158         /// decode IPv6
    159         void decode(struct in6_addr& in, bool move = true);
    160         /// encode IPv6
    161         void encode(const struct in6_addr& in, bool move = true);
    162         /// truncate buffer
    163         uint32 truncate();
    164         /// truncate buffer
    165         uint32 truncate(uint32 t);
    166         /// apply padding
    167         void padding(uint32 len, bool move = true);
    168         /// test for equality
    169         bool operator==(const NetMsg& n) const;
    170         /// encode a NetMsg into this NetMsg
    171         void encode(const NetMsg& m, uint32 len, bool move = true);
    172         /// decode a NetMsg from this NetMsg
    173         void decode(NetMsg& m, bool move = true);
    174         /// print a raw hexdump of the buffer
    175         ostream& hexdump(ostream& os, uchar *startpos=0, uint32 length=0) const;
    176 
    177          /// clean up tlp_list
    178         void clean_up_tlp_list() { delete tlp_list; tlp_list=NULL; }
    179         /// get tlp_list
    180         TLP_list* get_TLP_list(); 
    181         const TLP_list* get_TLP_list() const;
    182         /// fill TLP list from buffer
    183         void fill_tlp_list(uint32 pdu_start,
    184                       uint32 pdu_stop,
    185                       uint32 (*get_length_from_obj_header)(const uint8*),
    186                       uint16 (*get_type_from_obj_header)(const uint8*),
    187                       uint16 (*get_subtype_from_obj_header)(const uint8*),
    188                       bool clean_up_first = true
    189                       );
    190 
     90
     91  static const uint32 max_size;
     92
     93  /**
     94   * Creates a network message object of the desired size if possible.
     95   *
     96   * @param size buffer size,  must be 0 < size <= max_size
     97   * @throw NetMsgError if size is illegal or operator new failed
     98   */
     99  NetMsg (uint32 size);
     100
     101  /**
     102   * Creates a network message object of the desired size if possible.
     103   *
     104   * @param b pointer to a buffer to initialize the NetMsg.
     105   * @param s buffer size
     106   * @param copy copy the buffer or use the buffer without copying.
     107   * @throw NetMsgError if size is illegal or operator new failed
     108   */
     109  NetMsg (uchar* buffer, uint32 size, bool copy = true);
     110
     111  NetMsg (const NetMsg& other);
     112
     113  ~NetMsg();
     114
     115  NetMsg* copy() const { return new NetMsg (*this); }
     116
     117  // getters --------------------------------------------------------------------------------------------------------------------------------------
     118
     119  /// @return total size of the NetMsg buffer
     120  size_t get_size() const;
     121
     122  /// @return the number of bytes left, that is the number of bytes from the current position to the end of the buffer
     123  size_t get_bytes_left() const;
     124
     125  /// @return read/write position in the buffer. if get_pos() == get_size(),  then end of buffer is reached
     126  size_t get_pos() const;
     127
     128  /// @return pointer to beginning of the buffer
     129  uchar* get_buffer() const;
     130
     131  /// @return read-only pointer to current position of the buffer
     132  const uchar* get_pointer() const { return pos; };
     133
     134  // setters --------------------------------------------------------------------------------------------------------------------------------------
     135
     136  NetMsg& set_pos (uint32 p);
     137  /// move pointer relative
     138  NetMsg& set_pos_r (int32 rp);
     139  /// set pointer to beginning
     140  NetMsg& to_start();
     141
     142  // fillers --------------------------------------------------------------------------------------------------------------------------------------
     143
     144  /// Copy n bytes from buffer b into NetMsg buffer, starting there at position 0
     145  uint32 copy_from (const uchar* source, uint32 length);
     146  /// Copy n bytes from buffer b into NetMsg buffer, starting there at position start
     147  uint32 copy_from (const uchar* source, uint32 from, uint32 length);
     148  /// Copy n bytes into NetMsg buffer, starting from current position
     149  /// buffer position will be shifted by n bytes forward
     150  uint32 copy_from_cpos (const uchar* source, uint32 length);
     151
     152  /// Copy n bytes from NetMsg buffer to given buffer, starting from current position
     153  /// buffer position will be shifted by n bytes forward
     154  uint32 copy_to_cpos (uchar* dest, uint32 length);
     155  /// copy from NetMsg buffer
     156  uint32 copy_to (uchar* dest, uint32 length) const;
     157  /// copy from NetMsg buffer
     158  uint32 copy_to (uchar* dest, uint32 start, uint32 length) const;
     159
     160  /// decode uint8
     161  uint8 decode8 (bool move = true);
     162  /// decode uint16
     163  uint16 decode16 (bool move = true);
     164  /// decode uint16 read only
     165  uint16 decode16ro() const;
     166  /// decode uint32
     167  uint32 decode32 (bool move = true);
     168  /// decode uint64
     169  uint64 decode64 (bool move = true);
     170  /// decode uint128
     171  uint128 decode128 (bool move = true);
     172
     173  /// encode uint8
     174  void encode8 (uint8 i, bool move = true);
     175  /// encode uint16
     176  void encode16 (uint16 i, bool move = true);
     177  /// encode uint32
     178  void encode32 (uint32 i, bool move = true);
     179  /// encode uint64
     180  void encode64 (uint64 i, bool move = true);
     181  /// encode uint128
     182  void encode128 (uint128 i, bool move = true);
     183
     184  /// decode uchars
     185  void decode (uchar* c, uint32 len, bool move = true);
     186  /// encode uchars
     187  void encode (const uchar* c, uint32 len, bool move = true);
     188  /// decode string
     189
     190  uint32 decode (string& s, uint32 len, bool move = true);
     191  /// encode string
     192  uint32 encode (const string& s, bool move = true);
     193  /// decode IPv4
     194  void decode (struct in_addr& in, bool move = true);
     195  /// encode IPv4
     196  void encode (const struct in_addr& in, bool move = true);
     197  /// decode IPv6
     198  void decode (struct in6_addr& in, bool move = true);
     199  /// encode IPv6
     200  void encode (const struct in6_addr& in, bool move = true);
     201  /// truncate buffer
     202  uint32 truncate();
     203  /// truncate buffer
     204  uint32 truncate (uint32 t);
     205  /// apply padding
     206  void padding (uint32 len, bool move = true);
     207  /// test for equality
     208  bool operator== (const NetMsg& n) const;
     209  /// encode a NetMsg into this NetMsg
     210  void encode (const NetMsg& m, uint32 len, bool move = true);
     211  /// decode a NetMsg from this NetMsg
     212  void decode (NetMsg& m, bool move = true);
     213
     214  /// print a raw hexdump of the buffer
     215  ostream& hexdump (ostream& os, uchar* startpos = 0, uint32 length = 0) const;
     216
     217  /// clean up tlp_list
     218  void clean_up_tlp_list() { delete tlp_list; tlp_list = NULL; }
     219  /// get tlp_list
     220  TLP_list* get_TLP_list();
     221  const TLP_list* get_TLP_list() const;
     222  /// fill TLP list from buffer
     223  void fill_tlp_list (uint32 pdu_start,
     224                      uint32 pdu_stop,
     225                      uint32 (*get_length_from_obj_header) (const uint8*),
     226                      uint16 (*get_type_from_obj_header) (const uint8*),
     227                      uint16 (*get_subtype_from_obj_header) (const uint8*),
     228                      bool clean_up_first = true
     229                     );
     230
     231  NetMsg& operator=(const NetMsg& other) = delete; //TODO
     232                     
    191233private:
    192         /// buffer for data
    193         uchar *buf;
    194         /// buffer size
    195         uint32 buf_len;     
    196         /// current reading/writing position
    197         uchar *pos;
    198         /// buffer end
    199         /** Pointer to the last byte of the buffer. */ 
    200         uchar *buf_end;
    201 
    202         /// true if copied, used in destructor
    203         bool allocated;
    204 
    205         /// store type and position (in netmsg buffer)
    206         TLP_list* tlp_list;
     234  uchar* buf;
     235  size_t buf_len;
     236
     237  /// current reading/writing position
     238  uchar* pos;
     239  /** Pointer to the last byte of the buffer. */
     240  uchar* buf_end;
     241
     242  /// TODO fix comment! true if copied, used in destructor
     243  bool allocated;
     244
     245  /// store type and position (in netmsg buffer)
     246  TLP_list* tlp_list;
    207247
    208248};
    209249
    210 inline std::ostream &operator<<(std::ostream &out, const NetMsg &msg) {
    211         msg.hexdump(out);
    212         return out;
     250inline std::ostream& operator<< (std::ostream& out, const NetMsg& msg)
     251{
     252  msg.hexdump (out);
     253  return out;
    213254}
    214255
     
    218259
    219260#endif // _PROTLIB__NETWORK_MESSAGE_H_
     261
  • protlib/trunk/include/protlib_types.h

    r6639 r6765  
    66/// $HeadURL$
    77// ===========================================================
    8 //                     
     8//
    99// Copyright (C) 2005-2007, all rights reserved by
    1010// - Institute of Telematics, Universitaet Karlsruhe (TH)
     
    1212// More information and contact:
    1313// https://projekte.tm.uka.de/trac/NSIS
    14 //                     
     14//
    1515// This program is free software; you can redistribute it and/or modify
    1616// it under the terms of the GNU General Public License as published by
     
    3333// $HeadURL$
    3434// ==========================================================
    35 //                     
     35//
    3636// (C)opyright, all rights reserved by
    3737// - Institute of Telematics, University of Karlsruhe (TH)
     
    6868 * @{
    6969 */
    70  
     70
    7171/**
    7272 * The abstract base class for all exceptions thrown by protlib.
     
    133133        uint128(const uint128& other) { w64.low= other.w64.low; w64.high= other.w64.high; }
    134134        uint128(const uint64& other) { w64.low= other; w64.high= 0; }
    135        
     135
    136136        uint128& operator=(const uint128& other) { w64.low= other.w64.low; w64.high= other.w64.high; return *this; }
    137137
     
    179179                uint64 high;
    180180        };
    181        
    182         struct words_32 { 
     181
     182        struct words_32 {
    183183                uint32 w1;
    184184                uint32 w2;
     
    194194
    195195
    196 inline 
    197 uint128 
     196inline
     197uint128
    198198uint128::operator~() const
    199199{
     
    202202
    203203
    204 inline 
    205 uint128 
     204inline
     205uint128
    206206uint128::operator|(const uint128& other) const
    207207{
     
    209209}
    210210
    211 inline 
    212 uint128 
     211inline
     212uint128
    213213uint128::operator&(const uint128& other) const
    214214{
     
    216216}
    217217
    218 inline 
    219 uint128 
     218inline
     219uint128
    220220uint128::operator^(const uint128& other) const
    221221{
     
    224224
    225225
    226 inline 
    227 uint128 
     226inline
     227uint128
    228228uint128::operator<<(int bits_num) const
    229229{
     
    244244}
    245245
    246 inline 
    247 uint128 
     246inline
     247uint128
    248248uint128::operator>>(int bits_num) const
    249249{
     
    265265}
    266266
    267 inline 
    268 uint128 
     267inline
     268uint128
    269269uint128::operator+=(const uint128& other)
    270270{
     
    273273        if (w64.low < other.w64.low)
    274274                w64.high++;
    275        
     275
    276276        return *this;
    277277}
    278278
    279279
    280 inline 
    281 uint128 
     280inline
     281uint128
    282282uint128::operator-=(const uint128& other)
    283283{
     
    290290
    291291
    292 inline 
    293 uint128 
     292inline
     293uint128
    294294uint128::operator+(const uint128& other) const {
    295295  return uint128(*this) += other;
     
    297297
    298298
    299 inline 
    300 uint128 
     299inline
     300uint128
    301301uint128::operator-(const uint128& other) const {
    302302  return uint128(*this) -= other;
     
    308308{
    309309        uint128 tmp(*this);
    310        
     310
    311311        w64.low++;
    312312        if (w64.low == 0) // overflow -> add carry
     
    320320{
    321321        uint128 tmp(*this);
    322        
     322
    323323        if (w64.low == 0) // underflow -> sub carry
    324324                w64.high--;
     
    358358 * currently used for Query encapsulation and TLS/TCP
    359359 * this should be changed in the future, probably by using an additional
    360  * attribute in the appladdress object 
     360 * attribute in the appladdress object
    361361 **/
    362362const protocol_t prot_tls_tcp    = 254;
  • protlib/trunk/include/radixtrie.h

    r4210 r6765  
    4848        node *insert(const netaddress &key, data_type &dat) {
    4949                node *a, *b, *c, *n, *m;
    50                 int cmp, pos = 0;
    51 
    52                 c = a = key.is_ipv4() ? v4head : v6head;
     50                int cmp= 0, pos = 0;
     51
     52                c = b = a = key.is_ipv4() ? v4head : v6head;
    5353
    5454                // search the tree as long as there are bits left in key
     
    235235        node *lookup_node(const netaddress &key, bool lpfm = true,
    236236            bool with_data = true) {
    237                 node *a, *b, *c, *lpfn;
     237                node *a, *b, *lpfn;
    238238                int cmp, pos = 0;
    239239
    240240                lpfn = 0;
    241                 c = b = a = key.is_ipv4() ? v4head : v6head;
     241                b = a = key.is_ipv4() ? v4head : v6head;
    242242                if (lpfm) {
    243243                        if (!with_data)
     
    288288                                break;
    289289
    290                         c = a;
    291290                        a = b;
    292291                }
  • protlib/trunk/include/threads.h

    r6286 r6765  
    66/// $HeadURL$
    77// ===========================================================
    8 //                     
     8//
    99// Copyright (C) 2005-2007, all rights reserved by
    1010// - Institute of Telematics, Universitaet Karlsruhe (TH)
     
    1212// More information and contact:
    1313// https://projekte.tm.uka.de/trac/NSIS
    14 //                     
     14//
    1515// This program is free software; you can redistribute it and/or modify
    1616// it under the terms of the GNU General Public License as published by
     
    8787class ThreadParam {
    8888  public:
     89        virtual ~ThreadParam();
    8990        ThreadParam();
    9091        ThreadParam(uint32 sleeptime, const char* name,
     
    101102};
    102103
     104inline ThreadParam::~ThreadParam() = default;
    103105
    104106/**
     
    162164        *
    163165        * The state of a thread does not really tell whether there are threads
    164         * active or not. It only represents a state in the life cycle of a 
     166        * active or not. It only represents a state in the life cycle of a
    165167        * thread object.
    166168        */
     
    181183        uint32 started_threads;
    182184
    183         /** 
     185        /**
    184186        * Thread-global mutex.
    185187        *
     
    207209        uint32 get_started_threads() const;
    208210};
    209    
     211
    210212
    211213inline void Thread::lock() {
     
    453455template <class T, class TParam>
    454456bool ThreadStarter<T, TParam>::sleepuntilstop() {
    455        
     457
    456458        for (uint32 i = 0; thread_object.is_running()
    457459                        && i < thread_param.sleep_time; i++)
     
    475477
    476478        Thread::state_t state = thread_object.get_state(false);
    477         struct timespec sleeptime; 
     479        struct timespec sleeptime;
    478480        sleeptime.tv_sec= 0; sleeptime.tv_nsec= 100000000L; // 100ms
    479         struct timespec remainingtime; 
     481        struct timespec remainingtime;
    480482        while ( state == Thread::STATE_INIT || thread_object.is_running() ) {
    481483                nanosleep(&sleeptime,&remainingtime);
     
    490492 * Stop and kill the threads.
    491493 *
    492  * @param kill kill the threads if they do not stop. 
     494 * @param kill kill the threads if they do not stop.
    493495 */
    494496template <class T, class TParam>
     
    506508                break;
    507509
    508           case T::STATE_ABORT: 
     510          case T::STATE_ABORT:
    509511                if ( ! kill ) {
    510512                        //thread_object.unlock();
     
    521523
    522524        if ( thread_object.is_running() ) {
    523                 thread_object.stop_processing(false); 
     525                thread_object.stop_processing(false);
    524526                // unlock and sleep so the threads have a chance to stop.
    525527                thread_object.unlock();
     
    539541                thread_object.unlock();
    540542                if (kill) {
    541                         for (unsigned i = 0; i < pthreads.size(); i++) 
     543                        for (unsigned i = 0; i < pthreads.size(); i++)
    542544                                pthread_cancel( pthreads[i] );
    543545
    544546                        sleepuntilstop();
    545547
    546                         for (unsigned i = 0; i < pthreads.size(); i++) 
     548                        for (unsigned i = 0; i < pthreads.size(); i++)
    547549                                pthread_kill(pthreads[i], 9);
    548550
     
    569571
    570572#endif // PROTLIB__THREADS_H
     573
  • protlib/trunk/src/Makefile.am

    r6407 r6765  
    1414libprot_a_DEPENDENCIES = $(FQUEUE_LIB)
    1515
     16if PROTLIB_WITH_RAO
     17
    1618if PROTLIB_WITH_NFQ
    1719libprot_a_SOURCES += tp_queryencap_nfq.cpp
     
    1921libprot_a_SOURCES += tp_queryencap.cpp
    2022endif
     23
     24endif #PROTLIB_WITH_RAO
    2125
    2226nobase_include_HEADERS=$(top_srcdir)/include/address.h                  \
  • protlib/trunk/src/ie.cpp

    r6148 r6765  
    223223PDUSyntaxError::PDUSyntaxError(const char* msg)
    224224                : IEError(IEError::ERROR_PDU_SYNTAX),
    225                   coding(coding), category(0), type(0), subtype(0),
     225                  coding(0), category(0), type(0), subtype(0),
    226226                  errorpos(0), message(msg) {
    227227
  • protlib/trunk/src/messages.cpp

    r5724 r6765  
    107107/// Copy constructor
    108108message::message(const message& m)
    109         : type(m.type), source(m.source), msg_id(msg_id) {
     109        : type(m.type), source(m.source), msg_id(m.msg_id) {
    110110} // end constructor
    111111
  • protlib/trunk/src/network_message.cpp

    r6595 r6765  
    66/// $HeadURL$
    77// ===========================================================
    8 //                     
     8//
    99// Copyright (C) 2005-2007, all rights reserved by
    1010// - Institute of Telematics, Universitaet Karlsruhe (TH)
     
    1212// More information and contact:
    1313// https://projekte.tm.uka.de/trac/NSIS
    14 //                     
     14//
    1515// This program is free software; you can redistribute it and/or modify
    1616// it under the terms of the GNU General Public License as published by
     
    3232 */
    3333
    34 #include <netinet/in.h> 
     34#include <netinet/in.h>
    3535#include <string.h>
    3636#include <cctype>
     
    4444#include "logfile.h" // only required for color definitions
    4545
    46 namespace protlib {
    47 
    48 
    49   using namespace protlib::log;
     46#include "protlib_assert.h"
     47
     48namespace protlib
     49{
     50
     51
     52using namespace protlib::log;
    5053/** @addtogroup networkmsg Network Messages
    5154 * @{
     
    5356
    5457/** @param e error code */
    55 NetMsgError::NetMsgError(error_t e) : err(e) {}
     58NetMsgError::NetMsgError (error_t e) : err (e) {}
    5659
    5760const char* NetMsgError::getstr() const { return errstr[err]; }
    5861
    5962/** NetMsg error strings */
    60 const char* const NetMsgError::errstr[] = 
    61 {
    62     "Network message too long.",
    63     "Not enough memory to allocate network message.",
    64     "Operation not valid because of pointer position in NetMsg buffer.",
    65     "NULL pointer argument in call to NetMsg constructor.",
    66     "Invalid start offset.",
    67     "NetMsg buffer too short.",
    68     "Invalid buffer size: zero"
     63const char* const NetMsgError::errstr[] =
     64{
     65  "Network message too long.",
     66  "Not enough memory to allocate network message.",
     67  "Operation not valid because of pointer position in NetMsg buffer.",
     68  "NULL pointer argument in call to NetMsg constructor.",
     69  "Invalid start offset.",
     70  "NetMsg buffer too short.",
     71  "Invalid buffer size: zero"
    6972}; // end network message error strings
    7073
     
    7477const uint32 NetMsg::max_size = 128000;
    7578
    76 /** Creates a network message object of the desired size if possible.
    77  * @param s buffer size.
    78  */
    79         NetMsg::NetMsg(uint32 s) : buf(NULL), buf_len(0), pos(NULL), buf_end(NULL), allocated(true), tlp_list() {
    80   if (s>max_size) throw NetMsgError(NetMsgError::ERROR_TOO_LONG);
    81   if (s==0) throw NetMsgError(NetMsgError::ERROR_INVALID_BUFSIZE);
    82   buf = new(nothrow) uchar[s];
    83   if (!buf) throw NetMsgError(NetMsgError::ERROR_NO_MEM);
    84   memset(buf,0,s);
    85   buf_len = s;
     79
     80NetMsg::NetMsg (protlib::uint32 size) :
     81  buf (nullptr), buf_len (0), pos (nullptr), buf_end (nullptr), allocated (true), tlp_list()
     82{
     83  if (size > max_size) throw NetMsgError (NetMsgError::ERROR_TOO_LONG);
     84  if (size == 0) throw NetMsgError (NetMsgError::ERROR_INVALID_BUFSIZE);
     85
     86  buf = new (std::nothrow) uchar[size];
     87  if (!buf) throw NetMsgError (NetMsgError::ERROR_NO_MEM);
     88
     89  memset (buf, 0, size);
     90  buf_len = size;
    8691  pos = buf;
    87   buf_end = buf+(s-1);
    88 } // end constructor
    89 
    90 /** Creates a network message object of the desired size if possible.
    91  * @param b pointer to a buffer to initialize the NetMsg.
    92  * @param s buffer size
    93  * @param copy copy the buffer or use the buffer without copying.
    94  */
    95 NetMsg::NetMsg(uchar *b, uint32 s, bool copy) : buf(NULL), buf_len(0), pos(NULL), buf_end(NULL), allocated(false), tlp_list(NULL) {
    96   if (s>max_size) throw NetMsgError(NetMsgError::ERROR_TOO_LONG);
    97   if (s==0) throw NetMsgError(NetMsgError::ERROR_INVALID_BUFSIZE);
    98   if (copy) {
    99     buf = new(nothrow) uchar[s];
    100     if (!buf) throw NetMsgError(NetMsgError::ERROR_NO_MEM);
    101     allocated= true;
    102     memcpy(buf,b,s);
    103   } else {
    104     buf=b;
    105     if (!buf) throw NetMsgError(NetMsgError::ERROR_NULL_POINTER);
    106   } // end if copy
    107   buf_len = s;
     92  buf_end = buf + (size - 1);
     93}
     94
     95NetMsg::NetMsg (protlib::uchar* buffer, protlib::uint32 size, bool copy) :
     96  buf (nullptr), buf_len (0), pos (nullptr), buf_end (nullptr), allocated (false), tlp_list ()
     97{
     98  if (size > max_size) throw NetMsgError (NetMsgError::ERROR_TOO_LONG);
     99  if (size == 0) throw NetMsgError (NetMsgError::ERROR_INVALID_BUFSIZE);
     100
     101  if (copy)
     102  {
     103    buf = new (nothrow) uchar[size];
     104    if (!buf) throw NetMsgError (NetMsgError::ERROR_NO_MEM);
     105    allocated = true;
     106    memcpy (buf, buffer, size);
     107  }
     108  else
     109  {
     110    buf = buffer;
     111    if (!buf) throw NetMsgError (NetMsgError::ERROR_NULL_POINTER);
     112  }
     113
     114  buf_len = size;
    108115  pos = buf;
    109   buf_end = buf+(s-1);
    110 } // end constructor
    111 
     116  buf_end = buf + (size - 1);
     117}
    112118
    113119// copy constructor
    114 NetMsg::NetMsg(const NetMsg& n) : buf(NULL), buf_len(n.buf_len), pos(NULL), buf_end(NULL), allocated(false),
    115                                   tlp_list(n.get_TLP_list()?new TLP_list(*(n.get_TLP_list())):NULL) {
     120NetMsg::NetMsg (const protlib::NetMsg& other) : buf (nullptr), buf_len (other.buf_len), pos (nullptr), buf_end (nullptr), allocated (false),
     121  tlp_list (other.get_TLP_list() ? new TLP_list (* (other.get_TLP_list())) : NULL)
     122{
    116123  // only copy a buffer of length > 0, otherwise we initialize as empty buffer
    117124  if (buf_len)
    118125  {
    119           buf = new(nothrow) uchar[buf_len];
    120           if (!buf) throw NetMsgError(NetMsgError::ERROR_NO_MEM);
    121           allocated= true;
    122           memcpy(buf,n.buf,buf_len);
    123           pos = buf+(n.pos-n.buf);
    124           buf_end = buf+(buf_len-1);
     126    buf = new (nothrow) uchar[buf_len];
     127    if (!buf) throw NetMsgError (NetMsgError::ERROR_NO_MEM);
     128    allocated = true;
     129    memcpy (buf, other.buf, buf_len);
     130
     131    pos = buf + (other.pos - other.buf);
     132    buf_end = buf + (buf_len - 1);
    125133  }
    126134} // end copy constructor
    127135
    128136
    129 /** Frees the message buffer if memory was actually allocated. */
    130 NetMsg::~NetMsg() {
    131   if (buf && allocated) { delete[] buf; buf= 0; }
     137NetMsg::~NetMsg()
     138{
     139  // Frees the message buffer if memory was actually allocated.
     140  if (buf && allocated) { delete[] buf; buf = 0; }
    132141  delete tlp_list;
    133 } // end destructor
    134 
    135 /** @return the size of the network message buffer. */
    136 uint32 NetMsg::get_size() const {
    137    return buf_len;
    138 } // end get_size
    139 
    140 /** Returns the number of bytes left, that is the number of bytes from the
    141  * current position to the end of the buffer.
    142  */
    143 uint32 NetMsg::get_bytes_left() const {
    144   if (buf<=pos)
    145   {
    146     if (pos<=buf_end)
    147       return (buf_end-pos)+1;
    148     else
    149       return 0;
    150   }
    151   else /// should never happen
    152     throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
    153 } // end get_size
    154 
    155 /** Returns the offset of the buffer pointer.
    156  * Note that an offset of buf_len means that the pointer is one byte behind
    157  * the end of the buffer. This means that you reached the buffer end.
    158  * This leads to a get-pos result of buf_len.
    159  */
    160 uint32 NetMsg::get_pos() const {
    161   if ((buf<=pos) && (pos<=(buf_end+1)))
    162     return (pos-buf);
    163   else
    164     throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     142}
     143
     144// getters --------------------------------------------------------------------------------------------------------------------------------------
     145
     146size_t NetMsg::get_size() const { return buf_len; }
     147
     148size_t NetMsg::get_bytes_left() const
     149{
     150  PROTLIB_assert (buf <= pos);
     151
     152  if (pos <= buf_end)
     153    return (buf_end - pos) + 1;
     154  else
     155    return 0;
     156}
     157
     158size_t NetMsg::get_pos() const
     159{
     160  if ( (buf <= pos) && (pos <= (buf_end + 1)))
     161    return (pos - buf);
     162  else
     163    throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    165164} // end get_pos
    166165
    167 /** Move pointer to the given offset.
    168  * @param p pointer offset
     166uchar* NetMsg::get_buffer() const
     167{
     168  return buf;
     169}                                                           // end get_buffer
     170
     171
     172
     173// setters --------------------------------------------------------------------------------------------------------------------------------------
     174
     175
     176/** Move pointer to the given offset.
     177 * @param p pointer offset
    169178 * @note if p==buf_len then the pointer is one byte behind the buffer end.
    170179 * This is correct and signals that all data has been read from the buffer.
    171180 */
    172 NetMsg& NetMsg::set_pos(uint32 p) {
    173   if (p<=buf_len)
    174   {
    175     pos = buf+p;
     181NetMsg& NetMsg::set_pos (uint32 p)
     182{
     183  if (p <= buf_len)
     184  {
     185    pos = buf + p;
    176186    return *this;
    177   } 
    178   else 
    179     throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     187  }
     188  else
     189    throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    180190} // end set_pos
    181191
    182192/** Move pointer relative to current position.
    183  * @param rp offset relative to current position.
    184  */
    185 NetMsg& NetMsg::set_pos_r(int32 rp)
    186 {
    187   if (((pos+rp)>=buf) && ((pos+rp)<=(buf_end+1))) {
     193 * @param rp offset relative to current position.
     194 */
     195NetMsg& NetMsg::set_pos_r (int32 rp)
     196{
     197  if ( ( (pos + rp) >= buf) && ( (pos + rp) <= (buf_end + 1)))
     198  {
    188199    pos += rp;
    189   } 
    190   else 
    191     throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     200  }
     201  else
     202    throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    192203  return *this;
    193204} // end set_pos_r
    194205
    195206/** Set current position to buffer start. */
    196 NetMsg& NetMsg::to_start() {
    197   pos=buf;
     207NetMsg& NetMsg::to_start()
     208{
     209  pos = buf;
    198210  return *this;
    199211} // end to_start
     
    204216 * @return number of copied bytes
    205217 */
    206 uint32 NetMsg::copy_from(const uchar *b, uint32 n) {
    207   return copy_from(b,0,n);
     218uint32 NetMsg::copy_from (const protlib::uchar* source, protlib::uint32 length)
     219{
     220  return copy_from (source, 0, length);
    208221} // end copy_from
    209222
     
    214227 * @return number of copied bytes
    215228 */
    216 uint32 NetMsg::copy_from(const uchar *b, uint32 start, uint32 n) {
    217   if ((n+start)>buf_len) throw NetMsgError(NetMsgError::ERROR_TOO_SHORT);
    218   memmove(buf+start,b,n);
    219   return n;
     229uint32 NetMsg::copy_from (const protlib::uchar* source, protlib::uint32 from, protlib::uint32 length)
     230{
     231  if ( (length + from) > buf_len) throw NetMsgError (NetMsgError::ERROR_TOO_SHORT);
     232  memmove (buf + from, source, length);
     233  return length;
    220234} // end copy_from
    221235
     
    228242 * @return number of copied bytes
    229243 */
    230 uint32 NetMsg::copy_from_cpos(const uchar *b, uint32 n) {
    231   if ((n+pos-buf)>buf_len) throw NetMsgError(NetMsgError::ERROR_TOO_SHORT);
    232   memmove(pos,b,n);
    233   pos+= n;
    234 
    235   return n;
     244uint32 NetMsg::copy_from_cpos (const protlib::uchar* source, protlib::uint32 length)
     245{
     246  if ( (length + pos) > (buf_len + buf) ) throw NetMsgError (NetMsgError::ERROR_TOO_SHORT);
     247  memmove (pos, source, length);
     248  pos += length;
     249
     250  return length;
    236251} // end copy_from_cpos
    237252
    238253
    239254/** Copy n bytes from NetMsg buffer into b. If the NetMsg buffer is smaller
    240  * than n, less bytes are copied. 
     255 * than n, less bytes are copied.
    241256 * @param b destination buffer
    242257 * @param n number of bytes to be copied
    243258 * @return number of copied bytes
    244259 */
    245 uint32 NetMsg::copy_to_cpos(uchar *b, uint32 n) {
    246         if ((pos+n)>buf_end) n= buf_end-pos;
    247         memmove(b,pos,n);
    248         pos+= n;
    249         return n;
     260uint32 NetMsg::copy_to_cpos (protlib::uchar* dest, protlib::uint32 length)
     261{
     262  length = std::min ((size_t)length, get_bytes_left());
     263  memmove (dest, pos, length);
     264  pos += length;
     265  return length;
    250266} // end copy_to_cpos
    251267
    252268/** Copy n bytes from NetMsg buffer into b. If the NetMsg buffer is smaller
    253  * than n, less bytes are copied. 
     269 * than n, less bytes are copied.
    254270 * @param b destination buffer
    255271 * @param n number of bytes to be copied
    256272 * @return number of copied bytes
    257273 */
    258 uint32 NetMsg::copy_to(uchar *b, uint32 n) const {
    259   try {
    260     return copy_to(b,0,n);
    261   } catch(NetMsgError& e) {
     274uint32 NetMsg::copy_to (protlib::uchar* dest, protlib::uint32 length) const
     275{
     276  try
     277  {
     278    return copy_to (dest, 0, length);
     279  }
     280  catch (NetMsgError& e)
     281  {
    262282    // ERROR, should not happen
    263283  } // end try-catch
     
    266286
    267287/** Copy n bytes from NetMsg buffer into b. If the NetMsg buffer is smaller
    268  * than n, less bytes are copied. 
     288 * than n, less bytes are copied.
    269289 * @param b destination buffer
    270290 * @param start offset into NetMsg buffer
     
    272292 * @return number of copied bytes
    273293 */
    274 uint32 NetMsg::copy_to(uchar *b, uint32 start, uint32 n) const {
    275   if (start>=buf_len) throw NetMsgError(NetMsgError::ERROR_INVALID_START_OFFSET);
    276   if ((n+start)>buf_len) n=buf_len-start;
    277   memmove(b,buf+start,n);
    278   return n;
     294uint32 NetMsg::copy_to (protlib::uchar* dest, protlib::uint32 start, protlib::uint32 length) const
     295{
     296  if (start >= buf_len) throw NetMsgError (NetMsgError::ERROR_INVALID_START_OFFSET);
     297  if ( (length + start) > buf_len) length = buf_len - start;
     298  memmove (dest, buf + start, length);
     299  return length;
    279300} // end copy_to
    280301
    281 /** returns a pointer to the beginning of the NetMsg buffer. */
    282 uchar* NetMsg::get_buffer() const {
    283         return buf;
    284 } // end get_buffer
    285302
    286303
     
    289306 * @param move determines if current position in buffer is changed or not.
    290307 */
    291 uint8 NetMsg::decode8(bool move) {
     308uint8 NetMsg::decode8 (bool move)
     309{
    292310  register uint8 i;
    293   if (pos<=buf_end)
     311  if (pos <= buf_end)
    294312  {
    295313    i = *pos;
    296     if (move) pos+=1;
    297   } 
    298   else 
    299     throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
    300  
     314    if (move) pos += 1;
     315  }
     316  else
     317    throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
     318
    301319  return i;
    302320} // end decode uint8
     
    305323 * @param move determines if current position in buffer is changed or not.
    306324 */
    307 uint16 NetMsg::decode16(bool move) {
     325uint16 NetMsg::decode16 (bool move)
     326{
    308327  register uint16 i;
    309   if ((pos+1)<=buf_end) {
    310     i = ntohs(*((uint16*)pos));
    311     if (move) pos+=2;
    312   }
    313   else
    314     throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     328  if ( (pos + 1) <= buf_end)
     329  {
     330    i = ntohs (* ( (uint16*) pos));
     331    if (move) pos += 2;
     332  }
     333  else
     334    throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    315335  return i;
    316336} // end decode uint16
    317337
    318 /** Decode a uint16 integer.
    319  @note buffer position is not changed!   */
    320 uint16 NetMsg::decode16ro() const {
    321         register uint16 i;
    322         if ((pos+1)<=buf_end) {
    323                 i = ntohs(*((uint16*)pos));
    324         } 
    325         else 
    326                 throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
    327         return i;
    328 } // end decode uint16
     338/** Decode a uint16 integer.
     339 @note buffer position is not changed!   */
     340uint16 NetMsg::decode16ro() const
     341{
     342  register uint16 i;
     343  if ( (pos + 1) <= buf_end)
     344  {
     345    i = ntohs (* ( (uint16*) pos));
     346  }
     347  else
     348    throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
     349  return i;
     350} // end decode uint16
    329351
    330352
     
    332354 * @param move determines if current position in buffer is changed or not.
    333355 */
    334 uint32 NetMsg::decode32(bool move) {
     356uint32 NetMsg::decode32 (bool move)
     357{
    335358  register uint32 i;
    336   if ((pos+3)<=buf_end) {
    337     i = ntohl(*((uint32*)pos));
    338     if (move) pos+=4;
    339   }
    340   else
    341     throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     359  if ( (pos + 3) <= buf_end)
     360  {
     361    i = ntohl (* ( (uint32*) pos));
     362    if (move) pos += 4;
     363  }
     364  else
     365    throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    342366  return i;
    343367} // end decode uint32
     
    346370 * @param move determines if current position in buffer is changed or not.
    347371 */
    348 uint64 NetMsg::decode64(bool move) {
     372uint64 NetMsg::decode64 (bool move)
     373{
    349374  uint64 hi = 0;
    350375  uint64 lo = 0;
    351376  uint64 res = 0;
    352   uint32* p = (uint32*)pos;
    353   if ((pos+7)<=buf_end) {
    354     hi = ntohl(*p);
    355     lo = ntohl(*(p+1));
    356     res = (hi<<32)+lo;
    357     if (move) pos+=8;
    358   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     377  uint32* p = (uint32*) pos;
     378  if ( (pos + 7) <= buf_end)
     379  {
     380    hi = ntohl (*p);
     381    lo = ntohl (* (p + 1));
     382    res = (hi << 32) + lo;
     383    if (move) pos += 8;
     384  }
     385  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    359386  return res;
    360387} // end decode uint64
     
    363390 * @param move determines if current position in buffer is changed or not.
    364391 */
    365 uint128 NetMsg::decode128(bool move) {
     392uint128 NetMsg::decode128 (bool move)
     393{
    366394  uint32 word1, word2, word3, word4;
    367395  word1 = NetMsg::decode32();
     
    370398  word4 = NetMsg::decode32();
    371399
    372   if (!move) 
    373           pos-=16;
    374 
    375   return uint128(word1,word2,word3,word4);
     400  if (!move)
     401    pos -= 16;
     402
     403  return uint128 (word1, word2, word3, word4);
    376404} // end decode uint128
    377405
     
    380408 * @param move determines if current position in buffer is changed or not.
    381409 */
    382 void NetMsg::encode8(uint8 i, bool move) {
    383   if (pos<=buf_end) {
     410void NetMsg::encode8 (uint8 i, bool move)
     411{
     412  if (pos <= buf_end)
     413  {
    384414    *pos = i;
    385     if (move) pos+=1;
    386   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     415    if (move) pos += 1;
     416  }
     417  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    387418} // end encode uint8
    388419
     
    391422 * @param move determines if current position in buffer is changed or not.
    392423 */
    393 void NetMsg::encode16(uint16 i, bool move) {
    394   if ((pos+1)<=buf_end) {
    395     *((uint16*)pos) = htons(i);
    396     if (move) pos+=2;
    397   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     424void NetMsg::encode16 (uint16 i, bool move)
     425{
     426  if ( (pos + 1) <= buf_end)
     427  {
     428    * ( (uint16*) pos) = htons (i);
     429    if (move) pos += 2;
     430  }
     431  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    398432} // end encode uint16
    399433
     
    402436 * @param move determines if current position in buffer is changed or not.
    403437 */
    404 void NetMsg::encode32(uint32 i, bool move) {
    405   if ((pos+3)<=buf_end) {
    406     *((uint32*)pos) = htonl(i);
    407     if (move) pos+=4;
    408   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     438void NetMsg::encode32 (uint32 i, bool move)
     439{
     440  if ( (pos + 3) <= buf_end)
     441  {
     442    * ( (uint32*) pos) = htonl (i);
     443    if (move) pos += 4;
     444  }
     445  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    409446} // end encode uint32
    410447
     
    413450 * @param move determines if current position in buffer is changed or not.
    414451 */
    415 void NetMsg::encode64(uint64 i, bool move) {
    416         uint32 hi = 0;
    417         uint32 lo = 0;
    418         uint32* p = (uint32*)pos;
    419         if ((pos+7)<=buf_end) {
    420                 lo = i;
    421                 hi = (i>>32);
    422                 *p = htonl(hi);
    423                 *(p+1) = htonl(lo);
    424                 if (move) pos+=8;
    425         } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     452void NetMsg::encode64 (uint64 i, bool move)
     453{
     454  uint32 hi = 0;
     455  uint32 lo = 0;
     456  uint32* p = (uint32*) pos;
     457  if ( (pos + 7) <= buf_end)
     458  {
     459    lo = i;
     460    hi = (i >> 32);
     461    *p = htonl (hi);
     462    * (p + 1) = htonl (lo);
     463    if (move) pos += 8;
     464  }
     465  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    426466} // end encode uint64
    427467
     
    430470 * @param move determines if current position in buffer is changed or not.
    431471 */
    432 void NetMsg::encode128(uint128 i, bool move) {
    433         encode32(i.get_w1());
    434         encode32(i.get_w2());
    435         encode32(i.get_w3());
    436         encode32(i.get_w4());
    437         if (!move) pos-= 16;
     472void NetMsg::encode128 (uint128 i, bool move)
     473{
     474  encode32 (i.get_w1());
     475  encode32 (i.get_w2());
     476  encode32 (i.get_w3());
     477  encode32 (i.get_w4());
     478  if (!move) pos -= 16;
    438479} // end encode uint128
    439480
     
    443484 * @param move determines if current position in buffer is changed or not.
    444485 */
    445 void NetMsg::decode(uchar *c, uint32 len, bool move) {
     486void NetMsg::decode (uchar* c, uint32 len, bool move)
     487{
    446488  if (len == 0) // do nothing, otherwise next statement will fail
    447           return;
    448   if ((pos+(len-1))<=buf_end) {
    449     memmove(c,pos,len);
    450     if (move) pos+=len;
    451   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     489    return;
     490  if ( (pos + (len - 1)) <= buf_end)
     491  {
     492    memmove (c, pos, len);
     493    if (move) pos += len;
     494  }
     495  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    452496} // end decode uchars
    453497
     
    457501 * @param move determines if current position in buffer is changed or not.
    458502 */
    459 void NetMsg::encode(const uchar *c, uint32 len, bool move) {
     503void NetMsg::encode (const uchar* c, uint32 len, bool move)
     504{
    460505  if (len == 0) // do nothing, otherwise next statement will fail
    461           return;
    462 
    463   if ((pos+(len-1))<=buf_end) {
    464     memmove(pos,c,len);
    465     if (move) pos+=len;
    466   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     506    return;
     507
     508  if ( (pos + (len - 1)) <= buf_end)
     509  {
     510    memmove (pos, c, len);
     511    if (move) pos += len;
     512  }
     513  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    467514} // end encode uchars
    468515
     
    473520 * @return string length.
    474521 */
    475 uint32 NetMsg::decode(string& s, uint32 len, bool move) {
    476   if (len==0) {
     522uint32 NetMsg::decode (string& s, uint32 len, bool move)
     523{
     524  if (len == 0)
     525  {
    477526    s.clear();
    478527    return 0;
    479528  }
    480529
    481   if ((pos+(len-1))<=buf_end) {
     530  if ( (pos + (len - 1)) <= buf_end)
     531  {
    482532    s.clear();
    483     s.assign((const char*)pos,0,len);
    484     if (move) pos+=len;
     533    s.assign ( (const char*) pos, 0, len);
     534    if (move) pos += len;
    485535    return s.length();
    486   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     536  }
     537  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    487538} // end decode string
    488539
     
    491542 * @param move determines if current position in buffer is changed or not.
    492543 */
    493 uint32 NetMsg::encode(const string& s, bool move) {
     544uint32 NetMsg::encode (const string& s, bool move)
     545{
    494546  uint32 len = s.length();
    495   if (len==0) {
     547  if (len == 0)
     548  {
    496549    return 0;
    497550  }
    498   if ((pos+(len-1))<=buf_end) {
    499     memmove(pos,s.c_str(),len);
    500     if (move) pos+=len;
     551  if ( (pos + (len - 1)) <= buf_end)
     552  {
     553    memmove (pos, s.c_str(), len);
     554    if (move) pos += len;
    501555    return len;
    502   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     556  }
     557  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    503558} // end encode string
    504559
    505 /** Decode an IPv4 address. 
     560/** Decode an IPv4 address.
    506561 * @param in reference to in_addr
    507562 * @param move determines if current position in buffer is changed or not.
    508563 */
    509 void NetMsg::decode(struct in_addr& in, bool move) {
     564void NetMsg::decode (struct in_addr& in, bool move)
     565{
    510566  //in.s_addr = decode32(move);
    511   if ((pos+3)<=buf_end) {
    512     in.s_addr = *((uint32*)pos);
    513     if (move) pos+=4;
    514   }
    515   else
    516     throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     567  if ( (pos + 3) <= buf_end)
     568  {
     569    in.s_addr = * ( (uint32*) pos);
     570    if (move) pos += 4;
     571  }
     572  else
     573    throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    517574} // end decode(in_addr)
    518575
    519 /** Encode an IPv4 address. 
     576/** Encode an IPv4 address.
    520577 * @param in reference to const in_addr
    521578 * @param move determines if current position in buffer is changed or not.
    522579 */
    523 void NetMsg::encode(const struct in_addr& in, bool move) {
     580void NetMsg::encode (const struct in_addr& in, bool move)
     581{
    524582  //encode32(in.s_addr,move);
    525   if ((pos+3)<=buf_end) {
    526     *((uint32*)pos) = in.s_addr;
    527     if (move) pos+=4;
    528   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     583  if ( (pos + 3) <= buf_end)
     584  {
     585    * ( (uint32*) pos) = in.s_addr;
     586    if (move) pos += 4;
     587  }
     588  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    529589} // end encode(in_addr)
    530590
    531 /** Decode an IPv6 address. 
     591/** Decode an IPv6 address.
    532592 * @param in reference to in6_addr
    533593 * @param move determines if current position in buffer is changed or not.
    534594 */
    535 void NetMsg::decode(struct in6_addr& in, bool move) {
    536   if ((pos+15)<=buf_end) {
    537     memmove(in.s6_addr,pos,16);
    538     if (move) pos+=16;
    539   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     595void NetMsg::decode (struct in6_addr& in, bool move)
     596{
     597  if ( (pos + 15) <= buf_end)
     598  {
     599    memmove (in.s6_addr, pos, 16);
     600    if (move) pos += 16;
     601  }
     602  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    540603} // end decode(in6_addr)
    541604
    542 /** Encode an IPv6 address. 
     605/** Encode an IPv6 address.
    543606 * @param in reference to const in6_addr
    544607 * @param move determines if current position in buffer is changed or not.
    545608 */
    546 void NetMsg::encode(const struct in6_addr& in, bool move) {
    547   if ((pos+15)<=buf_end) {
    548     memmove(pos,in.s6_addr,16);
    549     if (move) pos+=16;
    550   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     609void NetMsg::encode (const struct in6_addr& in, bool move)
     610{
     611  if ( (pos + 15) <= buf_end)
     612  {
     613    memmove (pos, in.s6_addr, 16);
     614    if (move) pos += 16;
     615  }
     616  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    551617} // end encode(in6_addr)
    552618
     
    560626 * @return new buffer size.
    561627 */
    562 uint32 NetMsg::truncate() {
    563   if ((pos>=buf) && (pos<=(buf_end+1))) {
    564     buf_len = (pos-buf);
    565     buf_end = pos-1;
     628uint32 NetMsg::truncate()
     629{
     630  if ( (pos >= buf) && (pos <= (buf_end + 1)))
     631  {
     632    buf_len = (pos - buf);
     633    buf_end = pos - 1;
    566634    to_start();
    567   } else {
    568     throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     635  }
     636  else
     637  {
     638    throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    569639  } // end if buf
    570640  return buf_len;
     
    572642
    573643/** Truncates the buffer at given offset. */
    574 uint32 NetMsg::truncate(uint32 t) {
    575   set_pos(t);
     644uint32 NetMsg::truncate (uint32 t)
     645{
     646  set_pos (t);
    576647  return truncate();
    577648} // end truncate
     
    581652 * @param move determines if current position in buffer is changed or not.
    582653 */
    583 void NetMsg::padding(uint32 len, bool move) {
    584   if (len==0) return;
    585   else if ((pos+(len-1))<=buf_end) {
    586     memset(pos,0,len);
    587     if (move) pos+=len;
    588   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     654void NetMsg::padding (uint32 len, bool move)
     655{
     656  if (len == 0) return;
     657  else if ( (pos + (len - 1)) <= buf_end)
     658  {
     659    memset (pos, 0, len);
     660    if (move) pos += len;
     661  }
     662  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    589663} // end padding
    590664
    591665/** Two network messages are equal if their buffers and states are equal. */
    592 bool NetMsg::operator==(const NetMsg& n) const
     666bool NetMsg::operator== (const NetMsg& n) const
    593667{
    594668  // buffer size equal
    595   if (buf_len==n.buf_len)
     669  if (buf_len == n.buf_len)
    596670  {
    597671    // empty buffers are considered equal
    598     if ((buf==NULL) && (n.buf==NULL))
    599       return true;
    600     else
    601     if (buf && n.buf)
     672    if ( (buf == NULL) && (n.buf == NULL))
     673      return true;
     674    else if (buf && n.buf)
    602675    {
    603       // compare buffer content 
    604       if (memcmp(buf,n.buf,buf_len)==0)
     676      // compare buffer content
     677      if (memcmp (buf, n.buf, buf_len) == 0)
    605678      {
    606         // last check: position must be equal
    607         return ((pos-buf)==(n.pos-n.buf));
    608       } 
    609       else 
    610         return false;
    611     } 
    612     else 
     679        // last check: position must be equal
     680        return ( (pos - buf) == (n.pos - n.buf));
     681      }
     682      else
     683        return false;
     684    }
     685    else
    613686      return false;
    614   } 
    615   else 
     687  }
     688  else
    616689    return false;
    617690} // end operator==
     
    621694 * @param move determines if current position in buffer is changed or not.
    622695 */
    623 void NetMsg::decode(NetMsg& m, bool move) {
     696void NetMsg::decode (NetMsg& m, bool move)
     697{
    624698  uint32 len = m.get_size();
    625699  if (len == 0) // do nothing
    626           return;
    627 
    628   if ((pos+(len-1))<=buf_end) {
     700    return;
     701
     702  if ( (pos + (len - 1)) <= buf_end)
     703  {
    629704    // copy buffer
    630705    m.to_start();
    631     memmove(m.buf,pos,len);
    632     if (move) pos+=len;
    633   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     706    memmove (m.buf, pos, len);
     707    if (move) pos += len;
     708  }
     709  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    634710} // end decode NetMsg
    635711
     
    639715 * @param move determines if current position in buffer is changed or not.
    640716 */
    641 void NetMsg::encode(const NetMsg& m, uint32 len, bool move) {
    642   if (len==0)
     717void NetMsg::encode (const NetMsg& m, uint32 len, bool move)
     718{
     719  if (len == 0)
    643720    return;
    644   if ((pos+(len-1))<=buf_end) {
    645     memmove(pos,m.buf,len);
    646     if (move) pos+=len;
    647   } else throw NetMsgError(NetMsgError::ERROR_INVALID_POS);
     721  if ( (pos + (len - 1)) <= buf_end)
     722  {
     723    memmove (pos, m.buf, len);
     724    if (move) pos += len;
     725  }
     726  else throw NetMsgError (NetMsgError::ERROR_INVALID_POS);
    648727} // end encode NetMsg
    649728
     
    652731 * if startpos is 0, the beginning of the buffer is used
    653732 */
    654 ostream& 
    655 NetMsg::hexdump(ostream& os, uchar *startpos, uint32 length) const
    656 {
    657   if (length==0)
    658     length=buf_len;
     733ostream&
     734NetMsg::hexdump (ostream& os, uchar* startpos, uint32 length) const
     735{
     736  if (length == 0)
     737    length = buf_len;
    659738
    660739  if (startpos == 0)
    661     startpos= buf;
     740    startpos = buf;
    662741
    663742  ios_base::fmtflags flags = os.flags();        // save stream flags
    664743
    665   os << color[blue] << "[dump: start=" << static_cast<void *>(startpos) << ", length:" << length;
     744  os << color[blue] << "[dump: start=" << static_cast<void*> (startpos) << ", length:" << length;
    666745  if (startpos > buf_end)
    667746    return os << "ERROR: start position behind last buffer byte ]" << color[clear] << endl;
    668   else
    669   if (startpos < buf)
     747  else if (startpos < buf)
    670748    return os << "ERROR: start position before first buffer byte ]" << color[clear] << endl;
    671749
    672750  os << endl;
    673  
    674   while ( length > 0 && startpos <= buf_end )
    675   {
    676     os << setw(4) << startpos-buf << ": ";
     751
     752  while (length > 0 && startpos <= buf_end)
     753  {
     754    os << setw (4) << startpos - buf << ": ";
    677755
    678756    // alphanumeric characters are printed directly
    679     for (uint8 index=0; index <= 3; index++) {
    680         if ( startpos+index <= buf_end ) {
    681             uchar c = *(startpos+index);
    682             os << ( isalnum(c) ? static_cast<char>(c) : '.');
    683         }
    684         else
    685             os << ' ';
     757    for (uint8 index = 0; index <= 3; index++)
     758    {
     759      if (startpos + index <= buf_end)
     760      {
     761        uchar c = * (startpos + index);
     762        os << (isalnum (c) ? static_cast<char> (c) : '.');
     763      }
     764      else
     765        os << ' ';
    686766    }
    687767
     
    689769
    690770    // dump hex numbers
    691     for (uint8 index=0; index <= 3; index++) {
    692         if ( startpos+index <= buf_end )
    693             os << setw(2) << setfill('0')
    694                 << static_cast<unsigned short>(*(startpos+index)) << ' ';
    695         else
    696             os << "   ";
     771    for (uint8 index = 0; index <= 3; index++)
     772    {
     773      if (startpos + index <= buf_end)
     774        os << setw (2) << setfill ('0')
     775           << static_cast<unsigned short> (* (startpos + index)) << ' ';
     776      else
     777        os << "   ";
    697778    }
    698779
    699     os << setfill(' ') << "       ";
     780    os << setfill (' ') << "       ";
    700781
    701782    // print in base 2
    702     for (uint8 index=0; index <= 3 && (startpos+index <= buf_end); index++)
     783    for (uint8 index = 0; index <= 3 && (startpos + index <= buf_end); index++)
    703784    {
    704         unsigned short val = static_cast<unsigned short>(*(startpos+index));
    705 
    706         for (int i=7; i >= 0; i--)
    707             os << ((val >> i) & 1);
    708 
    709         os << ' ';
     785      unsigned short val = static_cast<unsigned short> (* (startpos + index));
     786
     787      for (int i = 7; i >= 0; i--)
     788        os << ( (val >> i) & 1);
     789
     790      os << ' ';
    710791    }
    711792
    712793    startpos += 4;
    713     length = ( length >= 4 ) ? length-4 : 0;
     794    length = (length >= 4) ? length - 4 : 0;
    714795
    715796    // reset formatting
    716     os.width(0);
    717     os << dec << setfill(' ') << endl;
    718   }
    719 
    720   os.setf(flags);               // reset stream flags
     797    os.width (0);
     798    os << dec << setfill (' ') << endl;
     799  }
     800
     801  os.setf (flags);              // reset stream flags
    721802
    722803  return os << ']' << color[clear] << endl;
    723804}
    724805
    725 ostream& operator<<(ostream& os, NetMsg& msg)
    726 { 
    727  
     806ostream& operator<< (ostream& os, NetMsg& msg)
     807{
     808
    728809  ostringstream hexdumpstr;
    729   msg.hexdump(hexdumpstr);
     810  msg.hexdump (hexdumpstr);
    730811  return os << hexdumpstr.str();
    731  
     812
    732813}
    733814
    734815
    735 TLP_list* NetMsg::get_TLP_list()
    736 {
    737     if (!tlp_list)
    738             tlp_list = new TLP_list();
    739 
    740     return tlp_list;
    741 
    742 
    743          
    744 const TLP_list* NetMsg::get_TLP_list() const
    745 
    746   return tlp_list; 
    747 
    748  
    749 void NetMsg::fill_tlp_list(uint32 pdu_start,
    750                            uint32 pdu_stop,
    751                            uint32 (*get_length_from_obj_header)(const uint8*),
    752                            uint16 (*get_type_from_obj_header)(const uint8*),
    753                            uint16 (*get_subtype_from_obj_header)(const uint8*),
    754                            bool clean_up_first)
    755 {
    756         if (clean_up_first) {
    757                 delete tlp_list;
    758                 tlp_list= new TLP_list;
    759         }
    760         else
    761         if (!tlp_list) tlp_list= new TLP_list;
    762        
    763         uint32 tmp_pos = pdu_start;
    764         while ( tmp_pos < pdu_stop ) {
    765                 uint8* tmp_adr = buf + tmp_pos;
    766                 tlp_list->insert(get_type_from_obj_header(tmp_adr),get_subtype_from_obj_header(tmp_adr),tmp_pos);
    767                 tmp_pos += get_length_from_obj_header(tmp_adr);
    768         }
    769 }
     816TLP_list* NetMsg::get_TLP_list()
     817{
     818  if (!tlp_list)
     819    tlp_list = new TLP_list();
     820
     821  return tlp_list;
     822}
     823
     824
     825const TLP_list* NetMsg::get_TLP_list() const
     826{
     827  return tlp_list;
     828}
     829
     830void NetMsg::fill_tlp_list (uint32 pdu_start,
     831                            uint32 pdu_stop,
     832                            uint32 (*get_length_from_obj_header) (const uint8*),
     833                            uint16 (*get_type_from_obj_header) (const uint8*),
     834                            uint16 (*get_subtype_from_obj_header) (const uint8*),
     835                            bool clean_up_first)
     836{
     837  if (clean_up_first)
     838  {
     839    delete tlp_list;
     840    tlp_list = new TLP_list;
     841  }
     842  else if (!tlp_list) tlp_list = new TLP_list;
     843
     844  uint32 tmp_pos = pdu_start;
     845  while (tmp_pos < pdu_stop)
     846  {
     847    uint8* tmp_adr = buf + tmp_pos;
     848    tlp_list->insert (get_type_from_obj_header (tmp_adr), get_subtype_from_obj_header (tmp_adr), tmp_pos);
     849    tmp_pos += get_length_from_obj_header (tmp_adr);
     850  }
     851}
    770852
    771853
  • protlib/trunk/src/protlib_types.cpp

    r6595 r6765  
    3939{
    4040  ios_base::fmtflags flags = os.flags();        // save stream flags
    41   os  << setw(8) << setfill('0') << hex << val.w32.w1 << '-'
     41  os  << setw(8) << setfill('0') << hex << val.w32.w4 << '-'
     42      << setw(8) << setfill('0') << hex << val.w32.w3 << '-'
    4243      << setw(8) << setfill('0') << hex << val.w32.w2 << '-'
    43       << setw(8) << setfill('0') << hex << val.w32.w3 << '-'
    44       << setw(8) << setfill('0') << hex << val.w32.w4;
     44      << setw(8) << setfill('0') << hex << val.w32.w1;
    4545
    4646  os.setf(flags);               // reset stream flags
  • protlib/trunk/src/readnl.cpp

    r6176 r6765  
    3333
    3434#include <iostream>
     35#include <unistd.h>
    3536
    3637#include "readnl.h"
  • protlib/trunk/src/setuid.cpp

    r2549 r6765  
    5656void setuid::init() {
    5757        if (is_init) {
    58           Log(ERROR_LOG,LOG_CRIT, "setuid", "Tried to initialize setuid although already initialized.");
     58          ERRCLog("setuid", "Tried to initialize setuid although already initialized.");
    5959        } else {
    6060                pthread_mutex_init(&mutex,NULL);
     
    8383                // turn off setuid
    8484                if (is_setuid) {
    85                   Log(INFO_LOG,LOG_CRIT, "setuid", "setuid::end() turn off setuid. Switching (maybe permamently) to " << real_userid << " " << real_username << " using setuid()");
    86                   ::setuid(real_userid);
     85                  ILog("setuid", "setuid::end() turn off setuid. Switching (maybe permamently) to " << real_userid << " " << real_username << " using setuid()");
     86                  if (::setuid(real_userid) < 0)
     87                  { // setuid failed, display error message
     88                          const uint8 error_msg_len= 255;
     89                          char error_msg[error_msg_len];
     90                          error_msg[0]='\0';
     91                          uint8 last_errno= errno;
     92                          if (strerror_r(last_errno, error_msg, error_msg_len-1)==0)
     93                                  ERRCLog("setuid", "setuid call failed:" << error_msg);
     94                          else
     95                                  ERRCLog("setuid", "setuid call failed: errno:" << errno << " " << error_msg);
     96                  }
     97
    8798                } // end if is_setuid
    8899        } else {
    89           Log(ERROR_LOG,LOG_CRIT, "setuid", "Tried to end setuid although not initialized.");
     100          ERRCLog("setuid", "Tried to end setuid although not initialized.");
    90101        } // end if is_init
    91102} // end end
     
    96107                        pthread_mutex_lock(&mutex); // install_cleanup_mutex_lock(&mutex);
    97108                        if (count==0) {
    98                           Log(INFO_LOG,LOG_CRIT, "setuid", "setuid::on(): setting euid to " << file_userid << " " << file_username);
     109                          ILog("setuid", "setuid::on(): setting euid to " << file_userid << " " << file_username);
    99110                          int status;
    100111                          #ifdef _POSIX_SAVED_IDS
     
    107118                                } else count++;
    108119                        } else {
    109                           Log(INFO_LOG,LOG_CRIT, "setuid", "setuid::on(): setuid already on");
     120                          ILog("setuid", "setuid::on(): setuid already on");
    110121                          count++;
    111122                        } // end if count
    112123                        pthread_mutex_unlock(&mutex); // uninstall_cleanup(1);
    113124                } else {
    114                   Log(ERROR_LOG,LOG_CRIT, "setuid", "Tried to use setuid although not initialized.");
     125                  ERRCLog("setuid", "Tried to use setuid although not initialized.");
    115126                } // end if is_init
    116127        } // end if is_setuid
  • protlib/trunk/src/threads.cpp

    r6282 r6765  
    66/// $HeadURL$
    77// ===========================================================
    8 //                     
     8//
    99// Copyright (C) 2005-2007, all rights reserved by
    1010// - Institute of Telematics, Universitaet Karlsruhe (TH)
     
    1212// More information and contact:
    1313// https://projekte.tm.uka.de/trac/NSIS
    14 //                     
     14//
    1515// This program is free software; you can redistribute it and/or modify
    1616// it under the terms of the GNU General Public License as published by
     
    3333
    3434
    35 namespace protlib {
    36    using namespace log;
     35namespace protlib
     36{
     37using namespace log;
    3738
    3839/** @addtogroup thread Threads
     
    4849
    4950/**
    50  * Initializes a ThreadParam object with a default wait time and a 
     51 * Initializes a ThreadParam object with a default wait time and a
    5152 * a thread (group) name string.
    5253 *
     
    5758 * @param maxc maximal number of threads
    5859 */
    59 ThreadParam::ThreadParam(uint32 wait, const char *n, uint32 minc, uint32 maxc)
    60                 : sleep_time(wait), name(n ? n : "UNKNOWN"),
    61                   min_count(minc), max_count(maxc) {
    62 
    63           assert( minc > 0 );
    64           assert( maxc >= minc );
     60ThreadParam::ThreadParam (uint32 wait, const char* n, uint32 minc, uint32 maxc)
     61  : sleep_time (wait), name (n ? n : "UNKNOWN"),
     62    min_count (minc), max_count (maxc)
     63{
     64
     65  assert (minc > 0);
     66  assert (maxc >= minc);
    6567}
    6668
     
    7375 * @param exp_allow if true, allow reception of expedited messages on the queue
    7476 */
    75 Thread::Thread(const ThreadParam &p, bool create_queue, bool exp_allow)
    76         : running_threads(0), started_threads(0), state(STATE_INIT), tparam(p),
    77           fq(create_queue ? new FastQueue(p.name.c_str(), exp_allow) : 0) {
    78 
    79         pthread_mutexattr_t mutex_attr;
    80 
    81         pthread_mutexattr_init(&mutex_attr);
     77Thread::Thread (const ThreadParam& p, bool create_queue, bool exp_allow)
     78  : running_threads (0), started_threads (0), state (STATE_INIT), tparam (p),
     79    fq (create_queue ? new FastQueue (p.name.c_str(), exp_allow) : 0)
     80{
     81
     82  pthread_mutexattr_t mutex_attr;
     83
     84  pthread_mutexattr_init (&mutex_attr);
    8285
    8386#ifdef _DEBUG
    84         pthread_mutexattr_settype(&mutex_attr,PTHREAD_MUTEX_ERRORCHECK);
     87  pthread_mutexattr_settype (&mutex_attr, PTHREAD_MUTEX_ERRORCHECK);
    8588#else
    86         pthread_mutexattr_settype(&mutex_attr,PTHREAD_MUTEX_NORMAL);
     89  pthread_mutexattr_settype (&mutex_attr, PTHREAD_MUTEX_NORMAL);
    8790#endif
    8891
    89         pthread_mutex_init(&mutex, &mutex_attr);
    90         pthread_cond_init(&cond,NULL);
    91 
    92         pthread_mutexattr_destroy(&mutex_attr);
     92  pthread_mutex_init (&mutex, &mutex_attr);
     93  pthread_cond_init (&cond, NULL);
     94
     95  pthread_mutexattr_destroy (&mutex_attr);
    9396}
    9497
     
    99102 * Currently throws an exception if there are still running threads.
    100103 */
    101 Thread::~Thread() {
    102         if ( get_running_threads() )
    103                 throw ThreadError(ThreadError::ERROR_STILL_RUNNING);
    104 
    105         delete fq; // delete queue, no-op if fq is NULL
    106 
    107         pthread_cond_destroy(&cond);
    108         pthread_mutex_destroy(&mutex);
     104Thread::~Thread()
     105{
     106  if (get_running_threads())
     107    throw ThreadError (ThreadError::ERROR_STILL_RUNNING);
     108
     109  delete fq; // delete queue, no-op if fq is NULL
     110
     111  pthread_cond_destroy (&cond);
     112  pthread_mutex_destroy (&mutex);
    109113}
    110114
     
    118122 * calls to lock() and unlock().
    119123 */
    120 void *Thread::start_processing() {
    121 
    122         lock();
    123 
    124         switch (state) {
    125                 case STATE_INIT:
    126                         state=STATE_RUN;
    127                         break;
    128                 case STATE_RUN:
    129                         break;
    130                 case STATE_STOP:
    131                 case STATE_ABORT:
    132                         unlock();
    133                         return NULL;
    134         }
    135 
    136         inc_running_threads();
    137         inc_started_threads();
    138 
    139         int thread_num = get_started_threads();
    140 
    141         unlock();
    142 
    143         /*
    144          * Catch exceptions for logging, but don't rethrow them as this would
    145          * lead to undefined behaviour (probably crashing the ThreadStarter).
    146          *
    147          * All exceptions should be handled in main_loop(), it is a programming
    148          * error if they are propagated up to this point!
    149          */
    150         try {
    151                 main_loop(thread_num);
    152         }
    153         catch ( ProtLibException &e ) {
    154                 ERRLog("Threads", "Unhandled ProtLibException in thread "
    155                         << tparam.name << ", num " << thread_num << ", error ["
    156                         << e.getstr() << ']');
    157         }
    158         catch ( bad_alloc & ) {
    159                 ERRLog("Threads", tparam.name << ", num " << thread_num
    160                         << ": [out of memory]");
    161         }
    162         catch ( ... ) {
    163                 ERRLog("Threads", "Unhandled non-ProtLibException in thread "
    164                         << tparam.name << ", num " << thread_num);
    165         }
    166 
    167         lock();
    168         dec_running_threads();
    169         unlock();
    170 
    171         return NULL;
     124void* Thread::start_processing()
     125{
     126
     127  lock();
     128
     129  switch (state)
     130  {
     131    case STATE_INIT:
     132      state = STATE_RUN;
     133      break;
     134    case STATE_RUN:
     135      break;
     136    case STATE_STOP:
     137    case STATE_ABORT:
     138      unlock();
     139      return NULL;
     140  }
     141
     142  inc_running_threads();
     143  inc_started_threads();
     144
     145  int thread_num = get_started_threads();
     146
     147  unlock();
     148
     149  /*
     150   * Catch exceptions for logging, but don't rethrow them as this would
     151   * lead to undefined behaviour (probably crashing the ThreadStarter).
     152   *
     153   * All exceptions should be handled in main_loop(), it is a programming
     154   * error if they are propagated up to this point!
     155   */
     156  try
     157  {
     158    main_loop (thread_num);
     159  }
     160  catch (ProtLibException& e)
     161  {
     162    ERRLog ("Threads", "Unhandled ProtLibException in thread "
     163            << tparam.name << ", num " << thread_num << ", error ["
     164            << e.getstr() << ']');
     165  }
     166  catch (bad_alloc&)
     167  {
     168    ERRLog ("Threads", tparam.name << ", num " << thread_num
     169            << ": [out of memory]");
     170  }
     171  catch (std::exception& e)
     172  {
     173    ERRLog ("Threads", "Unhandled std::exception in thread "
     174            << tparam.name << ", num " << thread_num << ", error ["
     175            << e.what() << ']');
     176  }
     177  catch (...)
     178  {
     179    ERRLog ("Threads", "Unhandled non-ProtLibException in thread "
     180            << tparam.name << ", num " << thread_num);
     181  }
     182
     183  lock();
     184  dec_running_threads();
     185  unlock();
     186
     187  return NULL;
    172188}
    173189
     
    181197 * @param do_lock if true the thread mutex is used
    182198 */
    183 void Thread::stop_processing(bool do_lock) {
    184 
    185         if ( do_lock )
    186                 lock();
    187 
    188         if (state==STATE_RUN) {
    189                 state = STATE_STOP;
    190                 // break any waiting condition at the queue
    191                 signal_cond();
    192         }
    193 
    194         if ( do_lock )
    195                 unlock();
    196 
    197         fq->signal_queue();
     199void Thread::stop_processing (bool do_lock)
     200{
     201
     202  if (do_lock)
     203    lock();
     204
     205  if (state == STATE_RUN)
     206  {
     207    state = STATE_STOP;
     208    // break any waiting condition at the queue
     209    signal_cond();
     210  }
     211
     212  if (do_lock)
     213    unlock();
     214
     215  fq->signal_queue();
    198216}
    199217
     
    204222 * @param do_lock if true the thread mutex is used
    205223 */
    206 void Thread::abort_processing(bool do_lock) {
    207         if ( do_lock )
    208                 lock();
    209 
    210         if ( state == STATE_RUN  ||  state == STATE_STOP ) {
    211                 state = STATE_ABORT;
    212 
    213                 // break any waiting condition at the queue
    214                 fq->signal_queue();
    215         }
    216 
    217         if ( do_lock )
    218                 unlock();
    219 
    220         signal_cond();
    221 }
    222 
    223 
    224 /**
    225  * Checks whether there is still a running thread.
    226  *
    227  */
    228 bool Thread::is_running() const {
    229         return get_running_threads() > 0;
     224void Thread::abort_processing (bool do_lock)
     225{
     226  if (do_lock)
     227    lock();
     228
     229  if (state == STATE_RUN  ||  state == STATE_STOP)
     230  {
     231    state = STATE_ABORT;
     232
     233    // break any waiting condition at the queue
     234    fq->signal_queue();
     235  }
     236
     237  if (do_lock)
     238    unlock();
     239
     240  signal_cond();
     241}
     242
     243
     244/**
     245 * Checks whether there is still a running thread.
     246 *
     247 */
     248bool Thread::is_running() const
     249{
     250  return get_running_threads() > 0;
    230251}
    231252
     
    238259 * @return 0, ETIMEDOUT or EINTR.
    239260 */
    240 int Thread::wait_cond(int32 sec, int32 nsec) {
    241         struct timeval tv;
    242         struct timespec ts;
    243 
    244         if ( sec < 0 )
    245                 sec = 0;
    246         if ( nsec < 0 )
    247                 nsec = 0;
    248 
    249         gettimeofday(&tv, NULL);
    250         ts.tv_sec = tv.tv_sec+sec;
    251         ts.tv_nsec = tv.tv_usec*1000+nsec;
    252 
    253         // TODO: This is weird.
    254         while ( ts.tv_nsec > 1000000000) {
    255                 ts.tv_sec++;
    256                 ts.tv_nsec -= 1000000000;
    257         }
    258 
    259         if ( ts.tv_sec < 0 )
    260                 ts.tv_sec = 0;
    261         if ( ts.tv_nsec < 0 )
    262                 ts.tv_nsec = 0;
    263 
    264         return pthread_cond_timedwait(&cond, &mutex, &ts);
     261int Thread::wait_cond (int32 sec, int32 nsec)
     262{
     263  struct timeval tv;
     264  struct timespec ts;
     265
     266  if (sec < 0)
     267    sec = 0;
     268  if (nsec < 0)
     269    nsec = 0;
     270
     271  gettimeofday (&tv, NULL);
     272  ts.tv_sec = tv.tv_sec + sec;
     273  ts.tv_nsec = tv.tv_usec * 1000 + nsec;
     274
     275  // TODO: This is weird.
     276  while (ts.tv_nsec > 1000000000)
     277  {
     278    ts.tv_sec++;
     279    ts.tv_nsec -= 1000000000;
     280  }
     281
     282  if (ts.tv_sec < 0)
     283    ts.tv_sec = 0;
     284  if (ts.tv_nsec < 0)
     285    ts.tv_nsec = 0;
     286
     287  return pthread_cond_timedwait (&cond, &mutex, &ts);
    265288}
    266289
     
    274297 * @see enum state_t for more information on what a thread state is.
    275298 */
    276 Thread::state_t Thread::get_state(bool do_lock) {
    277         if ( do_lock )
    278                 lock();
    279 
    280         state_t s = state;
    281 
    282         if ( do_lock )
    283                 unlock();
    284 
    285         return s;
     299Thread::state_t Thread::get_state (bool do_lock)
     300{
     301  if (do_lock)
     302    lock();
     303
     304  state_t s = state;
     305
     306  if (do_lock)
     307    unlock();
     308
     309  return s;
    286310}
    287311
    288312/// get time of day as timespec
    289 void Thread::get_time_of_day(struct timespec& ts) {
    290         struct timeval tv;
    291         gettimeofday(&tv,NULL);
    292         ts.tv_sec = tv.tv_sec;
    293         ts.tv_nsec = tv.tv_usec*1000;
    294 }
    295 
    296 const char* ThreadError::getstr() const {
    297         return errstr[(int)err];
    298 }
    299 
    300 const char* const ThreadError::errstr[] = {
    301         "Cannot create POSIX Threads.",
    302         "Thread is running.",
    303         "Thread is going to stop.",
    304         "Thread is aborting.",
    305         "Still running threads left.",
    306         "ThreadStarter is not initialized correctly."
    307         "Internal ThreadStarter or Thread error.",
    308         "Thread has not been started yet."
     313void Thread::get_time_of_day (struct timespec& ts)
     314{
     315  struct timeval tv;
     316  gettimeofday (&tv, NULL);
     317  ts.tv_sec = tv.tv_sec;
     318  ts.tv_nsec = tv.tv_usec * 1000;
     319}
     320
     321const char* ThreadError::getstr() const
     322{
     323  return errstr[ (int) err];
     324}
     325
     326const char* const ThreadError::errstr[] =
     327{
     328  "Cannot create POSIX Threads.",
     329  "Thread is running.",
     330  "Thread is going to stop.",
     331  "Thread is aborting.",
     332  "Still running threads left.",
     333  "ThreadStarter is not initialized correctly."
     334  "Internal ThreadStarter or Thread error.",
     335  "Thread has not been started yet."
    309336};
    310337
  • protlib/trunk/src/tp_over_tcp.cpp

    r6694 r6765  
    66/// $HeadURL$
    77// ===========================================================
    8 //                     
     8//
    99// Copyright (C) 2005-2012, all rights reserved by
    1010// - Institute of Telematics, Karlsruhe Institute of Technology (KIT)
     
    1212// More information and contact:
    1313// https://svn.tm.kit.edu/trac/NSIS
    14 //                     
     14//
    1515// This program is free software; you can redistribute it and/or modify
    1616// it under the terms of the GNU General Public License as published by
     
    2727//
    2828// ===========================================================
    29  
     29
    3030extern "C"
    3131{
     
    7979    TP(tsdb::get_tcp_id(),"tcp",p.name,p.common_header_length,p.getmsglength),
    8080    Thread(p), tpparam(p), already_aborted(false), msgqueue(NULL), master_listener_is_up(false), debug_pdu(p.debug_pdu)
    81 { 
     81{
    8282    // perform some initializing actions
    8383    init= true; ///< init done;
     
    8585
    8686
    87 /** get_connection_to() checks for already existing connections. 
    88  *  If a connection exists, it returns "AssocData" 
     87/** get_connection_to() checks for already existing connections.
     88 *  If a connection exists, it returns "AssocData"
    8989 *  and saves it in "connmap" for further use
    9090 *  If no connection exists, a new connection to "addr"
    9191 *  is created.
    9292 */
    93 AssocData* 
     93AssocData*
    9494TPoverTCP::get_connection_to(const appladdress& addr)
    9595{
     
    108108  int new_socket;
    109109  // loop until timeout is exceeded: TODO: check applicability of loop
    110   do 
     110  do
    111111  {
    112112    // check for existing connections to addr
     
    116116    // end critical section
    117117    unlock(); // uninstall_cleanup(1);
    118     if (assoc) 
     118    if (assoc)
    119119    {
    120120      // If not shut down then use it, else abort, wait and check again.
    121       if (!assoc->shutdown) 
     121      if (!assoc->shutdown)
    122122      {
    123123        return assoc;
     
    129129
    130130        return 0;
    131       } 
     131      }
    132132    } //end __if (assoc)__
    133     else 
    134     {
    135       Log(DEBUG_LOG,LOG_UNIMP,tpparam.name,"No existing connection to " 
     133    else
     134    {
     135      Log(DEBUG_LOG,LOG_UNIMP,tpparam.name,"No existing connection to "
    136136          << addr.get_ip_str() << " port #" << addr.get_port() << " found, creating a new one.");
    137137    }
    138138
    139139    // no connection found, create a new one
    140    
     140
    141141    // check whether master listener socket is up, this is important if we connect to ourselves
    142142    // otherwise we connect, but no socket is listening
     
    166166        ERRLog(tpparam.name, "Could not set socket option TCP_NODELAY:" << strerror(errno));
    167167    }
    168    
     168
    169169    // Reuse ports, even if they are busy
    170170    int socketreuseflag= 1;
     
    183183    dest_address.sin6_scope_id= 0;
    184184    addr.get_sockaddr(dest_address);
    185    
     185
    186186    struct sockaddr_in dest_address_v4;
    187187    if (plibconf.getpar<bool>(protlibconf_ipv4_only))
     
    189189            addr.get_sockaddr(dest_address_v4);
    190190    }
    191  
     191
    192192    // connect the socket to the destination address
    193    
     193
    194194    int connect_status = 0;
    195195
     
    207207    }
    208208
    209     // connects to the listening_port of the peer's masterthread   
     209    // connects to the listening_port of the peer's masterthread
    210210    if (connect_status != 0)
    211211    {
    212       ERRLog(tpparam.name,"Connect to " << addr.get_ip_str() << " port #" << addr.get_port() 
     212      ERRLog(tpparam.name,"Connect to " << addr.get_ip_str() << " port #" << addr.get_port()
    213213          << " failed: [" << color[red] << strerror(errno) << color[off] << "]");
    214214      // free resources
     
    221221    }
    222222
    223    
     223
    224224    struct sockaddr_in6 own_address;
    225225    struct sockaddr_in own_address_v4;
     
    230230    else
    231231            getsockname(new_socket, reinterpret_cast<struct sockaddr*>(&own_address), &own_address_len);
    232    
    233 
    234    
    235     DLog(tpparam.name,">>--Connect-->> to " << addr.get_ip_str() << " port #" << addr.get_port() 
    236          << " from " <<  ( plibconf.getpar<bool>(protlibconf_ipv4_only) ? 
    237                                                  inet_ntop(AF_INET,&own_address_v4.sin_addr,in6_addrstr,INET_ADDRSTRLEN) : 
     232
     233
     234
     235    DLog(tpparam.name,">>--Connect-->> to " << addr.get_ip_str() << " port #" << addr.get_port()
     236         << " from " <<  ( plibconf.getpar<bool>(protlibconf_ipv4_only) ?
     237                                                 inet_ntop(AF_INET,&own_address_v4.sin_addr,in6_addrstr,INET_ADDRSTRLEN) :
    238238                                                 inet_ntop(AF_INET6,&own_address.sin6_addr,in6_addrstr,INET6_ADDRSTRLEN) )
    239239         << " port #" << (plibconf.getpar<bool>(protlibconf_ipv4_only) ? ntohs(own_address_v4.sin_port) : ntohs(own_address.sin6_port)));
    240240
    241241    // create new AssocData record (will copy addr)
    242     assoc = new(nothrow) AssocData(new_socket, addr, 
    243                                    plibconf.getpar<bool>(protlibconf_ipv4_only) ? 
     242    assoc = new(nothrow) AssocData(new_socket, addr,
     243                                   plibconf.getpar<bool>(protlibconf_ipv4_only) ?
    244244                                   appladdress(own_address_v4,IPPROTO_TCP) : appladdress(own_address,IPPROTO_TCP) );
    245245
    246246    // if assoc could be successfully created, insert it into ConnectionMap
    247     if (assoc) 
     247    if (assoc)
    248248    {
    249249      bool insert_success= false;
     
    255255      unlock(); // uninstall_cleanup(1);
    256256
    257       if (insert_success == true) 
     257      if (insert_success == true)
    258258      {
    259259#ifdef _DEBUG
     
    261261            << " via socket " << new_socket);
    262262
    263                
     263
    264264#endif
    265265
     
    278278        else
    279279          ERRCLog(tpparam.name,"get_connection_to: could not get memory for internal msg");
    280       } 
    281       else 
     280      }
     281      else
    282282      {
    283283        // delete data and abort
    284284        ERRCLog(tpparam.name, "Cannot insert AssocData for socket " << new_socket << ", "<< addr.get_ip_str()
    285285            <<", port #" << addr.get_port() << " into connection map, aborting connection");
    286                
     286
    287287        // abort connection, delete its AssocData
    288288        close (new_socket);
    289         if (assoc) 
    290         { 
    291           delete assoc; 
     289        if (assoc)
     290        {
     291          delete assoc;
    292292          assoc= 0;
    293293        }
    294294        return assoc;
    295       } // end else connmap.insert                     
    296      
     295      } // end else connmap.insert
     296
    297297    } // end "if (assoc)"
    298   } 
     298  }
    299299  while (wait_cond(ts)!=ETIMEDOUT);
    300300
     
    321321 addr->convert_to_ipv6();
    322322
    323   // Create a new AssocData-pointer 
     323  // Create a new AssocData-pointer
    324324  AssocData* assoc = NULL;
    325325
     
    332332  lock(); // install_cleanup_thread_lock(TPoverTCP, this);
    333333  assoc= connmap.lookup(*addr);
    334   if (assoc) 
     334  if (assoc)
    335335  {
    336336    // stop receiver thread first, because assoc is still used there
     
    339339    EVLog(tpparam.name,thisproc<<"got request to shutdown connection for peer " << addr);
    340340    // If not shut down then use it, else abort, wait and check again.
    341     if (!assoc->shutdown) 
     341    if (!assoc->shutdown)
    342342    {
    343343      if (assoc->socketfd)
     
    350350        else
    351351        {
    352           EVLog(tpparam.name,thisproc<<"initiated closing of connection for peer " << addr << ". Shutdown (write) on socket "<< assoc->socketfd );       
     352          EVLog(tpparam.name,thisproc<<"initiated closing of connection for peer " << addr << ". Shutdown (write) on socket "<< assoc->socketfd );
    353353        }
    354354      }
     
    357357    else
    358358      EVLog(tpparam.name,thisproc<<"connection for peer " << addr << " is already in mode shutdown");
    359      
     359
    360360  }
    361361  else
     
    392392  appladdress* addr = NULL;
    393393  addr= dynamic_cast<appladdress*>(in_addr.copy());
    394    
     394
    395395  if (!addr)
    396396  {
    397397    ERRCLog(tpparam.name,"send() - given destination address is not of expected type (appladdress), has type " << (int) in_addr.get_type());
    398398    return;
    399   } 
     399  }
    400400  addr->convert_to_ipv6();
    401401
    402402  // lock due to sendermap access
    403403  lock();
    404    
     404
    405405  // check for existing sender thread
    406406  sender_thread_queuemap_t::const_iterator it= senderthread_queuemap.find(*addr);
    407    
     407
    408408  FastQueue* destqueue= 0;
    409409
     
    424424      create_new_sender_thread(sender_thread_queue);
    425425      // remember queue for later use
    426      
     426
    427427      //pair<sender_thread_queuemap_t::iterator, bool> tmpinsiterator=
    428428      senderthread_queuemap.insert( pair<appladdress,FastQueue*> (*addr,sender_thread_queue) );
    429      
     429
    430430      destqueue= sender_thread_queue;
    431431    }
     
    433433  else
    434434  { // we have a sender thread, use stored queue from map
    435     destqueue= it->second; 
    436   }
    437    
     435    destqueue= it->second;
     436  }
     437
    438438  unlock();
    439    
     439
    440440  // send a send_data message to it (if we have a destination queue)
    441441  if (destqueue)
    442442  {
    443443    // both parameters will be freed after message was sent!
    444    
     444
    445445    TPoverTCPMsg* internalmsg= new TPoverTCPMsg(netmsg, addr->copy(), message::qaddr_unknown, sentcallbackfunc);
    446446    if (internalmsg)
    447     { 
     447    {
    448448      // send the internal message to the sender thread queue
    449449      if ( internalmsg->send(tpparam.source,destqueue) == false )
     
    467467    delete netmsg;
    468468  }
    469  
     469
    470470  if (addr) delete addr;
    471471}
     
    477477 * @param addr   transport endpoint address
    478478 *
    479  * @note   if no connection exists, creates a new one 
     479 * @note   if no connection exists, creates a new one
    480480 * @note   both parameters are deleted after the message was sent
    481481 */
    482482void
    483483TPoverTCP::tcpsend(NetMsg* netmsg, appladdress* addr, TPsentcallback_t sentcallbackfunc)
    484 {                       
     484{
    485485#ifndef _NO_LOGGING
    486486  const char *const thisproc="sender   - ";
     
    493493  int ret= 0;
    494494
    495   // Create a new AssocData-pointer 
     495  // Create a new AssocData-pointer
    496496  AssocData* assoc = NULL;
    497  
     497
    498498  // tp.cpp checks for initialisation of tp and correctness of
    499499  // msgsize, protocol and ip,
     
    503503    addr->convert_to_ipv6();
    504504    check_send_args(*netmsg,*addr);
    505   } 
    506   else 
     505  }
     506  else
    507507  {
    508508    ERRCLog(tpparam.name, thisproc << "address pointer is NULL");
     
    514514    throw TPErrorInternal();
    515515  }
    516          
    517   // check for existing connections, 
    518   // if a connection exists, return its AssocData 
     516
     517  // check for existing connections,
     518  // if a connection exists, return its AssocData
    519519  // and save it in assoc for further use
    520520  // if no connection exists, create a new one (in get_connection_to()).
     
    558558    for (uint32 i=0;i<msgsize;i++)
    559559    {
    560       cout << "send_buf: " << i << " : "; 
     560      cout << "send_buf: " << i << " : ";
    561561      if ( isalnum(*(netmsg->get_buffer()+i)) )
    562562        cout << "'" << *(netmsg->get_buffer()+i) << "' (0x" << hex << (unsigned short) *(netmsg->get_buffer()+i) << dec << ")" ;
     
    575575
    576576    retry_count= 0;
    577     do 
     577    do
    578578    {
    579579      // socket send
    580       ret= ::send(assoc->socketfd, 
    581                   netmsg->get_buffer() + bytes_sent, 
    582                   msgsize - bytes_sent, 
     580      ret= ::send(assoc->socketfd,
     581                  netmsg->get_buffer() + bytes_sent,
     582                  msgsize - bytes_sent,
    583583                  MSG_NOSIGNAL);
    584      
     584
    585585      // send_buf + bytes_sent
    586586
     
    596596          case ENOBUFS: //  The output queue for a network interface was full.
    597597            retry_count++;
    598             ERRLog(tpparam.name,"Temporary failure while calling send(): " << strerror(saved_errno) << ", errno: " << saved_errno 
     598            ERRLog(tpparam.name,"Temporary failure while calling send(): " << strerror(saved_errno) << ", errno: " << saved_errno
    599599                   << " - retry sending, retry #" << retry_count);
    600600            // pace down a little bit, sleep for a while
     
    602602            break;
    603603
    604             // everything else should not lead to repetition 
     604            // everything else should not lead to repetition
    605605          default:
    606606            retry_count= retry_send_max;
     
    610610      else // leave while
    611611        break;
    612     } 
     612    }
    613613    while(retry_count < retry_send_max);
    614614
    615     if (ret < 0) 
     615    if (ret < 0)
    616616    { // unrecoverable error occured
    617      
     617
    618618      result= TCP_SEND_FAILURE;
    619619      break;
     
    634634  // *** note: netmsg is deleted here ***
    635635  delete netmsg;
    636  
    637   // Throwing an exception within a critical section does not 
     636
     637  // Throwing an exception within a critical section does not
    638638  // unlock the mutex.
    639639
     
    644644
    645645    throw TPErrorSendFailed(saved_errno);
    646    
     646
    647647  }
    648648  else
     
    651651    // note that this is no confirmation that the message arrived at the remote side, it is just intended to be
    652652    // use for flow control feeback
    653     if ( sentcallbackfunc ) 
     653    if ( sentcallbackfunc )
    654654      (*sentcallbackfunc)(true);
    655655
     
    659659  if (!assoc) {
    660660    // no connection
    661    
    662     ERRLog(tpparam.name, thisproc << "cannot get connection to " << addr->get_ip_str() 
     661
     662    ERRLog(tpparam.name, thisproc << "cannot get connection to " << addr->get_ip_str()
    663663        << ", port #" << addr->get_port());
    664664
     
    667667    throw TPErrorUnreachable(); // should be no assoc found
    668668  } // end "if (!assoc)"
    669  
     669
    670670  // *** delete address ***
    671671  delete addr;
     
    678678 * @param argp points to the thread queue for internal messages
    679679 */
    680 void 
     680void
    681681TPoverTCP::sender_thread(void *argp)
    682682{
     
    701701  {
    702702    internalmsg= dynamic_cast<TPoverTCPMsg*>(internal_thread_msg);
    703    
     703
    704704    if (internalmsg == 0)
    705705    {
     
    712712      if (internalmsg->get_netmsg() && internalmsg->get_appladdr())
    713713      {
    714         try 
     714        try
    715715        {
    716716                // send the NetMsg via TCP, address object is deleted inside tcpsend()
     
    719719        catch(TPErrorSendFailed& err)
    720720        {
    721           ERRLog(tpparam.name, methodname << "TCP send call failed - " << err.what() 
     721          ERRLog(tpparam.name, methodname << "TCP send call failed - " << err.what()
    722722                 << " cause: (" << err.get_reason() << ") " << strerror(err.get_reason()) );
    723723        } // end catch
     
    734734      {
    735735        ERRLog(tpparam.name, methodname << "problem with passed arguments references, they point to 0");
    736       } 
     736      }
    737737    }
    738738    else
     
    740740    {
    741741      terminate= true;
    742     } 
     742    }
    743743
    744744    delete internalmsg;
    745745  } // end while
    746  
     746
    747747  EVLog(tpparam.name, methodname << "<" << pthread_self() << "> terminated connection.");
    748748}
    749749
    750750
    751 /** receiver thread listens at a TCP socket for incoming PDUs 
     751/** receiver thread listens at a TCP socket for incoming PDUs
    752752 *  and passes complete PDUs to the coordinator. Incomplete
    753753 *  PDUs due to aborted connections or buffer overflows are discarded.
    754754 *  @param argp - assoc data and flags sig_terminate and terminated
    755  * 
     755 *
    756756 *  @note this is a static member function, so you cannot use class variables
    757757 */
    758 void 
     758void
    759759TPoverTCP::receiver_thread(void *argp)
    760760{
     
    768768  uint32 bytes_received = 0;
    769769  TPMsg* tpmsg= NULL;
    770  
     770
    771771  // argument parsing - start
    772772  if (receiver_thread_argp == 0)
     
    798798  {
    799799    ERRCLog(tpparam.name, methodname << "No peer assoc available - pointer is NULL");
    800    
     800
    801801    return;
    802802  }
     
    805805  {
    806806    ERRCLog(tpparam.name, methodname << "No peer address available for socket " << conn_socket << ", exiting.");
    807    
     807
    808808    return;
    809809  }
     
    811811#ifdef _DEBUG
    812812  Log(DEBUG_LOG,LOG_UNIMP, tpparam.name, methodname <<
    813       "Preparing to wait for data at socket " 
     813      "Preparing to wait for data at socket "
    814814      << conn_socket << " from " << receiver_thread_argp->peer_assoc->peer);
    815815#endif
     
    820820  bool pdu_complete= false; // when to terminate inner loop
    821821
    822   /* maybe use this to create a new pdu, 
     822  /* maybe use this to create a new pdu,
    823823    /// constructor
    824824    contextlistpdu(type_t t, subtype_t st, uint32 fc, uint32 numobj = 0);
    825   */ 
     825  */
    826826
    827827  // activate O_NON_BLOCK  for recv on socket conn_socket
    828828  // CAVEAT: this also implies non-blocking send()!
    829829  //fcntl(conn_socket,F_SETFL, O_NONBLOCK);
    830    
     830
    831831  // set options for polling
    832   const unsigned int number_poll_sockets= 1; 
     832  const unsigned int number_poll_sockets= 1;
    833833  struct pollfd poll_fd;
    834834  // have to set structure before poll call
    835835  poll_fd.fd = conn_socket;
    836   poll_fd.events = POLLIN | POLLPRI; 
     836  poll_fd.events = POLLIN | POLLPRI;
    837837  poll_fd.revents = 0;
    838838
     
    845845  size_t trailingbytes= 0;
    846846  bool skiprecv= false;
    847   // loop until we receive a terminate signal (read-only var for this thread) 
     847  // loop until we receive a terminate signal (read-only var for this thread)
    848848  // or get an error from socket read
    849849  while( receiver_thread_argp->sig_terminate == false )
     
    879879      recv_error= true;
    880880    }
    881    
     881
    882882    // loops until PDU is complete
    883883    // >>>>>>>>>>>>>>>>>>>>>>>>>>> while >>>>>>>>>>>>>>>>>>>>>>>>
    884     while (!pdu_complete && 
    885            !recv_error && 
     884    while (!pdu_complete &&
     885           !recv_error &&
    886886           !receiver_thread_argp->sig_terminate)
    887887    {
     
    890890        // read from TCP socket or return after sleep_time
    891891        poll_status= poll(&poll_fd, number_poll_sockets, tpparam.sleep_time);
    892        
     892
    893893        if (receiver_thread_argp->sig_terminate)
    894894        {
     
    924924          }
    925925        }
    926        
    927         if (poll_fd.revents & POLLHUP) // Hung up 
     926
     927        if (poll_fd.revents & POLLHUP) // Hung up
    928928        {
    929929          Log(EVENT_LOG,LOG_CRIT, tpparam.name, methodname << "Poll hung up");
    930930          recv_error= true;
    931931        }
    932        
     932
    933933        if (poll_fd.revents & POLLNVAL) // Invalid request: fd not open
    934934        {
     
    936936          recv_error= true;
    937937        }
    938        
     938
    939939        // check status (return value) of poll call
    940940        switch (poll_status)
     
    950950              recv_error= true;
    951951            }
    952            
     952
    953953            continue; // next while iteration
    954954            break;
    955            
     955
    956956          case 0:
    957957#ifdef DEBUG_HARD
     
    960960            continue; // next while iteration
    961961            break;
    962            
     962
    963963          default:
    964964#ifdef DEBUG_HARD
     
    970970
    971971        /// receive data from socket buffer (recv will not block)
    972         ret = recv(conn_socket, 
    973                    netmsg->get_buffer() + bytes_received, 
    974                    buffer_bytes_left, 
     972        ret = recv(conn_socket,
     973                   netmsg->get_buffer() + bytes_received,
     974                   buffer_bytes_left,
    975975                   MSG_DONTWAIT);
    976976
     
    10231023          }
    10241024        }
    1025       } // end if do not skip recv() statement     
     1025      } // end if do not skip recv() statement
    10261026
    10271027      if (buffer_bytes_left < 0) ///< buffer space exhausted now
     
    11151115      if (!tpmsg
    11161116          || (!tpmsg->get_peeraddress())
    1117           || (!tpmsg->send(message::qaddr_tp_over_tcp, tpparam.dest))) 
     1117          || (!tpmsg->send(message::qaddr_tp_over_tcp, tpparam.dest)))
    11181118      {
    11191119        ERRLog(tpparam.name, methodname << "Cannot allocate/send TPMsg");
     
    11511151  } // end while (thread not signalled for termination)
    11521152
    1153   DLog(tpparam.name, methodname << "Thread <" << pthread_self() 
     1153  DLog(tpparam.name, methodname << "Thread <" << pthread_self()
    11541154      << "> shutting down and closing socket " << receiver_thread_argp->peer_assoc->peer);
    11551155
     
    11791179  newmsg->send_to(tpparam.source);
    11801180
    1181 } 
     1181}
    11821182
    11831183
    11841184/** this signals a terminate to a thread and wait for the thread to stop
    11851185 *  @note it is not safe to access any thread related data after this method returned,
    1186  *        because the receiver thread will initiate a cleanup_receiver_thread() method 
     1186 *        because the receiver thread will initiate a cleanup_receiver_thread() method
    11871187 *        which may erase all relevant thread data.
    11881188 */
    1189 void 
     1189void
    11901190TPoverTCP::stop_receiver_thread(AssocData* peer_assoc)
    11911191{
     
    11991199
    12001200  pthread_t thread_id=  peer_assoc->thread_ID;
    1201  
     1201
    12021202  // try to clean up receiver_thread_arg
    12031203  recv_thread_argmap_t::iterator recv_thread_arg_iter= recv_thread_argmap.find(thread_id);
    1204   receiver_thread_arg_t* recv_thread_argp= 
     1204  receiver_thread_arg_t* recv_thread_argp=
    12051205    (recv_thread_arg_iter != recv_thread_argmap.end()) ? recv_thread_arg_iter->second : 0;
    12061206  if (recv_thread_argp)
     
    12301230 *       is still valid
    12311231 */
    1232 void 
     1232void
    12331233TPoverTCP::cleanup_receiver_thread(AssocData* peer_assoc)
    12341234{
     
    12421242
    12431243  pthread_t thread_id=  peer_assoc->thread_ID;
    1244  
     1244
    12451245  // try to clean up receiver_thread_arg
    12461246  recv_thread_argmap_t::iterator recv_thread_arg_iter= recv_thread_argmap.find(thread_id);
    1247   receiver_thread_arg_t* recv_thread_argp= 
     1247  receiver_thread_arg_t* recv_thread_argp=
    12481248    (recv_thread_arg_iter != recv_thread_argmap.end()) ? recv_thread_arg_iter->second : 0;
    12491249  if (recv_thread_argp)
     
    12871287 *       is still valid, a lock is also required, because senderthread_queuemap is changed
    12881288 */
    1289 void 
     1289void
    12901290TPoverTCP::terminate_sender_thread(const AssocData* assoc)
    12911291{
     
    13001300  if (it != senderthread_queuemap.end())
    13011301  { // we have a sender thread: send a stop message to it
    1302     FastQueue* destqueue= it->second; 
     1302    FastQueue* destqueue= it->second;
    13031303    if (destqueue)
    13041304    {
     
    13231323 * main_loop()
    13241324 */
    1325 void 
     1325void
    13261326TPoverTCP::terminate_all_threads()
    13271327{
     
    13431343        // then wait for its termination
    13441344        DLog(tpparam.name, "Signaled receiver thread <" << terminate_iterator->first << "> for termination");
    1345        
     1345
    13461346        pthread_join(terminate_iterator->first, 0);
    1347        
     1347
    13481348        DLog(tpparam.name, "Thread <" << terminate_iterator->first  << "> is terminated");
    13491349      }
    13501350      else
    13511351        DLog(tpparam.name, "Receiver thread <" << terminate_iterator->first << "> already terminated");
    1352        
     1352
    13531353      // cleanup all remaining argument structures of terminated threads
    13541354      delete terminate_argp;
     
    13561356      // terminate any related sender thread that is still running
    13571357      terminate_sender_thread(assoc);
    1358      
     1358
    13591359      connmap.erase(assoc);
    13601360      // delete assoc is not necessary, because connmap.erase() will do the job
     
    13651365
    13661366/**
    1367  * sender thread starter: 
    1368  * just a static starter method to allow starting the 
     1367 * sender thread starter:
     1368 * just a static starter method to allow starting the
    13691369 * actual sender_thread() method.
    13701370 *
     
    13751375{
    13761376  sender_thread_start_arg_t *sargp= static_cast<sender_thread_start_arg_t *>(argp);
    1377  
     1377
    13781378  //cout << "invoked sender_thread_Starter" << endl;
    13791379
     
    14001400
    14011401/**
    1402  * receiver thread starter: 
    1403  * just a static starter method to allow starting the 
     1402 * receiver thread starter:
     1403 * just a static starter method to allow starting the
    14041404 * actual receiver_thread() method.
    14051405 *
     
    14341434  pthread_t senderthreadid;
    14351435  // create new thread; (arg == 0) is handled by thread, too
    1436   int pthread_status= pthread_create(&senderthreadid, 
    1437                                      NULL, // NULL: default attributes: thread is joinable and has a 
     1436  int pthread_status= pthread_create(&senderthreadid,
     1437                                     NULL, // NULL: default attributes: thread is joinable and has a
    14381438                                     //       default, non-realtime scheduling policy
    14391439                                     TPoverTCP::sender_thread_starter,
     
    14421442  {
    14431443    Log(ERROR_LOG,LOG_CRIT, tpparam.name, "A new thread could not be created: " <<  strerror(pthread_status));
    1444    
     1444
    14451445    delete senderfqueue;
    14461446  }
     
    14511451TPoverTCP::create_new_receiver_thread(AssocData* peer_assoc)
    14521452{
    1453   receiver_thread_arg_t* argp= 
     1453  receiver_thread_arg_t* argp=
    14541454    new(nothrow) receiver_thread_arg(peer_assoc);
    1455  
     1455
    14561456  Log(EVENT_LOG,LOG_NORMAL, tpparam.name, "Starting new receiver thread...");
    14571457
    14581458  // create new thread; (arg == 0) is handled by thread, too
    1459   int pthread_status= pthread_create(&peer_assoc->thread_ID, 
    1460                                      NULL, // NULL: default attributes: thread is joinable and has a 
     1459  int pthread_status= pthread_create(&peer_assoc->thread_ID,
     1460                                     NULL, // NULL: default attributes: thread is joinable and has a
    14611461                                     //       default, non-realtime scheduling policy
    14621462                                     receiver_thread_starter,
     
    14651465  {
    14661466    Log(ERROR_LOG,LOG_CRIT, tpparam.name, "A new thread could not be created: " <<  strerror(pthread_status));
    1467    
     1467
    14681468    delete argp;
    14691469  }
     
    14811481    }
    14821482    unlock(); // uninstall_cleanup(1);
    1483   } 
     1483  }
    14841484}
    14851485
    14861486
    14871487/**
    1488  * master listener thread starter: 
    1489  * just a static starter method to allow starting the 
     1488 * master listener thread starter:
     1489 * just a static starter method to allow starting the
    14901490 * actual master_listener_thread() method.
    14911491 *
     
    15081508 * master listener thread: waits for incoming connections at the well-known tcp port
    15091509 * when a connection request is received this thread spawns a receiver_thread for
    1510  * receiving packets from the peer at the new socket. 
     1510 * receiving packets from the peer at the new socket.
    15111511 */
    15121512void
     
    15181518  own_address.sin6_flowinfo= 0;
    15191519  own_address.sin6_port = htons(tpparam.port); // use port number in param structure
    1520   // accept incoming connections on all interfaces 
     1520  // accept incoming connections on all interfaces
    15211521  own_address.sin6_addr = in6addr_any;
    15221522  own_address.sin6_scope_id= 0;
     
    15251525  own_address_v4.sin_port = htons(tpparam.port); // use port number in param structure
    15261526  own_address_v4.sin_addr.s_addr = INADDR_ANY;
    1527  
     1527
    15281528  // create a listening socket
    15291529  int master_listener_socket= -1;
     
    15381538    return;
    15391539  }
    1540  
     1540
    15411541  // Disable Nagle Algorithm, set (TCP_NODELAY)
    15421542  int nodelayflag= 1;
     
    15501550    ERRLog(tpparam.name, "Could not set socket option TCP_NODELAY:" << strerror(errno));
    15511551  }
    1552  
     1552
    15531553  // Reuse ports, even if they are busy
    15541554  int socketreuseflag= 1;
     
    15621562      ERRLog(tpparam.name, "Could not set socket option SO_REUSEADDR:" << strerror(errno));
    15631563  }
    1564  
    1565  
     1564
     1565
    15661566  // bind the newly created socket to a specific address
    15671567  struct sockaddr* ownsockaddr= plibconf.getpar<bool>(protlibconf_ipv4_only) ?
     
    15711571          sizeof(own_address_v4) : sizeof(own_address);
    15721572
    1573   int bind_status = bind(master_listener_socket,
     1573  int bind_status = ::bind(master_listener_socket,
    15741574                         ownsockaddr,
    15751575                         ownsockaddr_len);
    15761576  if (bind_status)
    1577     { 
    1578       ERRCLog(tpparam.name, "Binding to " 
     1577    {
     1578      ERRCLog(tpparam.name, "Binding to "
    15791579              << (plibconf.getpar<bool>(protlibconf_ipv4_only) ? inet_ntop(AF_INET, &own_address_v4.sin_addr, in6_addrstr, INET6_ADDRSTRLEN) :
    15801580                  inet_ntop(AF_INET6, &own_address.sin6_addr, in6_addrstr, INET6_ADDRSTRLEN))
     
    15831583    }
    15841584
    1585     // listen at the socket, 
     1585    // listen at the socket,
    15861586    // queuesize for pending connections= max_listen_queue_size
    15871587    int listen_status = listen(master_listener_socket, max_listen_queue_size);
    15881588    if (listen_status)
    15891589    {
    1590       ERRCLog(tpparam.name, "Listen at socket " << master_listener_socket 
     1590      ERRCLog(tpparam.name, "Listen at socket " << master_listener_socket
    15911591          << " failed, error: " << strerror(errno));
    15921592      return;
     
    16031603    struct pollfd poll_fd;
    16041604    poll_fd.fd = master_listener_socket;
    1605     poll_fd.events = POLLIN | POLLPRI; 
     1605    poll_fd.events = POLLIN | POLLPRI;
    16061606    poll_fd.revents = 0;
    16071607    /*
    1608       #define POLLIN    0x001   // There is data to read. 
    1609       #define POLLPRI   0x002   // There is urgent data to read. 
    1610       #define POLLOUT   0x004   // Writing now will not block. 
     1608      #define POLLIN    0x001   // There is data to read.
     1609      #define POLLPRI   0x002   // There is urgent data to read.
     1610      #define POLLOUT   0x004   // Writing now will not block.
    16111611    */
    1612    
     1612
    16131613    bool terminate = false;
    16141614    // check for thread terminate condition using get_state()
    16151615    state_t currstate= get_state();
    16161616    int poll_status= 0;
    1617     const unsigned int number_poll_sockets= 1; 
     1617    const unsigned int number_poll_sockets= 1;
    16181618    struct sockaddr_in6 peer_address;
    16191619    struct sockaddr_in peer_address_v4;
     
    16261626    while(! (terminate= (currstate==STATE_ABORT || currstate==STATE_STOP) ) )
    16271627    {
    1628       // wait on number_poll_sockets (main drm socket) 
     1628      // wait on number_poll_sockets (main drm socket)
    16291629      // for the events specified above for sleep_time (in ms)
    16301630      poll_status= poll(&poll_fd, number_poll_sockets, tpparam.sleep_time);
    16311631      if (poll_fd.revents & POLLERR) // Error condition
    16321632      {
    1633         if (errno != EINTR) 
     1633        if (errno != EINTR)
    16341634        {
    16351635          ERRCLog(tpparam.name, "Poll caused error " << strerror(errno) << " - indicated by revents");
     
    16411641
    16421642      }
    1643       if (poll_fd.revents & POLLHUP) // Hung up 
     1643      if (poll_fd.revents & POLLHUP) // Hung up
    16441644      {
    16451645        ERRCLog(tpparam.name, "Poll hung up");
     
    16511651        return;
    16521652      }
    1653      
     1653
    16541654      switch (poll_status)
    16551655      {
     
    16631663            EVLog(tpparam.name, "Poll status: " << strerror(errno));
    16641664          }
    1665            
     1665
    16661666          break;
    16671667
    16681668        case 0:
    16691669#ifdef DEBUG_HARD
    1670           Log(DEBUG_LOG,LOG_UNIMP, tpparam.name, 
     1670          Log(DEBUG_LOG,LOG_UNIMP, tpparam.name,
    16711671              "Listen Thread - Poll timed out after " << tpparam.sleep_time << " ms.");
    16721672#endif
     
    16821682      } // end switch
    16831683
    1684       // after a successful accept call, 
     1684      // after a successful accept call,
    16851685      // accept stores the address information of the connecting party
    16861686      // in peer_address and the size of its address in addrlen
     
    17201720        // allocated peer_assoc will be stored in connmap
    17211721        AssocData* peer_assoc = new(nothrow) AssocData(conn_socket, addr,
    1722                                                        plibconf.getpar<bool>(protlibconf_ipv4_only) ? 
     1722                                                       plibconf.getpar<bool>(protlibconf_ipv4_only) ?
    17231723                                                       appladdress(own_address_v4,IPPROTO_TCP) : appladdress(own_address,IPPROTO_TCP) );
    17241724        bool insert_success= false;
     
    17311731          unlock(); // uninstall_cleanup(1);
    17321732        }
    1733        
    1734        
     1733
     1734
    17351735        if (insert_success == false) // not inserted into connmap
    17361736        {
    17371737          ERRCLog(tpparam.name, "Cannot insert AssocData for socket " << conn_socket
    1738               << ", " << addr.get_ip_str() << ", port #" 
     1738              << ", " << addr.get_ip_str() << ", port #"
    17391739              << addr.get_port() << " into connection map, aborting connection...");
    17401740
    17411741          // abort connection, delete its AssocData
    17421742          close (conn_socket);
    1743           if (peer_assoc) 
    1744           { 
     1743          if (peer_assoc)
     1744          {
    17451745            delete peer_assoc;
    17461746            peer_assoc= 0;
    1747           }             
     1747          }
    17481748        } //end __else(connmap.insert());__
    17491749        else
     
    17531753        }
    17541754      } // end __else (connsocket)__
    1755      
     1755
    17561756      // get new thread state
    17571757      currstate= get_state();
     
    17611761    close(master_listener_socket);
    17621762    return;
    1763 } // end listen_for_connections()   
     1763} // end listen_for_connections()
    17641764
    17651765
     
    17831783 * @param nr number of current thread instance
    17841784 */
    1785 void 
     1785void
    17861786TPoverTCP::main_loop(uint32 nr)
    17871787{
     
    17891789  // get internal queue for messages from receiver_thread
    17901790  FastQueue* fq = get_fqueue();
    1791   if (!fq) 
     1791  if (!fq)
    17921792  {
    17931793    ERRCLog(tpparam.name, "Cannot find message queue");
     
    17991799  // start master listener thread
    18001800  pthread_t master_listener_thread_ID;
    1801   int pthread_status= pthread_create(&master_listener_thread_ID, 
    1802                                      NULL, // NULL: default attributes: thread is joinable and has a 
     1801  int pthread_status= pthread_create(&master_listener_thread_ID,
     1802                                     NULL, // NULL: default attributes: thread is joinable and has a
    18031803                                     //       default, non-realtime scheduling policy
    18041804                                     master_listener_thread_starter,
     
    18181818
    18191819  // check whether this thread is signaled for termination
    1820   while( currstate!=STATE_ABORT && currstate!=STATE_STOP ) 
     1820  while( currstate!=STATE_ABORT && currstate!=STATE_STOP )
    18211821  {
    18221822    // poll internal message queue (blocking)
     
    18431843        else
    18441844          ERRCLog(tpparam.name, "unexpected internal message:" << internalmsg->get_msgtype());
    1845          
     1845
    18461846        delete internalmsg;
    18471847      }
     
    18651865  // do not accept any more messages
    18661866  fq->shutdown();
    1867   // terminate all receiver and sender threads that are still active 
     1867  // terminate all receiver and sender threads that are still active
    18681868  terminate_all_threads();
    18691869}
  • protlib/trunk/src/tp_over_udp.cpp

    r6570 r6765  
    66/// $HeadURL$
    77// ===========================================================
    8 //                     
     8//
    99// Copyright (C) 2005-2007, all rights reserved by
    1010// - Institute of Telematics, Universitaet Karlsruhe (TH)
     
    1212// More information and contact:
    1313// https://projekte.tm.uka.de/trac/NSIS
    14 //                     
     14//
    1515// This program is free software; you can redistribute it and/or modify
    1616// it under the terms of the GNU General Public License as published by
     
    9494 *  @note the netmsg is deleted by the send() method when it is not used anymore
    9595 */
    96 void 
     96void
    9797TPoverUDP::send (NetMsg * netmsg, const address & in_addr, bool use_existing_connection, const address *local_addr)
    9898{
     
    103103  if (local_addr)
    104104    own_addr = dynamic_cast<const hostaddress *>(local_addr);
    105  
     105
    106106  if (!addr) return;
    107  
     107
    108108  // Do it independently from master thread
    109109  udpsend(netmsg, addr, own_addr);
     
    114114 *
    115115 * @param netmsg   message to send
    116  * @param addr     transport endpoint address 
     116 * @param addr     transport endpoint address
    117117 *
    118118 * @note           both parameters are deleted after the message was sent
    119119 */
    120 void 
     120void
    121121TPoverUDP::udpsend (NetMsg * netmsg, appladdress * addr, const hostaddress *local_addr)
    122122{
     
    130130  int ret = 0;
    131131
    132    
     132
    133133  if (addr)
    134134  {
     
    154154  struct sockaddr_in6 dest_address;
    155155  struct sockaddr_in dest_address_v4;
    156  
     156
    157157  if  ( plibconf.getpar<bool>(protlibconf_ipv4_only) )
    158158  {
     
    172172  {
    173173          addr->convert_to_ipv6();
    174           in6_addr ip6addr; 
     174          in6_addr ip6addr;
    175175          // convert to v4-mapped address if necessary! (we use dual-stack IPv4/IPv6 socket)
    176176          addr->get_ip(ip6addr);
     
    214214  else
    215215          header.msg_name = &dest_address;
    216   header.msg_namelen= plibconf.getpar<bool>(protlibconf_ipv4_only) ? sizeof(dest_address_v4) : sizeof(dest_address); 
     216  header.msg_namelen= plibconf.getpar<bool>(protlibconf_ipv4_only) ? sizeof(dest_address_v4) : sizeof(dest_address);
    217217  header.msg_control=NULL;
    218218  header.msg_controllen=0;
     
    231231  while (master_listener_socket == -1)
    232232  {
    233     struct timespec sleeptime; 
     233    struct timespec sleeptime;
    234234    sleeptime.tv_sec= 0; sleeptime.tv_nsec= 100000000L;
    235  
     235
    236236    DLog(tpparam.name, "socket not yet ready for sending - sending deferred (" << sleeptime.tv_nsec/1000000L << " ms)");
    237     struct timespec remainingtime; 
     237    struct timespec remainingtime;
    238238    nanosleep(&sleeptime,&remainingtime);
    239239    DLog(tpparam.name, "retrying to send");
     
    246246  // send UDP packet
    247247  DLog(tpparam.name, "SEND to " << *addr);
    248   ret= sendmsg(master_listener_socket,&header,MSG_DONTWAIT); 
     248  ret= sendmsg(master_listener_socket,&header,MSG_DONTWAIT);
    249249
    250250  // free ancilliary data allocated by protlib::util::set_ancillary_data()
     
    252252  header.msg_control = NULL; // ... just in case
    253253
    254   if (ret<0) 
     254  if (ret<0)
    255255    ERRCLog(tpparam.name, "Socket Send failed! - error (" << errno << "):" << strerror(errno));
    256256  if (debug_pdu)
     
    261261           "PDU debugging enabled - Sent:" << hexdump.str ());
    262262    }
    263      
     263
    264264  if (ret < 0)
    265265    {
     
    267267      //    break;
    268268    } // end if (ret < 0)
    269      
    270          
     269
     270
    271271      // *** note: netmsg is deleted here ***
    272   delete netmsg;     
    273 
    274      
    275   // Throwing an exception within a critical section does not 
     272  delete netmsg;
     273
     274
     275  // Throwing an exception within a critical section does not
    276276  // unlock the mutex.
    277277
     
    291291  // *** delete address ***
    292292  delete addr;
    293 } // end TPoverUDP::udpsend 
     293} // end TPoverUDP::udpsend
    294294
    295295
    296296
    297297/**
    298  * IPv4 catcher thread starter: 
    299  * just a static starter method to allow starting the 
     298 * IPv4 catcher thread starter:
     299 * just a static starter method to allow starting the
    300300 * actual master_listener_thread() method.
    301301 *
     
    328328  own_address.sin6_flowinfo= 0;
    329329  own_address.sin6_port = htons(tpparam.port); // use port number in param structure
    330   // accept incoming connections on all interfaces 
     330  // accept incoming connections on all interfaces
    331331  own_address.sin6_addr = in6addr_any;
    332332  own_address.sin6_scope_id= 0;
     
    335335  own_address_v4.sin_port = htons(tpparam.port); // use port number in param structure
    336336  own_address_v4.sin_addr.s_addr = INADDR_ANY;
    337  
     337
    338338  // create a listening socket
    339339  if (plibconf.getpar<bool>(protlibconf_ipv4_only))
     
    357357    ERRCLog(tpparam.name, "Could not set socket option SO_REUSEADDR:" << strerror(errno));
    358358  }
    359  
     359
    360360  // TODO: insert multicast socket options/calls here
    361    
     361
    362362  // bind the newly created socket to a specific address
    363363  // bind the newly created socket to a specific address
     
    368368          sizeof(own_address_v4) : sizeof(own_address);
    369369
    370   int bind_status = bind(master_listener_socket,
     370  int bind_status = ::bind(master_listener_socket,
    371371                         ownsockaddr,
    372372                         ownsockaddr_len);
    373373  if (bind_status)
    374   { 
    375           ERRCLog(tpparam.name, "Binding to " 
    376               << (plibconf.getpar<bool>(protlibconf_ipv4_only) ? 
     374  {
     375          ERRCLog(tpparam.name, "Binding to "
     376              << (plibconf.getpar<bool>(protlibconf_ipv4_only) ?
    377377                  inet_ntop(AF_INET, &own_address_v4.sin_addr, in6_addrstr_loc, INET6_ADDRSTRLEN) :
    378378                  inet_ntop(AF_INET6, &own_address.sin6_addr, in6_addrstr_loc, INET6_ADDRSTRLEN))
     
    389389  struct pollfd poll_fd;
    390390  poll_fd.fd = master_listener_socket;
    391   poll_fd.events = POLLIN | POLLPRI; 
     391  poll_fd.events = POLLIN | POLLPRI;
    392392  poll_fd.revents = 0;
    393393  /*
    394     #define POLLIN      0x001   // There is data to read. 
    395     #define POLLPRI     0x002   // There is urgent data to read. 
    396     #define POLLOUT     0x004   // Writing now will not block. 
     394    #define POLLIN      0x001   // There is data to read.
     395    #define POLLPRI     0x002   // There is urgent data to read.
     396    #define POLLOUT     0x004   // Writing now will not block.
    397397  */
    398      
     398
    399399  bool terminate = false;
    400400  // check for thread terminate condition using get_state()
    401401  state_t currstate= get_state();
    402402  int poll_status= 0;
    403   const unsigned int number_poll_sockets= 1; 
     403  const unsigned int number_poll_sockets= 1;
    404404  struct sockaddr_in6 peer_address;
    405405  struct sockaddr_in peer_address_v4;
     
    410410  while(! (terminate= (currstate==STATE_ABORT || currstate==STATE_STOP) ) )
    411411  {
    412       // wait on number_poll_sockets (main drm socket) 
     412      // wait on number_poll_sockets (main drm socket)
    413413      // for the events specified above for sleep_time (in ms) tpparam.sleep_time
    414414      poll_status= poll(&poll_fd, number_poll_sockets, 250);
    415415      if (poll_fd.revents & POLLERR) // Error condition
    416416        {
    417           if (errno != EINTR) 
     417          if (errno != EINTR)
    418418            {
    419419              ERRCLog(tpparam.name, "Poll caused error " << strerror(errno) << " - indicated by revents");
     
    423423              EVLog(tpparam.name, "poll(): " << strerror(errno));
    424424            }
    425              
     425
    426426        }
    427       if (poll_fd.revents & POLLHUP) // Hung up 
     427      if (poll_fd.revents & POLLHUP) // Hung up
    428428        {
    429429          ERRCLog(tpparam.name, "Poll hung up");
     
    435435          return;
    436436        }
    437          
     437
    438438      switch (poll_status)
    439439        {
     
    447447              EVLog(tpparam.name, "Poll status: " << strerror(errno));
    448448            }
    449                  
     449
    450450          break;
    451                  
     451
    452452        case 0:
    453453#ifdef DEBUG_HARD
    454           Log(DEBUG_LOG,LOG_UNIMP, tpparam.name, 
     454          Log(DEBUG_LOG,LOG_UNIMP, tpparam.name,
    455455              "Listen Thread - Poll timed out after " << tpparam.sleep_time << " ms.");
    456456#endif
     
    458458          continue;
    459459          break;
    460                  
     460
    461461        default:
    462462#ifdef DEBUG_HARD
     
    472472      if ((poll_fd.revents & POLLIN) || (poll_fd.revents & POLLPRI)) {
    473473
    474          
     474
    475475        // in peer_address and the size of its address in addrlen
    476476        peer_address_len= plibconf.getpar<bool>(protlibconf_ipv4_only) ? sizeof(peer_address_v4) : sizeof(peer_address);
    477                  
     477
    478478        //Build us a NetMsg
    479479        NetMsg *netmsg=0;
    480480        netmsg = new NetMsg (NetMsg::max_size);
    481              
    482              
    483              
     481
     482
     483
    484484        /// receive data from socket buffer (recv will not block)
    485485        int ret = recvfrom (master_listener_socket,
    486                             netmsg->get_buffer (), NetMsg::max_size, 0, 
     486                            netmsg->get_buffer (), NetMsg::max_size, 0,
    487487                            plibconf.getpar<bool>(protlibconf_ipv4_only) ? reinterpret_cast<struct sockaddr *>(&peer_address_v4) : reinterpret_cast<struct sockaddr *>(&peer_address),
    488488                            &peer_address_len);
    489          
    490         if (ret) 
     489
     490        if (ret)
    491491        {
    492492          DLog(tpparam.name, "received " << ret << " bytes of UDP data");
     
    504504         *  all should be well. At least until now.                   *
    505505         **************************************************************/
    506              
     506
    507507        // Build peer_adr and own_addr
    508508        appladdress* peer_addr = new appladdress;
     
    520520
    521521        appladdress* own_addr = new appladdress();
    522              
     522
    523523        // Log the sender peer and write to peer_addr
    524524        char source_addr[INET6_ADDRSTRLEN+1];
     
    535535        TPMsg *tpmsg=
    536536          new (nothrow) TPMsg (netmsg, peer_addr, own_addr);
    537              
     537
    538538        DLog (tpparam.name,
    539              "recvthread - receipt of GIST PDU now complete, sending msg#" << tpmsg->get_id() << " to signaling module");             
    540              
     539             "recvthread - receipt of GIST PDU now complete, sending msg#" << tpmsg->get_id() << " to signaling module");
     540
    541541        if (tpmsg == NULL || !tpmsg->send(tpparam.source, tpparam.dest))
    542542          {
     
    546546            if (netmsg)
    547547              delete netmsg;
    548                  
    549           } 
    550            
     548
     549          }
     550
    551551      }
    552      
     552
    553553      // get new thread state
    554554      currstate= get_state();
     
    561561
    562562}
    563      
     563
    564564
    565565TPoverUDP::~TPoverUDP ()
    566566{
    567567  init = false;
    568  
     568
    569569  Log (DEBUG_LOG, LOG_NORMAL, tpparam.name, "Destructor called");
    570  
     570
    571571}
    572572
     
    579579 * @param nr number of current thread instance
    580580 */
    581 void 
     581void
    582582TPoverUDP::main_loop (uint32 nr)
    583583{
     
    585585  int pthread_status = 0;
    586586
    587      
     587
    588588  // start UDP listener thread
    589589  pthread_t listener_thread_ID;
     
    597597    }
    598598  else
    599          
     599
    600600    Log(INFO_LOG,LOG_NORMAL, tpparam.name, color[green] << "Listening at port #" << tpparam.port << color[off]);
    601      
    602      
    603      
     601
     602
     603
    604604  // define max latency for thread reaction on termination/stop signal
    605605  state_t currstate = get_state ();
    606      
     606
    607607  // check whether this thread is signaled for termination
    608608  while (currstate != STATE_ABORT && currstate != STATE_STOP)
    609609    {
    610          
     610
    611611      // get thread state
    612612      currstate = get_state ();
    613          
     613
    614614      sleep(4);
    615          
     615
    616616    }                           // end while
    617      
     617
    618618  if (currstate == STATE_STOP)
    619619    {
     
    622622           "Asked to abort, stopping all receiver threads");
    623623    }                           // end if stopped
    624      
     624
    625625  // do not accept any more messages
    626   // terminate all receiver and sender threads that are still active 
     626  // terminate all receiver and sender threads that are still active
    627627  //terminate_all_threads ();
    628628}
    629    
    630    
    631 void 
    632 TPoverUDP::terminate(const address& addr) 
     629
     630
     631void
     632TPoverUDP::terminate(const address& addr)
    633633{
    634634        // no connection oriented protocol, nothing to terminate
    635635}
    636    
     636
    637637}                               // end namespace protlib
    638638
  • protlib/trunk/src/tp_over_uds.cpp

    r6265 r6765  
    66/// $HeadURL$
    77// ===========================================================
    8 //                     
     8//
    99// Copyright (C) 2005-2007, all rights reserved by
    1010// - Institute of Telematics, Universitaet Karlsruhe (TH)
     
    1212// More information and contact:
    1313// https://projekte.tm.uka.de/trac/NSIS
    14 //                     
     14//
    1515// This program is free software; you can redistribute it and/or modify
    1616// it under the terms of the GNU General Public License as published by
     
    2727//
    2828// ===========================================================
    29  
     29
    3030extern "C"
    3131{
     
    7575
    7676
    77 /** get_connection_to() checks for already existing connections. 
    78  *  If a connection exists, it returns "AssocData" 
     77/** get_connection_to() checks for already existing connections.
     78 *  If a connection exists, it returns "AssocData"
    7979 *  and saves it in "connmap" for further use
    8080 *  If no connection exists, a new connection to "addr"
    8181 *  is created.
    8282 */
    83 AssocDataUDS* 
     83AssocDataUDS*
    8484TPoverUDS::get_connection_to(udsaddress& addr)
    8585{
     
    9898  int new_socket;
    9999  // loop until timeout is exceeded: TODO: check applicability of loop
    100   do 
     100  do
    101101  {
    102102    // check for existing connections to addr
     
    106106    // end critical section
    107107    unlock(); // uninstall_cleanup(1);
    108     if (assoc) 
     108    if (assoc)
    109109    {
    110110      // If not shut down then use it, else abort, wait and check again.
    111       if (!assoc->shutdown) 
     111      if (!assoc->shutdown)
    112112      {
    113113        return assoc;
     
    119119
    120120        return 0;
    121       } 
     121      }
    122122    } //end __if (assoc)__
    123     else 
    124     {
    125       Log(DEBUG_LOG,LOG_UNIMP,tpparam.name,"No existing connection to " 
     123    else
     124    {
     125      Log(DEBUG_LOG,LOG_UNIMP,tpparam.name,"No existing connection to "
    126126          << addr << " found, creating a new one.");
    127127    }
     
    135135      return 0;
    136136    }
    137    
     137
    138138    // Reuse ports, even if they are busy
    139139    int socketreuseflag= 1;
     
    151151    dest_address.sun_family= AF_UNIX;
    152152    strcpy(dest_address.sun_path, addr.get_udssocket().c_str());
    153      
     153
    154154    // connect the socket to the destination address
    155155    int connect_status = connect(new_socket,
     
    157157                                 sizeof(dest_address));
    158158
    159     // connects to the listening_port of the peer's masterthread   
     159    // connects to the listening_port of the peer's masterthread
    160160    if (connect_status != 0)
    161161    {
    162162        Log(ERROR_LOG,LOG_NORMAL, tpparam.name,"Connect to " << addr.get_udssocket() << "failed: [" << color[red] << strerror(errno) << color[off] << "]");
    163      
     163
    164164      throw TPErrorConnectSetupFail();
    165165    }
    166166
    167    
     167
    168168    //struct sockaddr_un own_address;
    169169    //socklen_t own_address_len= sizeof(own_address);
     
    171171
    172172    Log(DEBUG_LOG,LOG_UNIMP, tpparam.name,">>--Connect-->> to " << addr << " from " << udsaddress(new_socket));
    173    
     173
    174174    // create new AssocData record (will copy addr)
    175175    assoc = new(nothrow) AssocDataUDS(new_socket, addr, udsaddress(new_socket));
    176176
    177177    // if assoc could be successfully created, insert it into ConnectionMap
    178     if (assoc) 
     178    if (assoc)
    179179    {
    180180      bool insert_success= false;
     
    186186      unlock(); // uninstall_cleanup(1);
    187187
    188       if (insert_success == true) 
     188      if (insert_success == true)
    189189      {
    190190#ifdef _DEBUG
    191191        Log(DEBUG_LOG,LOG_UNIMP, tpparam.name, "Connected to " << addr << " via socket " << new_socket);
    192192
    193                
     193
    194194#endif
    195195
     
    203203        else
    204204          Log(ERROR_LOG,LOG_CRIT,tpparam.name,"get_connection_to: could not get memory for internal msg");
    205       } 
    206       else 
     205      }
     206      else
    207207      {
    208208        // delete data and abort
    209209        Log(ERROR_LOG,LOG_CRIT, tpparam.name, "Cannot insert AssocData for socket " << new_socket << ", "<< addr << " into connection map, aborting connection");
    210                
     210
    211211        // abort connection, delete its AssocData
    212212        close (new_socket);
    213         if (assoc) 
    214         { 
    215           delete assoc; 
     213        if (assoc)
     214        {
     215          delete assoc;
    216216          assoc= 0;
    217217        }
    218218        return assoc;
    219       } // end else connmap.insert                     
    220      
     219      } // end else connmap.insert
     220
    221221    } // end "if (assoc)"
    222   } 
     222  }
    223223  while (wait_cond(ts)!=ETIMEDOUT);
    224224
     
    242242#endif
    243243
    244   // Create a new AssocData-pointer 
     244  // Create a new AssocData-pointer
    245245  AssocDataUDS* assoc = NULL;
    246246
     
    253253  lock(); // install_cleanup_thread_lock(TPoverUDS, this);
    254254  assoc= connmap.lookup(*addr);
    255   if (assoc) 
     255  if (assoc)
    256256  {
    257257    Log(EVENT_LOG,LOG_NORMAL,tpparam.name,thisproc<<"got request to shutdown connection for peer " << addr);
    258258    // If not shut down then use it, else abort, wait and check again.
    259     if (!assoc->shutdown) 
     259    if (!assoc->shutdown)
    260260    {
    261261      if (assoc->socketfd)
     
    268268        else
    269269        {
    270           Log(EVENT_LOG,LOG_NORMAL,tpparam.name,thisproc<<"initiated closing of connection for peer " << addr << ". Shutdown (write) on socket "<< assoc->socketfd );     
     270          Log(EVENT_LOG,LOG_NORMAL,tpparam.name,thisproc<<"initiated closing of connection for peer " << addr << ". Shutdown (write) on socket "<< assoc->socketfd );
    271271        }
    272272      }
     
    275275    else
    276276      Log(EVENT_LOG,LOG_NORMAL,tpparam.name,thisproc<<"connection for peer " << addr << " is already in mode shutdown");
    277      
     277
    278278  }
    279279  else
     
    336336      create_new_sender_thread(sender_thread_queue);
    337337      // remember queue for later use
    338    
     338
    339339      //pair<sender_thread_queuemap_t::iterator, bool> tmpinsiterator=
    340340      senderthread_queuemap.insert( pair<udsaddress,FastQueue*> (*addr,sender_thread_queue) );
     
    345345  else
    346346  { // we have a sender thread, use stored queue from map
    347     destqueue= it->second; 
     347    destqueue= it->second;
    348348  }
    349349
    350350  unlock();
    351    
     351
    352352  // send a send_data message to it (if we have a destination queue)
    353353  if (destqueue)
    354354  {
    355355    // both parameters will be freed after message was sent!
    356    
     356
    357357      //DLog(tpparam.name, "Sending self-message for socket " << addr->get_udssocket().c_str());
    358358
     
    371371    else
    372372      DLog(tpparam.name,"no active sender thread found " << *addr << " - but policy forbids to set up a new connection, will drop data");
    373      
     373
    374374    // cannot send data, so we must drop it
    375375    delete netmsg;
     
    382382 *
    383383 * @param netmsg - message to send
    384  * @param addr   - transport endpoint address 
     384 * @param addr   - transport endpoint address
    385385 *
    386  * @note if no connection exists, creates a new one 
     386 * @note if no connection exists, creates a new one
    387387 * @note both parameters are deleted after the message was sent
    388388 */
    389389void
    390390TPoverUDS::udssend(NetMsg* netmsg, udsaddress* addr)
    391 {                       
     391{
    392392#ifndef _NO_LOGGING
    393393  const char *const thisproc="sender   - ";
     
    399399  int ret= 0;
    400400
    401   // Create a new AssocData-pointer 
     401  // Create a new AssocData-pointer
    402402  AssocDataUDS* assoc = NULL;
    403  
     403
    404404  // tp.cpp checks for initialisation of tp and correctness of
    405405  // msgsize, protocol and ip,
     
    412412  } else {
    413413      Log(ERROR_LOG,LOG_CRIT, tpparam.name, thisproc << "address pointer is NULL");
    414       result= UDS_SEND_FAILURE;   
     414      result= UDS_SEND_FAILURE;
    415415      throw TPErrorInternal();
    416416  }
    417    
    418 
    419 
    420   // check for existing connections, 
    421   // if a connection exists, return its AssocData 
     417
     418
     419
     420  // check for existing connections,
     421  // if a connection exists, return its AssocData
    422422  // and save it in assoc for further use
    423423  // if no connection exists, create a new one (in get_connection_to()).
     
    464464    for (uint32 i=0;i<msgsize;i++)
    465465    {
    466       cout << "send_buf: " << i << " : "; 
     466      cout << "send_buf: " << i << " : ";
    467467      if ( isalnum(*(netmsg->get_buffer()+i)) )
    468468        cout << "'" << *(netmsg->get_buffer()+i) << "' (0x" << hex << (unsigned short) *(netmsg->get_buffer()+i) << dec << ")" ;
     
    481481
    482482    // socket send
    483     ret= ::send(assoc->socketfd, 
    484                 netmsg->get_buffer() + bytes_sent, 
    485                 msgsize - bytes_sent, 
     483    ret= ::send(assoc->socketfd,
     484                netmsg->get_buffer() + bytes_sent,
     485                msgsize - bytes_sent,
    486486                MSG_NOSIGNAL);
    487487
     
    495495    }
    496496
    497     if (ret < 0) 
     497    if (ret < 0)
    498498    {
    499499      result= UDS_SEND_FAILURE;
     
    505505  // *** note: netmsg is deleted here ***
    506506  delete netmsg;
    507  
    508   // Throwing an exception within a critical section does not 
     507
     508  // Throwing an exception within a critical section does not
    509509  // unlock the mutex.
    510510
     
    515515
    516516    throw TPErrorSendFailed();
    517    
     517
    518518    // There is no special errorcode for sending failed
    519519    // in tp.h, there are only these:
     
    532532  if (!assoc) {
    533533    // no connection
    534    
     534
    535535    Log(ERROR_LOG,LOG_NORMAL, tpparam.name, thisproc << "cannot get connection to " << *addr);
    536536
     
    539539    throw TPErrorUnreachable(); // should be no assoc found
    540540  } // end "if (!assoc)"
    541  
     541
    542542  // *** delete address ***
    543543  delete addr;
    544544}
    545  
     545
    546546/* this thread waits for an internal message that either:
    547547 * - requests transmission of a packet
     
    549549 * @param argp points to the thread queue for internal messages
    550550 */
    551 void 
     551void
    552552TPoverUDS::sender_thread(void *argp)
    553553{
     
    572572  {
    573573    internalmsg= dynamic_cast<TPoverUDSMsg*>(internal_thread_msg);
    574    
     574
    575575    if (internalmsg == 0)
    576576    {
    577       Log(ERROR_LOG,LOG_NORMAL, tpparam.name, methodname << "received not an TPoverUDSMsg but a" << internal_thread_msg->get_type_name());     
     577      Log(ERROR_LOG,LOG_NORMAL, tpparam.name, methodname << "received not an TPoverUDSMsg but a" << internal_thread_msg->get_type_name());
    578578    }
    579579    else
    580580    if (internalmsg->get_msgtype() == TPoverUDSMsg::send_data)
    581581    {
    582      
     582
    583583        //DLog(tpparam.name, "Got a send request for socket " << *(internalmsg->get_appladdr()));
    584584
     
    591591      {
    592592        Log(ERROR_LOG,LOG_NORMAL, tpparam.name, methodname << "problem with passed arguments references, they point to 0");
    593       } 
     593      }
    594594    }
    595595    else
     
    597597    {
    598598      terminate= true;
    599     } 
     599    }
    600600  } // end while
    601  
     601
    602602  Log(EVENT_LOG,LOG_NORMAL, tpparam.name, methodname << "<" << pthread_self() << "> terminated connection.");
    603603}
    604604
    605605
    606 /** receiver thread listens at a TCP socket for incoming PDUs 
     606/** receiver thread listens at a TCP socket for incoming PDUs
    607607 *  and passes complete PDUs to the coordinator. Incomplete
    608608 *  PDUs due to aborted connections or buffer overflows are discarded.
    609609 *  @param argp - assoc data and flags sig_terminate and terminated
    610  * 
     610 *
    611611 *  @note this is a static member function, so you cannot use class variables
    612612 */
    613 void 
     613void
    614614TPoverUDS::receiver_thread(void *argp)
    615615{
     
    622622  uint32 bytes_received = 0;
    623623  TPMsg* tpmsg= NULL;
    624  
     624
    625625  // argument parsing - start
    626626  if (receiver_thread_argp == 0)
     
    652652  {
    653653    Log(ERROR_LOG,LOG_CRIT, tpparam.name, methodname << "No peer assoc available - pointer is NULL");
    654    
     654
    655655    return;
    656656  }
     
    659659  {
    660660    Log(ERROR_LOG,LOG_CRIT, tpparam.name, methodname << "No peer address available for socket " << conn_socket << ", exiting.");
    661    
     661
    662662    return;
    663663  }
     
    665665#ifdef _DEBUG
    666666  Log(DEBUG_LOG,LOG_UNIMP, tpparam.name, methodname <<
    667       "Preparing to wait for data at socket " 
     667      "Preparing to wait for data at socket "
    668668      << conn_socket << " from " << receiver_thread_argp->peer_assoc->peer);
    669669#endif
     
    674674  bool pdu_complete= false; // when to terminate inner loop
    675675
    676   /* maybe use this to create a new pdu, 
     676  /* maybe use this to create a new pdu,
    677677    /// constructor
    678678    contextlistpdu(type_t t, subtype_t st, uint32 fc, uint32 numobj = 0);
    679   */ 
     679  */
    680680
    681681  // activate O_NON_BLOCK  for recv on socket conn_socket
    682682  fcntl(conn_socket,F_SETFL, O_NONBLOCK);
    683    
     683
    684684  // set options for polling
    685   const unsigned int number_poll_sockets= 1; 
     685  const unsigned int number_poll_sockets= 1;
    686686  struct pollfd poll_fd;
    687687  // have to set structure before poll call
    688688  poll_fd.fd = conn_socket;
    689   poll_fd.events = POLLIN | POLLPRI; 
     689  poll_fd.events = POLLIN | POLLPRI;
    690690
    691691  int poll_status;
     
    697697  size_t trailingbytes= 0;
    698698  bool skiprecv= false;
    699   // loop until we receive a terminate signal (read-only var for this thread) 
     699  // loop until we receive a terminate signal (read-only var for this thread)
    700700  // or get an error from socket read
    701701  while( receiver_thread_argp->sig_terminate == false )
     
    731731      recv_error= true;
    732732    }
    733    
     733
    734734    // loops until PDU is complete
    735735    // >>>>>>>>>>>>>>>>>>>>>>>>>>> while >>>>>>>>>>>>>>>>>>>>>>>>
    736     while (!pdu_complete && 
    737            !recv_error && 
     736    while (!pdu_complete &&
     737           !recv_error &&
    738738           !receiver_thread_argp->sig_terminate)
    739739    {
     
    742742        // read from TCP socket or return after sleep_time
    743743        poll_status= poll(&poll_fd, number_poll_sockets, tpparam.sleep_time);
    744        
     744
    745745        if (receiver_thread_argp->sig_terminate)
    746746        {
     
    776776          }
    777777        }
    778        
    779         if (poll_fd.revents & POLLHUP) // Hung up 
     778
     779        if (poll_fd.revents & POLLHUP) // Hung up
    780780        {
    781781          Log(EVENT_LOG,LOG_CRIT, tpparam.name, methodname << "Poll hung up");
    782782          recv_error= true;
    783783        }
    784        
     784
    785785        if (poll_fd.revents & POLLNVAL) // Invalid request: fd not open
    786786        {
     
    788788          recv_error= true;
    789789        }
    790        
     790
    791791        // check status (return value) of poll call
    792792        switch (poll_status)
     
    802802              recv_error= true;
    803803            }
    804            
     804
    805805            continue; // next while iteration
    806806            break;
    807            
     807
    808808          case 0:
    809809#ifdef DEBUG_HARD
     
    812812            continue; // next while iteration
    813813            break;
    814            
     814
    815815          default:
    816816#ifdef DEBUG_HARD
     
    822822
    823823        /// receive data from socket buffer (recv will not block)
    824         ret = recv(conn_socket, 
    825                    netmsg->get_buffer() + bytes_received, 
    826                    buffer_bytes_left, 
     824        ret = recv(conn_socket,
     825                   netmsg->get_buffer() + bytes_received,
     826                   buffer_bytes_left,
    827827                   0);
    828828
     
    845845          if (ret == 0)
    846846          {
    847             // this means that EOF is reached, 
     847            // this means that EOF is reached,
    848848            // other side has closed connection
    849849            Log(DEBUG_LOG,LOG_UNIMP, tpparam.name, methodname << "Other side (" << *peer_addr << ") closed connection for socket " << conn_socket);
     
    871871          }
    872872        }
    873       } // end if do not skip recv() statement     
     873      } // end if do not skip recv() statement
    874874
    875875      if (buffer_bytes_left < 0) ///< buffer space exhausted now
     
    908908      if (msgcontentlength_known && bytes_received-common_header_length >= msgcontentlength )
    909909      {
    910        
     910
    911911        pdu_complete= true;
    912912        if (bytes_received-common_header_length > msgcontentlength)
     
    949949      if (!tpmsg
    950950          || (!tpmsg->get_peeraddress())
    951           || (!tpmsg->send_to(tpparam.dest))) 
     951          || (!tpmsg->send_to(tpparam.dest)))
    952952      {
    953953        Log(ERROR_LOG,LOG_NORMAL, tpparam.name, methodname << "Cannot allocate/send TPMsg");
     
    967967        ostringstream hexdumpstr;
    968968        netmsg->hexdump(hexdumpstr,netmsg->get_buffer(),bytes_received);
    969         Log(DEBUG_LOG,LOG_NORMAL,tpparam.name,"Message too short to be a valid protocol header - dumping received bytes:" << hexdumpstr.str()); 
     969        Log(DEBUG_LOG,LOG_NORMAL,tpparam.name,"Message too short to be a valid protocol header - dumping received bytes:" << hexdumpstr.str());
    970970      }
    971971      // leave the outer loop
     
    977977  } // end while (thread not signalled for termination)
    978978
    979   Log(DEBUG_LOG,LOG_NORMAL, tpparam.name, methodname << "Thread <" << pthread_self() 
     979  Log(DEBUG_LOG,LOG_NORMAL, tpparam.name, methodname << "Thread <" << pthread_self()
    980980      << "> shutting down and closing socket " << receiver_thread_argp->peer_assoc->peer);
    981981
     
    10011001  // send message to main loop thread
    10021002  newmsg->send_to(tpparam.source);
    1003 } 
     1003}
    10041004
    10051005
    10061006/** this signals a terminate to a thread and wait for the thread to stop
    10071007 *  @note it is not safe to access any thread related data after this method returned,
    1008  *        because the receiver thread will initiate a cleanup_receiver_thread() method 
     1008 *        because the receiver thread will initiate a cleanup_receiver_thread() method
    10091009 *        which may erase all relevant thread data.
    10101010 */
    1011 void 
     1011void
    10121012TPoverUDS::stop_receiver_thread(AssocDataUDS* peer_assoc)
    10131013{
     
    10211021
    10221022  pthread_t thread_id=  peer_assoc->thread_ID;
    1023  
     1023
    10241024  // try to clean up receiver_thread_arg
    10251025  recv_thread_argmap_t::iterator recv_thread_arg_iter= recv_thread_argmap.find(thread_id);
    1026   receiver_thread_arg_t* recv_thread_argp= 
     1026  receiver_thread_arg_t* recv_thread_argp=
    10271027    (recv_thread_arg_iter != recv_thread_argmap.end()) ? recv_thread_arg_iter->second : 0;
    10281028  if (recv_thread_argp)
     
    10521052 *       is still valid
    10531053 */
    1054 void 
     1054void
    10551055TPoverUDS::cleanup_receiver_thread(AssocDataUDS* peer_assoc)
    10561056{
     
    10641064
    10651065  pthread_t thread_id=  peer_assoc->thread_ID;
    1066  
     1066
    10671067  // try to clean up receiver_thread_arg
    10681068  recv_thread_argmap_t::iterator recv_thread_arg_iter= recv_thread_argmap.find(thread_id);
    1069   receiver_thread_arg_t* recv_thread_argp= 
     1069  receiver_thread_arg_t* recv_thread_argp=
    10701070    (recv_thread_arg_iter != recv_thread_argmap.end()) ? recv_thread_arg_iter->second : 0;
    10711071  if (recv_thread_argp)
     
    11091109 *       is still valid, a lock is also required, because senderthread_queuemap is changed
    11101110 */
    1111 void 
     1111void
    11121112TPoverUDS::terminate_sender_thread(const AssocDataUDS* assoc)
    11131113{
     
    11221122  if (it != senderthread_queuemap.end())
    11231123  { // we have a sender thread: send a stop message to it
    1124     FastQueue* destqueue= it->second; 
     1124    FastQueue* destqueue= it->second;
    11251125    if (destqueue)
    11261126    {
     
    11451145 * main_loop()
    11461146 */
    1147 void 
     1147void
    11481148TPoverUDS::terminate_all_threads()
    11491149{
     
    11641164        terminate_argp->sig_terminate= true;
    11651165        // then wait for its termination
    1166         Log(DEBUG_LOG,LOG_NORMAL, tpparam.name, 
     1166        Log(DEBUG_LOG,LOG_NORMAL, tpparam.name,
    11671167            "Signaled receiver thread <" << terminate_iterator->first << "> for termination");
    1168        
     1168
    11691169        pthread_join(terminate_iterator->first, 0);
    1170        
     1170
    11711171        Log(DEBUG_LOG,LOG_NORMAL, tpparam.name, "Thread <" << terminate_iterator->first  << "> is terminated");
    11721172      }
    11731173      else
    1174         Log(DEBUG_LOG,LOG_NORMAL, tpparam.name, 
     1174        Log(DEBUG_LOG,LOG_NORMAL, tpparam.name,
    11751175            "Receiver thread <" << terminate_iterator->first << "> already terminated");
    1176        
     1176
    11771177      // cleanup all remaining argument structures of terminated threads
    11781178      delete terminate_argp;
     
    11801180      // terminate any related sender thread that is still running
    11811181      terminate_sender_thread(assoc);
    1182      
     1182
    11831183      connmap.erase(assoc);
    11841184      // delete assoc is not necessary, because connmap.erase() will do the job
     
    11891189
    11901190/**
    1191  * sender thread starter: 
    1192  * just a static starter method to allow starting the 
     1191 * sender thread starter:
     1192 * just a static starter method to allow starting the
    11931193 * actual sender_thread() method.
    11941194 *
     
    11991199{
    12001200  sender_thread_start_arg_t *sargp= static_cast<sender_thread_start_arg_t *>(argp);
    1201  
     1201
    12021202  //cout << "invoked sender_thread_Starter" << endl;
    12031203
     
    12241224
    12251225/**
    1226  * receiver thread starter: 
    1227  * just a static starter method to allow starting the 
     1226 * receiver thread starter:
     1227 * just a static starter method to allow starting the
    12281228 * actual receiver_thread() method.
    12291229 *
     
    12581258  pthread_t senderthreadid;
    12591259  // create new thread; (arg == 0) is handled by thread, too
    1260   int pthread_status= pthread_create(&senderthreadid, 
    1261                                      NULL, // NULL: default attributes: thread is joinable and has a 
     1260  int pthread_status= pthread_create(&senderthreadid,
     1261                                     NULL, // NULL: default attributes: thread is joinable and has a
    12621262                                     //       default, non-realtime scheduling policy
    12631263                                     TPoverUDS::sender_thread_starter,
     
    12661266  {
    12671267    Log(ERROR_LOG,LOG_CRIT, tpparam.name, "A new thread could not be created: " <<  strerror(pthread_status));
    1268    
     1268
    12691269    delete senderfqueue;
    12701270  }
     
    12751275TPoverUDS::create_new_receiver_thread(AssocDataUDS* peer_assoc)
    12761276{
    1277   receiver_thread_arg_t* argp= 
     1277  receiver_thread_arg_t* argp=
    12781278    new(nothrow) receiver_thread_arg(peer_assoc);
    1279  
     1279
    12801280  Log(EVENT_LOG,LOG_NORMAL, tpparam.name, "Starting new receiver thread...");
    12811281
    12821282  // create new thread; (arg == 0) is handled by thread, too
    1283   int pthread_status= pthread_create(&peer_assoc->thread_ID, 
    1284                                      NULL, // NULL: default attributes: thread is joinable and has a 
     1283  int pthread_status= pthread_create(&peer_assoc->thread_ID,
     1284                                     NULL, // NULL: default attributes: thread is joinable and has a
    12851285                                     //